Compare commits
3 Commits
5b3a035dcf
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ca60733ea0 | |||
|
|
4211d5cf39 | ||
| bd7712b28e |
@@ -70,7 +70,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
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.
|
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`.
|
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`.
|
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). En grupos de chicos la cuenta es del **adulto a cargo** (`person_guardians`): invitar a un chico vincula al adulto (y pasa al adulto una cuenta vieja del chico), y `linkedPersonWhere` le da acceso a todos sus chicos, también a los que se sumen después, sin reinvitar.
|
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.
|
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).
|
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.
|
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.
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
-- CreateEnum
|
|
||||||
CREATE TYPE "GroupAudience" AS ENUM ('ADULTS', 'KIDS');
|
|
||||||
|
|
||||||
-- AlterTable
|
|
||||||
ALTER TABLE "groups" ADD COLUMN "audience" "GroupAudience" NOT NULL DEFAULT 'ADULTS';
|
|
||||||
|
|
||||||
-- AlterTable
|
|
||||||
ALTER TABLE "plan_configs" ADD COLUMN "kids_groups" BOOLEAN NOT NULL DEFAULT false;
|
|
||||||
|
|
||||||
-- Pro includes kids groups from the start; Free keeps the default (false).
|
|
||||||
UPDATE "plan_configs" SET "kids_groups" = true WHERE "plan" = 'PRO';
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
-- CreateTable
|
|
||||||
CREATE TABLE "person_guardians" (
|
|
||||||
"child_id" TEXT NOT NULL,
|
|
||||||
"guardian_id" TEXT NOT NULL,
|
|
||||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
|
|
||||||
CONSTRAINT "person_guardians_pkey" PRIMARY KEY ("child_id","guardian_id")
|
|
||||||
);
|
|
||||||
|
|
||||||
-- CreateIndex
|
|
||||||
CREATE INDEX "person_guardians_guardian_id_idx" ON "person_guardians"("guardian_id");
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_child_id_fkey" FOREIGN KEY ("child_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- AddForeignKey
|
|
||||||
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_guardian_id_fkey" FOREIGN KEY ("guardian_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
||||||
|
|
||||||
-- The old guardian_name / guardian_phone become an adult of their own: an
|
|
||||||
-- existing person of the same teacher with that phone, or a new one (one per
|
|
||||||
-- teacher and phone, so siblings end up sharing it).
|
|
||||||
INSERT INTO "people" ("id", "created_by_id", "full_name", "phone", "created_at", "updated_at")
|
|
||||||
SELECT DISTINCT ON (k."created_by_id", k."guardian_phone")
|
|
||||||
gen_random_uuid()::text,
|
|
||||||
k."created_by_id",
|
|
||||||
COALESCE(NULLIF(TRIM(k."guardian_name"), ''), 'Adulto a cargo'),
|
|
||||||
k."guardian_phone",
|
|
||||||
CURRENT_TIMESTAMP,
|
|
||||||
CURRENT_TIMESTAMP
|
|
||||||
FROM (
|
|
||||||
SELECT "created_by_id", TRIM("guardian_phone") AS "guardian_phone", "guardian_name", "created_at"
|
|
||||||
FROM "people"
|
|
||||||
WHERE NULLIF(TRIM("guardian_phone"), '') IS NOT NULL
|
|
||||||
) k
|
|
||||||
WHERE NOT EXISTS (
|
|
||||||
SELECT 1 FROM "people" p
|
|
||||||
WHERE p."created_by_id" = k."created_by_id" AND p."phone" = k."guardian_phone"
|
|
||||||
)
|
|
||||||
ORDER BY k."created_by_id", k."guardian_phone", k."created_at";
|
|
||||||
|
|
||||||
INSERT INTO "person_guardians" ("child_id", "guardian_id")
|
|
||||||
SELECT c."id", g."id"
|
|
||||||
FROM "people" c
|
|
||||||
JOIN "people" g
|
|
||||||
ON g."created_by_id" = c."created_by_id"
|
|
||||||
AND g."phone" = TRIM(c."guardian_phone")
|
|
||||||
AND g."id" <> c."id"
|
|
||||||
WHERE NULLIF(TRIM(c."guardian_phone"), '') IS NOT NULL;
|
|
||||||
|
|
||||||
-- AlterTable
|
|
||||||
ALTER TABLE "people" DROP COLUMN "guardian_name",
|
|
||||||
DROP COLUMN "guardian_phone";
|
|
||||||
@@ -102,7 +102,6 @@ model PlanConfig {
|
|||||||
maxAttendees Int? @map("max_attendees")
|
maxAttendees Int? @map("max_attendees")
|
||||||
whatsappAutomations Boolean @map("whatsapp_automations")
|
whatsappAutomations Boolean @map("whatsapp_automations")
|
||||||
mpCharges Boolean @map("mp_charges")
|
mpCharges Boolean @map("mp_charges")
|
||||||
kidsGroups Boolean @default(false) @map("kids_groups")
|
|
||||||
updatedById String? @map("updated_by_id")
|
updatedById String? @map("updated_by_id")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ model Group {
|
|||||||
// Weekly WhatsApp automations, off until the teacher turns them on.
|
// Weekly WhatsApp automations, off until the teacher turns them on.
|
||||||
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
||||||
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
||||||
// KIDS: each student is a kid and the contact is the adult in charge.
|
|
||||||
audience GroupAudience @default(ADULTS)
|
|
||||||
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
||||||
createdById String @map("created_by_id")
|
createdById String @map("created_by_id")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
@@ -33,11 +31,6 @@ model Group {
|
|||||||
@@map("groups")
|
@@map("groups")
|
||||||
}
|
}
|
||||||
|
|
||||||
enum GroupAudience {
|
|
||||||
ADULTS
|
|
||||||
KIDS
|
|
||||||
}
|
|
||||||
|
|
||||||
enum WeekDay {
|
enum WeekDay {
|
||||||
MONDAY
|
MONDAY
|
||||||
TUESDAY
|
TUESDAY
|
||||||
@@ -90,6 +83,8 @@ model Person {
|
|||||||
fullName String @map("full_name")
|
fullName String @map("full_name")
|
||||||
email String?
|
email String?
|
||||||
phone String?
|
phone String?
|
||||||
|
guardianName String? @map("guardian_name")
|
||||||
|
guardianPhone String? @map("guardian_phone")
|
||||||
notes String?
|
notes String?
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
@@ -97,31 +92,11 @@ model Person {
|
|||||||
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
||||||
attendees Attendee[]
|
attendees Attendee[]
|
||||||
studentAccounts StudentAccountPerson[]
|
studentAccounts StudentAccountPerson[]
|
||||||
// As a kid: the adult in charge (one in v1, enforced by the code).
|
|
||||||
guardians PersonGuardian[] @relation("GuardianChild")
|
|
||||||
// As the adult in charge: their kids. An adult has no memberships of their own.
|
|
||||||
children PersonGuardian[] @relation("GuardianAdult")
|
|
||||||
|
|
||||||
@@index([createdById])
|
@@index([createdById])
|
||||||
@@map("people")
|
@@map("people")
|
||||||
}
|
}
|
||||||
|
|
||||||
// A kid (`child`) and the adult in charge (`guardian`), both people of the same
|
|
||||||
// teacher. The adult is who gets the messages and signs in to the student app;
|
|
||||||
// siblings share the same adult, so their phone is not duplicated on each kid.
|
|
||||||
model PersonGuardian {
|
|
||||||
childId String @map("child_id")
|
|
||||||
guardianId String @map("guardian_id")
|
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
|
||||||
|
|
||||||
child Person @relation("GuardianChild", fields: [childId], references: [id], onDelete: Cascade)
|
|
||||||
guardian Person @relation("GuardianAdult", fields: [guardianId], references: [id], onDelete: Cascade)
|
|
||||||
|
|
||||||
@@id([childId, guardianId])
|
|
||||||
@@index([guardianId])
|
|
||||||
@@map("person_guardians")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Membership of a person in a group. Status, attendance, fees and the absence
|
// Membership of a person in a group. Status, attendance, fees and the absence
|
||||||
// link (`notifyToken`) are per group.
|
// link (`notifyToken`) are per group.
|
||||||
model Attendee {
|
model Attendee {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { PlanFeature, ProblemDetails } from '@gruperly/shared';
|
import type { ProblemDetails } from '@gruperly/shared';
|
||||||
import { notFoundProblem } from './problem-details';
|
import { notFoundProblem } from './problem-details';
|
||||||
import { PROBLEM_DOMAIN } from './problem-domain';
|
import { PROBLEM_DOMAIN } from './problem-domain';
|
||||||
|
|
||||||
@@ -248,16 +248,13 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const PLAN_FEATURE_DETAIL: Record<PlanFeature, string> = {
|
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */
|
||||||
mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.',
|
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails {
|
||||||
whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
|
||||||
kidsGroups: 'Los grupos de chicos con adulto a cargo están disponibles en el plan Pro.',
|
|
||||||
};
|
|
||||||
|
|
||||||
/** A feature the owner's plan does not include (Mercado Pago, WhatsApp automations, kids groups). */
|
|
||||||
export function planFeatureRequiredProblem(feature: PlanFeature): ProblemDetails {
|
|
||||||
return paymentRequiredProblem({
|
return paymentRequiredProblem({
|
||||||
detail: PLAN_FEATURE_DETAIL[feature],
|
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',
|
code: 'plan_feature_required',
|
||||||
params: { feature },
|
params: { feature },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import type {
|
|||||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||||
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
|
||||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||||
@@ -75,7 +74,7 @@ export async function findStudentsAtRisk(
|
|||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { groupId, status: 'ACTIVE' },
|
where: { groupId, status: 'ACTIVE' },
|
||||||
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
|
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
||||||
}).then((rows) => rows.map(flattenPerson)),
|
}).then((rows) => rows.map(flattenPerson)),
|
||||||
db.attendance.findMany({
|
db.attendance.findMany({
|
||||||
where: { attendee: { groupId } },
|
where: { attendee: { groupId } },
|
||||||
@@ -112,8 +111,7 @@ export async function findStudentsAtRisk(
|
|||||||
atRisk.push({
|
atRisk.push({
|
||||||
attendeeId: attendee.id,
|
attendeeId: attendee.id,
|
||||||
fullName: attendee.fullName,
|
fullName: attendee.fullName,
|
||||||
// The number to reach them on: the adult in charge for a kid.
|
phone: attendee.phone,
|
||||||
phone: contactPhone(attendee),
|
|
||||||
riskLevel,
|
riskLevel,
|
||||||
consecutiveAbsences,
|
consecutiveAbsences,
|
||||||
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
|
import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
alreadyWaitlistedProblem,
|
alreadyWaitlistedProblem,
|
||||||
@@ -11,13 +11,9 @@ import prisma from '@/lib/prisma';
|
|||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import {
|
import {
|
||||||
alreadyInGroupProblem,
|
alreadyInGroupProblem,
|
||||||
contactPhone,
|
|
||||||
findPersonByPhone,
|
findPersonByPhone,
|
||||||
guardianRequiredProblem,
|
|
||||||
guardianSelect,
|
|
||||||
isUniqueViolation,
|
isUniqueViolation,
|
||||||
personExistsProblem,
|
personExistsProblem,
|
||||||
type WithGuardians,
|
|
||||||
} from '@/modules/people/lib/people';
|
} from '@/modules/people/lib/people';
|
||||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||||
|
|
||||||
@@ -58,51 +54,27 @@ export class CreateAttendeeUseCase {
|
|||||||
return err(noGroupAccessProblem());
|
return err(noGroupAccessProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const isKidsGroup = group.audience === 'KIDS';
|
const phone = normalizePhone(payload.phone);
|
||||||
if (isKidsGroup && !payload.personId && !payload.guardian) {
|
|
||||||
return err(guardianRequiredProblem());
|
|
||||||
}
|
|
||||||
// A kid may have no phone of their own: the adult in charge is the contact.
|
|
||||||
const phone = payload.phone ? normalizePhone(payload.phone) : null;
|
|
||||||
|
|
||||||
/* The person: the one the form picked (`personId`, after the "ya existe"
|
/* 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. */
|
hint) or a new one. A phone the teacher already has is never duplicated. */
|
||||||
let person: ({ id: string; fullName: string; phone: string | null } & WithGuardians) | null = null;
|
let person: { id: string; fullName: string } | null = null;
|
||||||
// Kids groups: the adult in charge, already one of the teacher's people or new.
|
|
||||||
let guardian: { id: string } | null = null;
|
|
||||||
if (payload.personId) {
|
if (payload.personId) {
|
||||||
person = await db.person.findFirst({
|
person = await db.person.findFirst({
|
||||||
where: { id: payload.personId, createdById: group.createdById },
|
where: { id: payload.personId, createdById: group.createdById },
|
||||||
select: { id: true, fullName: true, phone: true, ...guardianSelect },
|
select: { id: true, fullName: true },
|
||||||
});
|
});
|
||||||
if (!person) {
|
if (!person) {
|
||||||
return err(notFoundResourceProblem('Person', payload.personId));
|
return err(notFoundResourceProblem('Person', payload.personId));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (payload.phone) {
|
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
||||||
// The raw phone: its variants also match older rows stored as typed.
|
if (samePhone) {
|
||||||
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
return err(
|
||||||
if (samePhone) {
|
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
||||||
return err(
|
? alreadyInGroupProblem()
|
||||||
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
: personExistsProblem(),
|
||||||
? alreadyInGroupProblem()
|
);
|
||||||
: personExistsProblem(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (payload.guardian) {
|
|
||||||
guardian = await findPersonByPhone(db, group.createdById, payload.guardian.phone);
|
|
||||||
// The same kid of the same adult (same name) is that kid, not a twin.
|
|
||||||
if (guardian) {
|
|
||||||
person = await db.person.findFirst({
|
|
||||||
where: {
|
|
||||||
createdById: group.createdById,
|
|
||||||
fullName: { equals: kidFullName(payload), mode: 'insensitive' },
|
|
||||||
guardians: { some: { guardianId: guardian.id } },
|
|
||||||
},
|
|
||||||
select: { id: true, fullName: true, phone: true, ...guardianSelect },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,12 +86,7 @@ export class CreateAttendeeUseCase {
|
|||||||
return err(alreadyInGroupProblem());
|
return err(alreadyInGroupProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullName = person?.fullName ?? kidFullName(payload);
|
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||||
// Who the waitlist row (and later the messages) reaches.
|
|
||||||
const reachPhone =
|
|
||||||
(person ? contactPhone(person) : null) ??
|
|
||||||
phone ??
|
|
||||||
(payload.guardian ? normalizePhone(payload.guardian.phone) : null);
|
|
||||||
|
|
||||||
if (group.capacity !== null) {
|
if (group.capacity !== null) {
|
||||||
const currentCount = await db.attendee.count({
|
const currentCount = await db.attendee.count({
|
||||||
@@ -132,9 +99,9 @@ export class CreateAttendeeUseCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isOwner) {
|
if (!isOwner) {
|
||||||
const existingWaitlistEntry = reachPhone
|
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
||||||
? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } })
|
where: { groupId, phone },
|
||||||
: null;
|
});
|
||||||
|
|
||||||
if (existingWaitlistEntry) {
|
if (existingWaitlistEntry) {
|
||||||
return err(alreadyWaitlistedProblem());
|
return err(alreadyWaitlistedProblem());
|
||||||
@@ -144,7 +111,7 @@ export class CreateAttendeeUseCase {
|
|||||||
data: {
|
data: {
|
||||||
groupId,
|
groupId,
|
||||||
fullName,
|
fullName,
|
||||||
phone: reachPhone ?? '',
|
phone,
|
||||||
email: payload.email?.trim() || null,
|
email: payload.email?.trim() || null,
|
||||||
notes: payload.notes?.trim() || null,
|
notes: payload.notes?.trim() || null,
|
||||||
},
|
},
|
||||||
@@ -190,7 +157,6 @@ export class CreateAttendeeUseCase {
|
|||||||
phone,
|
phone,
|
||||||
email: payload.email?.trim() || null,
|
email: payload.email?.trim() || null,
|
||||||
notes: payload.notes?.trim() || null,
|
notes: payload.notes?.trim() || null,
|
||||||
...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}),
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -207,24 +173,3 @@ export class CreateAttendeeUseCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function kidFullName(payload: CreateAttendee): string {
|
|
||||||
return `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Nested create of the kid's link to the adult in charge: the existing adult,
|
|
||||||
or a new person with the adult's data. */
|
|
||||||
function guardianLink(ownerId: string, input: GuardianInput, existing: { id: string } | null) {
|
|
||||||
return {
|
|
||||||
guardian: existing
|
|
||||||
? { connect: { id: existing.id } }
|
|
||||||
: {
|
|
||||||
create: {
|
|
||||||
createdById: ownerId,
|
|
||||||
fullName: input.fullName.trim(),
|
|
||||||
phone: normalizePhone(input.phone),
|
|
||||||
email: input.email?.trim() || null,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import { err, ok } from '@gruperly/shared';
|
|||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
import { personMembershipsSelect, primaryGuardian, toMemberships } from '@/modules/people/lib/people';
|
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
|
||||||
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
||||||
|
|
||||||
type GetAttendeeDeps = {
|
type GetAttendeeDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'personGuardian'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -48,21 +48,11 @@ export class GetAttendee {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { attendees: memberships, ...person } = attendee.person;
|
const { attendees: memberships, ...person } = attendee.person;
|
||||||
// The other kids of the same adult in charge.
|
|
||||||
const guardian = primaryGuardian(person);
|
|
||||||
const siblings = guardian
|
|
||||||
? await db.personGuardian.findMany({
|
|
||||||
where: { guardianId: guardian.id, childId: { not: person.id } },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { child: { select: { id: true, fullName: true } } },
|
|
||||||
})
|
|
||||||
: [];
|
|
||||||
return ok(
|
return ok(
|
||||||
toAttendeeDetailDto({
|
toAttendeeDetailDto({
|
||||||
...attendee,
|
...attendee,
|
||||||
person,
|
person,
|
||||||
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
||||||
siblings: siblings.map(({ child }) => ({ personId: child.id, fullName: child.fullName })),
|
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
import type { GuardianInput } from '@gruperly/shared';
|
|
||||||
import { GuardianInputSchema } from '@gruperly/shared';
|
|
||||||
import { Hono } from 'hono';
|
|
||||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
|
||||||
import { validate } from '@/http/validate';
|
|
||||||
import { UpdateAttendeeGuardian } from './use-case';
|
|
||||||
|
|
||||||
/** `PATCH /groups/:groupId/attendees/:attendeeId/guardian`. */
|
|
||||||
const route = new Hono();
|
|
||||||
|
|
||||||
route.patch('/:groupId/attendees/:attendeeId/guardian', validate.json(GuardianInputSchema), async (c) => {
|
|
||||||
const user = c.get('user');
|
|
||||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
|
||||||
|
|
||||||
const result = await new UpdateAttendeeGuardian().execute({
|
|
||||||
groupId: c.req.param('groupId'),
|
|
||||||
attendeeId: c.req.param('attendeeId'),
|
|
||||||
userId: user.id,
|
|
||||||
input: c.req.valid('json') as GuardianInput,
|
|
||||||
});
|
|
||||||
return resultJson(c, result);
|
|
||||||
});
|
|
||||||
|
|
||||||
export default route;
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
|
||||||
import type { AttendeeDto, GuardianInput, 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 {
|
|
||||||
findOrCreateGuardian,
|
|
||||||
guardianSelect,
|
|
||||||
isUniqueViolation,
|
|
||||||
personPhoneTakenProblem,
|
|
||||||
primaryGuardian,
|
|
||||||
} from '@/modules/people/lib/people';
|
|
||||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
|
||||||
|
|
||||||
type UpdateGuardianDeps = {
|
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person' | 'personGuardian'>;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UpdateGuardianCommand = {
|
|
||||||
groupId: string;
|
|
||||||
attendeeId: string;
|
|
||||||
userId: string;
|
|
||||||
input: GuardianInput;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The adult in charge of a kid, from the kid's page. With an adult already
|
|
||||||
* linked it edits that adult (a person of their own, so it shows on every
|
|
||||||
* sibling); without one it links the adult with that phone, or a new one.
|
|
||||||
*/
|
|
||||||
export class UpdateAttendeeGuardian {
|
|
||||||
constructor(private readonly deps: UpdateGuardianDeps = {}) {}
|
|
||||||
|
|
||||||
async execute(command: UpdateGuardianCommand): 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, person: { select: { id: true, phone: true, ...guardianSelect } } },
|
|
||||||
});
|
|
||||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
|
||||||
|
|
||||||
const current = primaryGuardian(attendee.person);
|
|
||||||
try {
|
|
||||||
if (current) {
|
|
||||||
await db.person.update({
|
|
||||||
where: { id: current.id },
|
|
||||||
data: {
|
|
||||||
fullName: input.fullName.trim(),
|
|
||||||
phone: normalizePhone(input.phone),
|
|
||||||
email: input.email?.trim() || null,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const guardian = await findOrCreateGuardian(db, access.value.createdById, input);
|
|
||||||
// The kid's own phone is not an adult in charge of themselves.
|
|
||||||
if (guardian.id === attendee.personId) return err(personPhoneTakenProblem());
|
|
||||||
await db.personGuardian.create({ data: { childId: attendee.personId, guardianId: guardian.id } });
|
|
||||||
}
|
|
||||||
} 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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||||
import { type GuardianContact, guardianSelect, primaryGuardian } from '@/modules/people/lib/guardians';
|
|
||||||
|
|
||||||
/* Contact data of the person behind an attendee (shared by all their groups). */
|
/* Contact data of the person behind an attendee (shared by all their groups). */
|
||||||
export const personContactSelect = {
|
export const personContactSelect = {
|
||||||
@@ -7,8 +6,9 @@ export const personContactSelect = {
|
|||||||
fullName: true,
|
fullName: true,
|
||||||
email: true,
|
email: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
|
guardianName: true,
|
||||||
|
guardianPhone: true,
|
||||||
notes: true,
|
notes: true,
|
||||||
...guardianSelect,
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
||||||
@@ -19,8 +19,9 @@ export type PersonContactRecord = {
|
|||||||
fullName: string;
|
fullName: string;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
|
guardianName: string | null;
|
||||||
|
guardianPhone: string | null;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
guardians?: { guardian: GuardianContact }[];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AttendeeRecord = {
|
export type AttendeeRecord = {
|
||||||
@@ -45,20 +46,8 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
|||||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||||
payments: AttendeeListItemRecord['payments'];
|
payments: AttendeeListItemRecord['payments'];
|
||||||
otherGroups: AttendeeDetailDto['otherGroups'];
|
otherGroups: AttendeeDetailDto['otherGroups'];
|
||||||
siblings?: AttendeeDetailDto['siblings'];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/* The adult in charge, flattened into the attendee DTO (all null when none). */
|
|
||||||
export function guardianFields(person: { guardians?: { guardian: GuardianContact }[] }) {
|
|
||||||
const guardian = primaryGuardian(person);
|
|
||||||
return {
|
|
||||||
guardianPersonId: guardian?.id ?? null,
|
|
||||||
guardianName: guardian?.fullName ?? null,
|
|
||||||
guardianPhone: guardian?.phone ?? null,
|
|
||||||
guardianEmail: guardian?.email ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
id: record.id,
|
||||||
@@ -67,7 +56,8 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
|||||||
fullName: record.person.fullName,
|
fullName: record.person.fullName,
|
||||||
email: record.person.email,
|
email: record.person.email,
|
||||||
phone: record.person.phone,
|
phone: record.person.phone,
|
||||||
...guardianFields(record.person),
|
guardianName: record.person.guardianName,
|
||||||
|
guardianPhone: record.person.guardianPhone,
|
||||||
notes: record.person.notes,
|
notes: record.person.notes,
|
||||||
notifyToken: record.notifyToken ?? null,
|
notifyToken: record.notifyToken ?? null,
|
||||||
createdAt: record.createdAt.toISOString(),
|
createdAt: record.createdAt.toISOString(),
|
||||||
@@ -101,7 +91,6 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
|
|||||||
...toAttendeeDto(record),
|
...toAttendeeDto(record),
|
||||||
payment: pickRelevantPayment(record.payments),
|
payment: pickRelevantPayment(record.payments),
|
||||||
otherGroups: record.otherGroups,
|
otherGroups: record.otherGroups,
|
||||||
siblings: record.siblings ?? [],
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import prisma from '@/lib/prisma';
|
|||||||
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
||||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
import { contactPhone } from '@/modules/people/lib/people';
|
||||||
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||||
|
|
||||||
type GetAttentionOverviewDeps = {
|
type GetAttentionOverviewDeps = {
|
||||||
@@ -35,7 +35,7 @@ type AttendeeRow = {
|
|||||||
groupId: string;
|
groupId: string;
|
||||||
fullName: string;
|
fullName: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
guardians?: { guardian: { phone: string | null } }[];
|
guardianPhone: string | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
};
|
};
|
||||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||||
@@ -88,7 +88,7 @@ export class GetAttentionOverview {
|
|||||||
id: true,
|
id: true,
|
||||||
groupId: true,
|
groupId: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
person: { select: { fullName: true, phone: true, ...guardianSelect } },
|
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||||
},
|
},
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ export class PlanCatalog {
|
|||||||
maxAttendees: config.maxAttendees,
|
maxAttendees: config.maxAttendees,
|
||||||
whatsappAutomations: config.whatsappAutomations,
|
whatsappAutomations: config.whatsappAutomations,
|
||||||
mpCharges: config.mpCharges,
|
mpCharges: config.mpCharges,
|
||||||
kidsGroups: config.kidsGroups,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
for (const price of prices) {
|
for (const price of prices) {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { type GroupRecord, toGroupDto } from '../../lib';
|
|||||||
|
|
||||||
type CreateGroupDeps = {
|
type CreateGroupDeps = {
|
||||||
unitOfWork?: UnitOfWork;
|
unitOfWork?: UnitOfWork;
|
||||||
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class CreateGroup {
|
export class CreateGroup {
|
||||||
@@ -25,15 +25,10 @@ export class CreateGroup {
|
|||||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||||
|
|
||||||
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
||||||
const allowed = await planGuard.canCreateGroup(userId);
|
|
||||||
if (!allowed.ok) {
|
if (!allowed.ok) {
|
||||||
return allowed;
|
return allowed;
|
||||||
}
|
}
|
||||||
if (data.audience === 'KIDS') {
|
|
||||||
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
|
|
||||||
if (!kidsAllowed.ok) return kidsAllowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
const transaction = unitOfWork.executeResult(
|
const transaction = unitOfWork.executeResult(
|
||||||
async (tx: Prisma.TransactionClient) => {
|
async (tx: Prisma.TransactionClient) => {
|
||||||
@@ -47,7 +42,6 @@ export class CreateGroup {
|
|||||||
price: data.price,
|
price: data.price,
|
||||||
billingType: data.billingType,
|
billingType: data.billingType,
|
||||||
dueDay: data.dueDay,
|
dueDay: data.dueDay,
|
||||||
audience: data.audience,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import type { UpdateGroup } from '@gruperly/shared';
|
|
||||||
import { UpdateGroupSchema } from '@gruperly/shared';
|
|
||||||
import { Hono } from 'hono';
|
|
||||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
|
||||||
import { validate } from '@/http/validate';
|
|
||||||
import { UpdateGroupUseCase } from './use-case';
|
|
||||||
|
|
||||||
/** `PATCH /groups/:groupId` ("Editar grupo"). */
|
|
||||||
const route = new Hono();
|
|
||||||
|
|
||||||
route.patch('/:groupId', validate.json(UpdateGroupSchema), async (c) => {
|
|
||||||
const user = c.get('user');
|
|
||||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
|
||||||
|
|
||||||
const input = c.req.valid('json') as UpdateGroup;
|
|
||||||
const result = await new UpdateGroupUseCase().execute(c.req.param('groupId'), user.id, input);
|
|
||||||
return resultJson(c, result);
|
|
||||||
});
|
|
||||||
|
|
||||||
export default route;
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
|
||||||
import type { GroupDto, ProblemDetails, Result, UpdateGroup } from '@gruperly/shared';
|
|
||||||
import { err, ok } from '@gruperly/shared';
|
|
||||||
import { conflictProblem, forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
|
||||||
import prisma from '@/lib/prisma';
|
|
||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
|
||||||
import { type GroupRecord, toGroupDto } from '../../lib';
|
|
||||||
|
|
||||||
type UpdateGroupDeps = {
|
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
|
||||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Editar grupo": name, schedule, capacity, billing and who it is for. Only
|
|
||||||
* the owner can. A lower capacity than the current members is allowed: it only
|
|
||||||
* stops new additions.
|
|
||||||
*
|
|
||||||
* Who it is for: turning it into a kids group needs the `kidsGroups` plan
|
|
||||||
* feature (a kids group that already exists keeps working after a downgrade);
|
|
||||||
* going back to adults is blocked while a member has no phone of their own,
|
|
||||||
* since without the adult in charge nobody could be reached.
|
|
||||||
*/
|
|
||||||
export class UpdateGroupUseCase {
|
|
||||||
constructor(private readonly deps: UpdateGroupDeps = {}) {}
|
|
||||||
|
|
||||||
async execute(groupId: string, userId: string, input: UpdateGroup): Promise<Result<GroupDto, ProblemDetails>> {
|
|
||||||
const db = this.deps.db ?? prisma;
|
|
||||||
|
|
||||||
const group = await db.group.findUnique({
|
|
||||||
where: { id: groupId },
|
|
||||||
select: { id: true, createdById: true, audience: true },
|
|
||||||
});
|
|
||||||
if (!group) return err(notFoundResourceProblem('Group', groupId));
|
|
||||||
if (group.createdById !== userId) {
|
|
||||||
return err(
|
|
||||||
forbiddenProblem({
|
|
||||||
detail: 'Solo quien creó el grupo puede editarlo.',
|
|
||||||
code: 'group_owner_required',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.audience === 'KIDS' && group.audience !== 'KIDS') {
|
|
||||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(userId, 'kidsGroups');
|
|
||||||
if (!allowed.ok) return allowed;
|
|
||||||
}
|
|
||||||
if (input.audience === 'ADULTS' && group.audience === 'KIDS') {
|
|
||||||
const withoutPhone = await db.attendee.count({
|
|
||||||
where: { groupId, status: { not: 'DROPPED' }, person: { phone: null } },
|
|
||||||
});
|
|
||||||
if (withoutPhone > 0) {
|
|
||||||
return err(
|
|
||||||
conflictProblem({
|
|
||||||
detail: 'Hay chicos sin teléfono propio: cargales uno antes de pasar el grupo a adultos.',
|
|
||||||
code: 'group_has_kids_without_phone',
|
|
||||||
params: { count: withoutPhone },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = await db.group.update({ where: { id: groupId }, data: input });
|
|
||||||
return ok(toGroupDto(updated as GroupRecord));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { BillingType, GroupAudience, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
||||||
|
|
||||||
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
||||||
|
|
||||||
@@ -21,7 +21,6 @@ export type GroupRecord = {
|
|||||||
inviteToken?: string | null;
|
inviteToken?: string | null;
|
||||||
autoPaymentReminders?: boolean;
|
autoPaymentReminders?: boolean;
|
||||||
autoReengagement?: boolean;
|
autoReengagement?: boolean;
|
||||||
audience?: GroupAudience;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/* The listing adds the occupancy counters to each group so the card can show
|
/* The listing adds the occupancy counters to each group so the card can show
|
||||||
@@ -50,7 +49,6 @@ export function toGroupDto(record: GroupRecord): GroupDto {
|
|||||||
inviteToken: record.inviteToken ?? null,
|
inviteToken: record.inviteToken ?? null,
|
||||||
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
autoReengagement: record.autoReengagement ?? false,
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
audience: record.audience ?? 'ADULTS',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
|||||||
import moveAttendeeRoute from '../attendees/features/move/route';
|
import moveAttendeeRoute from '../attendees/features/move/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||||
import updateAttendeeGuardianRoute from '../attendees/features/update-guardian/route';
|
|
||||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
||||||
@@ -20,7 +19,6 @@ import getAllRoute from './features/get-all/route';
|
|||||||
import getByIdRoute from './features/get-by-id/route';
|
import getByIdRoute from './features/get-by-id/route';
|
||||||
import inviteTokenRoute from './features/invite-token/route';
|
import inviteTokenRoute from './features/invite-token/route';
|
||||||
import listAttendeesRoute from './features/list-attendees/route';
|
import listAttendeesRoute from './features/list-attendees/route';
|
||||||
import updateGroupRoute from './features/update/route';
|
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
@@ -33,14 +31,12 @@ routes.route('/', bulkCreateAttendeesRoute);
|
|||||||
routes.route('/', getByIdRoute);
|
routes.route('/', getByIdRoute);
|
||||||
routes.route('/', createPaymentsBatchRoute);
|
routes.route('/', createPaymentsBatchRoute);
|
||||||
routes.route('/', updateGroupAutomationsRoute);
|
routes.route('/', updateGroupAutomationsRoute);
|
||||||
routes.route('/', updateGroupRoute);
|
|
||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
routes.route('/', groupPreRegistrationRoutes);
|
routes.route('/', groupPreRegistrationRoutes);
|
||||||
routes.route('/', analyticsRoutes);
|
routes.route('/', analyticsRoutes);
|
||||||
routes.route('/', getAttendeeRoute);
|
routes.route('/', getAttendeeRoute);
|
||||||
routes.route('/', updateAttendeeRoute);
|
routes.route('/', updateAttendeeRoute);
|
||||||
routes.route('/', updateAttendeeGuardianRoute);
|
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
routes.route('/', removeAttendeeRoute);
|
routes.route('/', removeAttendeeRoute);
|
||||||
routes.route('/', moveAttendeeRoute);
|
routes.route('/', moveAttendeeRoute);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import { toOnboardingGroupDto } from '../../lib';
|
|||||||
type CreateFirstGroupDeps = {
|
type CreateFirstGroupDeps = {
|
||||||
db?: Pick<PrismaClient, 'user'>;
|
db?: Pick<PrismaClient, 'user'>;
|
||||||
unitOfWork?: UnitOfWork;
|
unitOfWork?: UnitOfWork;
|
||||||
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class CreateFirstGroup {
|
export class CreateFirstGroup {
|
||||||
@@ -41,15 +41,10 @@ export class CreateFirstGroup {
|
|||||||
return err(planNotSelectedProblem());
|
return err(planNotSelectedProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
||||||
const allowed = await planGuard.canCreateGroup(userId);
|
|
||||||
if (!allowed.ok) {
|
if (!allowed.ok) {
|
||||||
return allowed;
|
return allowed;
|
||||||
}
|
}
|
||||||
if (data.audience === 'KIDS') {
|
|
||||||
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
|
|
||||||
if (!kidsAllowed.ok) return kidsAllowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
const transaction = unitOfWork.executeResult(
|
const transaction = unitOfWork.executeResult(
|
||||||
async (tx: Prisma.TransactionClient) => {
|
async (tx: Prisma.TransactionClient) => {
|
||||||
@@ -63,7 +58,6 @@ export class CreateFirstGroup {
|
|||||||
price: data.price,
|
price: data.price,
|
||||||
billingType: data.billingType,
|
billingType: data.billingType,
|
||||||
dueDay: data.dueDay,
|
dueDay: data.dueDay,
|
||||||
audience: data.audience,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { BillingType, GroupAudience, OnboardingGroupDto, WeekDay } from '@gruperly/shared';
|
import type { BillingType, OnboardingGroupDto, WeekDay } from '@gruperly/shared';
|
||||||
|
|
||||||
type PriceLike = { toString(): string };
|
type PriceLike = { toString(): string };
|
||||||
|
|
||||||
@@ -17,7 +17,6 @@ export type OnboardingGroupRecord = {
|
|||||||
dueDay: number | null;
|
dueDay: number | null;
|
||||||
autoPaymentReminders?: boolean;
|
autoPaymentReminders?: boolean;
|
||||||
autoReengagement?: boolean;
|
autoReengagement?: boolean;
|
||||||
audience?: GroupAudience;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
|
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
|
||||||
@@ -36,6 +35,5 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG
|
|||||||
dueDay: record.dueDay,
|
dueDay: record.dueDay,
|
||||||
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
autoReengagement: record.autoReengagement ?? false,
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
audience: record.audience ?? 'ADULTS',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
/* Kept apart from `people.ts` (no imports): `attendees/lib/helpers.ts` spreads
|
|
||||||
`guardianSelect` at load time and `people.ts` imports from it. */
|
|
||||||
|
|
||||||
/* The adult in charge of a kid (`PersonGuardian`). One per kid in v1: the
|
|
||||||
oldest link wins if there were ever more. */
|
|
||||||
export const guardianSelect = {
|
|
||||||
guardians: {
|
|
||||||
take: 1,
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export type GuardianContact = { id: string; fullName: string; phone: string | null; email: string | null };
|
|
||||||
export type WithGuardians = { guardians?: { guardian: Partial<GuardianContact> & { phone: string | null } }[] };
|
|
||||||
|
|
||||||
export function primaryGuardian<T extends { phone: string | null }>(person: {
|
|
||||||
guardians?: { guardian: T }[];
|
|
||||||
}): T | null {
|
|
||||||
return person.guardians?.[0]?.guardian ?? null;
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||||
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
||||||
import { conflictProblem } from '@/http/problem-builders';
|
import { conflictProblem } from '@/http/problem-builders';
|
||||||
import { problemDetails } from '@/http/problem-details';
|
|
||||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||||
import { primaryGuardian, type WithGuardians } from './guardians';
|
|
||||||
|
|
||||||
export { type GuardianContact, guardianSelect, primaryGuardian, type WithGuardians } from './guardians';
|
|
||||||
|
|
||||||
/* A person is the teacher's contact (student, or a guardian's child); their
|
/* A person is the teacher's contact (student, or a guardian's child); their
|
||||||
`attendees` are the memberships in each group. The phone is unique per
|
`attendees` are the memberships in each group. The phone is unique per
|
||||||
@@ -64,27 +60,12 @@ export async function findPersonSummaryByPhone(
|
|||||||
): Promise<PersonSummary | null> {
|
): Promise<PersonSummary | null> {
|
||||||
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
||||||
if (!person) return null;
|
if (!person) return null;
|
||||||
// When the phone is an adult in charge, the add form offers their kids.
|
|
||||||
const links = await db.person.findUnique({
|
|
||||||
where: { id: person.id },
|
|
||||||
select: {
|
|
||||||
children: {
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { child: { select: { id: true, fullName: true, ...personMembershipsSelect } } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
id: person.id,
|
id: person.id,
|
||||||
fullName: person.fullName,
|
fullName: person.fullName,
|
||||||
email: person.email,
|
email: person.email,
|
||||||
phone: person.phone,
|
phone: person.phone,
|
||||||
groups: toMemberships(person.attendees),
|
groups: toMemberships(person.attendees),
|
||||||
children: (links?.children ?? []).map(({ child }) => ({
|
|
||||||
id: child.id,
|
|
||||||
fullName: child.fullName,
|
|
||||||
groups: toMemberships(child.attendees),
|
|
||||||
})),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,24 +109,9 @@ export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone
|
|||||||
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
|
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The number the teacher reaches the person on: the adult in charge when there
|
/* The number the teacher reaches the person on: theirs, or the guardian's. */
|
||||||
is one (a kid's own phone, if any, is not who answers for them), else theirs. */
|
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null {
|
||||||
export function contactPhone(person: { phone: string | null } & WithGuardians): string | null {
|
return person.phone ?? person.guardianPhone;
|
||||||
return primaryGuardian(person)?.phone ?? person.phone;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The adult in charge, found by phone among the teacher's people (their stored
|
|
||||||
data wins, like any other person) or created. */
|
|
||||||
export async function findOrCreateGuardian(
|
|
||||||
db: PeopleDb,
|
|
||||||
ownerId: string,
|
|
||||||
data: { fullName: string; phone: string; email?: string | null },
|
|
||||||
): Promise<{ id: string; created: boolean }> {
|
|
||||||
return findOrCreatePerson(db, ownerId, {
|
|
||||||
fullName: data.fullName.trim(),
|
|
||||||
phone: normalizePhone(data.phone),
|
|
||||||
email: data.email?.trim() || null,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isUniqueViolation(error: unknown): boolean {
|
export function isUniqueViolation(error: unknown): boolean {
|
||||||
@@ -168,16 +134,6 @@ export function personExistsProblem(): ProblemDetails {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A kids group: each new kid needs the adult in charge. */
|
|
||||||
export function guardianRequiredProblem(): ProblemDetails {
|
|
||||||
return problemDetails({
|
|
||||||
title: 'Bad Request',
|
|
||||||
status: 400,
|
|
||||||
detail: 'En un grupo de chicos tenés que cargar al adulto a cargo.',
|
|
||||||
code: 'guardian_required',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function personPhoneTakenProblem(): ProblemDetails {
|
export function personPhoneTakenProblem(): ProblemDetails {
|
||||||
return conflictProblem({
|
return conflictProblem({
|
||||||
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { err, ok } from '@gruperly/shared';
|
|||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
import { guardianSelect } from '@/modules/people/lib/guardians';
|
|
||||||
import { computeStudentAccess } from '../../lib/status';
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
type GetStudentAccessDeps = {
|
type GetStudentAccessDeps = {
|
||||||
@@ -24,14 +23,9 @@ export class GetStudentAccess {
|
|||||||
const access = await findGroupForUser(db, groupId, userId);
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
if (!access.ok) return access;
|
if (!access.ok) return access;
|
||||||
|
|
||||||
const attendee = await db.attendee.findFirst({
|
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
|
||||||
where: { id: attendeeId, groupId },
|
|
||||||
select: { personId: true, person: { select: guardianSelect } },
|
|
||||||
});
|
|
||||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
// A kid with an adult in charge uses the adult's account (shared by siblings).
|
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
|
||||||
const ownerId = attendee.person.guardians[0]?.guardian.id ?? attendee.personId;
|
|
||||||
return ok(await computeStudentAccess(db, ownerId, this.deps.now ?? new Date()));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
||||||
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
import { contactPhone, guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
|
import { contactPhone } from '@/modules/people/lib/people';
|
||||||
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||||
import { computeStudentAccess } from '../../lib/status';
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
@@ -38,25 +38,36 @@ export class InviteStudent {
|
|||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
personId: true,
|
personId: true,
|
||||||
person: { select: { fullName: true, phone: true, ...guardianSelect } },
|
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||||
group: { select: { owner: { select: { country: true } } } },
|
group: { select: { owner: { select: { country: true } } } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
// The account belongs to the adult in charge when the kid has one: it
|
|
||||||
// reaches all of their kids.
|
|
||||||
const guardian = primaryGuardian(attendee.person);
|
|
||||||
const owner = guardian
|
|
||||||
? { personId: guardian.id, fullName: guardian.fullName }
|
|
||||||
: { personId: attendee.personId, fullName: attendee.person.fullName };
|
|
||||||
|
|
||||||
const token = generateAccessToken();
|
const token = generateAccessToken();
|
||||||
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
||||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
|
||||||
const issued = await unitOfWork.executeResult(async (tx) => {
|
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||||
const accountId = await resolveAccount(tx, owner, userId);
|
// One account per person: inviting from any of their groups reuses it.
|
||||||
|
const link = await tx.studentAccountPerson.findFirst({
|
||||||
|
where: { personId: attendee.personId },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { accountId: true },
|
||||||
|
});
|
||||||
|
const accountId =
|
||||||
|
link?.accountId
|
||||||
|
?? (
|
||||||
|
await tx.studentAccount.create({
|
||||||
|
data: {
|
||||||
|
name: attendee.person.fullName,
|
||||||
|
createdById: userId,
|
||||||
|
people: { create: { personId: attendee.personId } },
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
).id;
|
||||||
|
|
||||||
await tx.studentAccessToken.updateMany({
|
await tx.studentAccessToken.updateMany({
|
||||||
where: { accountId, usedAt: null, revokedAt: null },
|
where: { accountId, usedAt: null, revokedAt: null },
|
||||||
data: { revokedAt: now },
|
data: { revokedAt: now },
|
||||||
@@ -85,7 +96,7 @@ export class InviteStudent {
|
|||||||
url: studentLinkUrl(token),
|
url: studentLinkUrl(token),
|
||||||
expiresAt: expiresAt.toISOString(),
|
expiresAt: expiresAt.toISOString(),
|
||||||
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
||||||
access: await computeStudentAccess(db, owner.personId, now),
|
access: await computeStudentAccess(db, attendee.personId, now),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,52 +104,3 @@ export class InviteStudent {
|
|||||||
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
||||||
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccountOwner = { personId: string; fullName: string };
|
|
||||||
|
|
||||||
/* One account per person: inviting from any of their groups (or, for an adult
|
|
||||||
in charge, from any of their kids) reuses it. Accounts made before kids
|
|
||||||
groups were linked to the kid: the oldest one of the adult's kids moves to
|
|
||||||
the adult, and the kids stop being linked one by one (they are reached
|
|
||||||
through `person_guardians`). */
|
|
||||||
async function resolveAccount(tx: Prisma.TransactionClient, owner: AccountOwner, userId: string): Promise<string> {
|
|
||||||
const kids = await tx.personGuardian.findMany({ where: { guardianId: owner.personId }, select: { childId: true } });
|
|
||||||
const kidIds = kids.map((kid) => kid.childId);
|
|
||||||
|
|
||||||
const own = await tx.studentAccountPerson.findFirst({
|
|
||||||
where: { personId: owner.personId },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { accountId: true },
|
|
||||||
});
|
|
||||||
const legacy =
|
|
||||||
own || kidIds.length === 0
|
|
||||||
? null
|
|
||||||
: await tx.studentAccountPerson.findFirst({
|
|
||||||
where: { personId: { in: kidIds } },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { accountId: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
let accountId: string;
|
|
||||||
if (own) {
|
|
||||||
accountId = own.accountId;
|
|
||||||
} else if (legacy) {
|
|
||||||
accountId = legacy.accountId;
|
|
||||||
await tx.studentAccount.update({
|
|
||||||
where: { id: accountId },
|
|
||||||
data: { name: owner.fullName, people: { create: { personId: owner.personId } } },
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
accountId = (
|
|
||||||
await tx.studentAccount.create({
|
|
||||||
data: { name: owner.fullName, createdById: userId, people: { create: { personId: owner.personId } } },
|
|
||||||
select: { id: true },
|
|
||||||
})
|
|
||||||
).id;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (kidIds.length > 0) {
|
|
||||||
await tx.studentAccountPerson.deleteMany({ where: { personId: { in: kidIds } } });
|
|
||||||
}
|
|
||||||
return accountId;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import { occurrencesBetween } from '@/modules/home/lib/scheduler';
|
|||||||
import {
|
import {
|
||||||
classAlreadyStartedProblem,
|
classAlreadyStartedProblem,
|
||||||
findLinkedAttendee,
|
findLinkedAttendee,
|
||||||
linkedPersonWhere,
|
|
||||||
studentAttendeeNotFoundProblem,
|
studentAttendeeNotFoundProblem,
|
||||||
teacherTimeZone,
|
teacherTimeZone,
|
||||||
} from '../../lib';
|
} from '../../lib';
|
||||||
@@ -128,7 +127,7 @@ export class CancelStudentAbsence {
|
|||||||
where: {
|
where: {
|
||||||
id: noticeId,
|
id: noticeId,
|
||||||
cancelledAt: null,
|
cancelledAt: null,
|
||||||
attendee: { status: { not: 'DROPPED' }, person: linkedPersonWhere(accountId) },
|
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
|
||||||
},
|
},
|
||||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
@@ -9,13 +9,6 @@ type GetStudentLinkInfoDeps = {
|
|||||||
now?: Date;
|
now?: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
const firstGroupSelect = {
|
|
||||||
where: { status: { not: 'DROPPED' } },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
take: 1,
|
|
||||||
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
|
||||||
} satisfies Prisma.Person$attendeesArgs;
|
|
||||||
|
|
||||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||||
|
|
||||||
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
||||||
@@ -45,12 +38,10 @@ export class GetStudentLinkInfo {
|
|||||||
select: {
|
select: {
|
||||||
person: {
|
person: {
|
||||||
select: {
|
select: {
|
||||||
attendees: firstGroupSelect,
|
attendees: {
|
||||||
// An adult in charge has no groups of their own: their kids' count.
|
|
||||||
children: {
|
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
take: 1,
|
take: 1,
|
||||||
select: { child: { select: { attendees: firstGroupSelect } } },
|
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -71,9 +62,7 @@ export class GetStudentLinkInfo {
|
|||||||
return ok({ status: 'invalid' });
|
return ok({ status: 'invalid' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const person = row.account.people[0]?.person;
|
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
|
||||||
const group =
|
|
||||||
person?.attendees[0]?.group ?? person?.children[0]?.child.attendees[0]?.group ?? null;
|
|
||||||
return ok({
|
return ok({
|
||||||
status: 'valid',
|
status: 'valid',
|
||||||
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||||
|
|||||||
@@ -1,44 +1,9 @@
|
|||||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import { unauthorizedProblem } from '@/http/problem-details';
|
import { unauthorizedProblem } from '@/http/problem-details';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
const personGroupsSelect = {
|
|
||||||
fullName: true,
|
|
||||||
attendees: {
|
|
||||||
where: { status: { not: 'DROPPED' } },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} satisfies Prisma.PersonSelect;
|
|
||||||
|
|
||||||
type PersonGroups = Prisma.PersonGetPayload<{ select: typeof personGroupsSelect }>;
|
|
||||||
|
|
||||||
/* One entry per membership; a kid reached twice (linked and through the adult)
|
|
||||||
shows up once. */
|
|
||||||
function studentsOf(people: PersonGroups[]): StudentMe['students'] {
|
|
||||||
const seen = new Set<string>();
|
|
||||||
return people.flatMap((person) =>
|
|
||||||
person.attendees.flatMap((attendee) => {
|
|
||||||
if (seen.has(attendee.id)) return [];
|
|
||||||
seen.add(attendee.id);
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
attendeeId: attendee.id,
|
|
||||||
fullName: person.fullName,
|
|
||||||
groupId: attendee.group.id,
|
|
||||||
groupName: attendee.group.name,
|
|
||||||
teacherName: attendee.group.owner.name,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
||||||
|
|
||||||
export class GetStudentMe {
|
export class GetStudentMe {
|
||||||
@@ -55,15 +20,21 @@ export class GetStudentMe {
|
|||||||
pendingRecoveryEmail: true,
|
pendingRecoveryEmail: true,
|
||||||
welcomedAt: true,
|
welcomedAt: true,
|
||||||
_count: { select: { passkeys: true } },
|
_count: { select: { passkeys: true } },
|
||||||
// Linked people (and the kids of a linked adult in charge), and every
|
// Linked people, and every group each of them is in.
|
||||||
// group each of them is in.
|
|
||||||
people: {
|
people: {
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
select: {
|
select: {
|
||||||
person: {
|
person: {
|
||||||
select: {
|
select: {
|
||||||
...personGroupsSelect,
|
fullName: true,
|
||||||
children: { orderBy: { createdAt: 'asc' }, select: { child: { select: personGroupsSelect } } },
|
attendees: {
|
||||||
|
where: { status: { not: 'DROPPED' } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -81,7 +52,15 @@ export class GetStudentMe {
|
|||||||
hasPasskey: account._count.passkeys > 0,
|
hasPasskey: account._count.passkeys > 0,
|
||||||
welcomed: account.welcomedAt !== null,
|
welcomed: account.welcomedAt !== null,
|
||||||
},
|
},
|
||||||
students: studentsOf(account.people.flatMap(({ person }) => [person, ...person.children.map(({ child }) => child)])),
|
students: account.people.flatMap(({ person }) =>
|
||||||
|
person.attendees.map((attendee) => ({
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
fullName: person.fullName,
|
||||||
|
groupId: attendee.group.id,
|
||||||
|
groupName: attendee.group.name,
|
||||||
|
teacherName: attendee.group.owner.name,
|
||||||
|
})),
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,29 +2,17 @@ import type { Prisma } from '@generated/prisma/client';
|
|||||||
|
|
||||||
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||||
|
|
||||||
/* The people a student account reaches: the ones linked to it and the kids of
|
|
||||||
a linked adult in charge (kids groups). Kids are not linked one by one, so a
|
|
||||||
kid added later shows up without a new invitation. */
|
|
||||||
export function linkedPersonWhere(accountId: string): Prisma.PersonWhereInput {
|
|
||||||
return {
|
|
||||||
OR: [
|
|
||||||
{ studentAccounts: { some: { accountId } } },
|
|
||||||
{ guardians: { some: { guardian: { studentAccounts: { some: { accountId } } } } } },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The authorization rule of every student endpoint: an attendee (membership)
|
/* The authorization rule of every student endpoint: an attendee (membership)
|
||||||
of a person linked to the session's account, with what the student screens
|
of a person linked to the session's account, with what the student screens
|
||||||
need from the group. The account is linked to the person (or to their adult
|
need from the group. The account is linked to the person, so every group
|
||||||
in charge), so every group they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
||||||
access): routes answer 404, the same as for an id that doesn't exist. */
|
access): routes answer 404, the same as for an id that doesn't exist. */
|
||||||
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||||
return db.attendee.findFirst({
|
return db.attendee.findFirst({
|
||||||
where: {
|
where: {
|
||||||
id: attendeeId,
|
id: attendeeId,
|
||||||
status: { not: 'DROPPED' },
|
status: { not: 'DROPPED' },
|
||||||
person: linkedPersonWhere(accountId),
|
person: { studentAccounts: { some: { accountId } } },
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
import { contactPhone } from '@/modules/people/lib/people';
|
||||||
import {
|
import {
|
||||||
addTotals,
|
addTotals,
|
||||||
type DispatchItem,
|
type DispatchItem,
|
||||||
@@ -71,7 +71,7 @@ export class SendPaymentReminders {
|
|||||||
dueDate: true,
|
dueDate: true,
|
||||||
checkoutUrl: true,
|
checkoutUrl: true,
|
||||||
attendee: {
|
attendee: {
|
||||||
select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
|
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
orderBy: { dueDate: 'asc' },
|
orderBy: { dueDate: 'asc' },
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
findStudentsAtRisk,
|
findStudentsAtRisk,
|
||||||
type StudentsAtRiskDb,
|
type StudentsAtRiskDb,
|
||||||
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
||||||
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
import { contactPhone } from '@/modules/people/lib/people';
|
||||||
import {
|
import {
|
||||||
addTotals,
|
addTotals,
|
||||||
type DispatchItem,
|
type DispatchItem,
|
||||||
@@ -70,7 +70,7 @@ export class SendReengagementMessages {
|
|||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
select: { id: true, person: { select: { phone: true, ...guardianSelect } } },
|
select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
||||||
|
|||||||
@@ -8,9 +8,6 @@ const db = {
|
|||||||
attendee: {
|
attendee: {
|
||||||
findFirst: mock(),
|
findFirst: mock(),
|
||||||
},
|
},
|
||||||
personGuardian: {
|
|
||||||
findMany: mock(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
mock.module('@/lib/prisma', () => ({
|
mock.module('@/lib/prisma', () => ({
|
||||||
@@ -47,9 +44,9 @@ const attendee = {
|
|||||||
fullName: 'Ana Pérez',
|
fullName: 'Ana Pérez',
|
||||||
email: 'ana@example.com',
|
email: 'ana@example.com',
|
||||||
phone: '5512345678',
|
phone: '5512345678',
|
||||||
|
guardianName: 'Luis Pérez',
|
||||||
|
guardianPhone: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
// The adult in charge, a person of their own.
|
|
||||||
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '5598765432', email: null } }],
|
|
||||||
// Every membership of the person: this one and another group.
|
// Every membership of the person: this one and another group.
|
||||||
attendees: [
|
attendees: [
|
||||||
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
|
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
|
||||||
@@ -72,7 +69,6 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
|||||||
it('devuelve el participante del grupo', async () => {
|
it('devuelve el participante del grupo', async () => {
|
||||||
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
prisma.attendee.findFirst.mockResolvedValue(attendee);
|
prisma.attendee.findFirst.mockResolvedValue(attendee);
|
||||||
prisma.personGuardian.findMany.mockResolvedValue([{ child: { id: 'person-2', fullName: 'Tomás Pérez' } }]);
|
|
||||||
|
|
||||||
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
|
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
|
||||||
|
|
||||||
@@ -84,21 +80,15 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
|||||||
fullName: 'Ana Pérez',
|
fullName: 'Ana Pérez',
|
||||||
email: 'ana@example.com',
|
email: 'ana@example.com',
|
||||||
phone: '5512345678',
|
phone: '5512345678',
|
||||||
guardianPersonId: 'person-9',
|
|
||||||
guardianName: 'Luis Pérez',
|
guardianName: 'Luis Pérez',
|
||||||
guardianPhone: '5598765432',
|
guardianPhone: null,
|
||||||
guardianEmail: null,
|
|
||||||
notes: null,
|
notes: null,
|
||||||
notifyToken: 'token-1',
|
notifyToken: 'token-1',
|
||||||
createdAt: '2026-08-01T10:00:00.000Z',
|
createdAt: '2026-08-01T10:00:00.000Z',
|
||||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||||
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||||
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
|
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
|
||||||
siblings: [{ personId: 'person-2', fullName: 'Tomás Pérez' }],
|
|
||||||
});
|
});
|
||||||
expect(prisma.personGuardian.findMany).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ where: { guardianId: 'person-9', childId: { not: 'person-1' } } }),
|
|
||||||
);
|
|
||||||
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
|
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
|
||||||
where: { id: 'a-1', groupId: 'group-1' },
|
where: { id: 'a-1', groupId: 'group-1' },
|
||||||
include: {
|
include: {
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
|||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
expect(prisma.person.findFirst).toHaveBeenCalledWith({
|
expect(prisma.person.findFirst).toHaveBeenCalledWith({
|
||||||
where: { id: 'person-1', createdById: teacherId },
|
where: { id: 'person-1', createdById: teacherId },
|
||||||
select: expect.objectContaining({ id: true, fullName: true }),
|
select: { id: true, fullName: true },
|
||||||
});
|
});
|
||||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||||
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
|
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
|
||||||
|
|||||||
@@ -24,12 +24,9 @@ const personSelect = {
|
|||||||
fullName: true,
|
fullName: true,
|
||||||
email: true,
|
email: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
|
guardianName: true,
|
||||||
|
guardianPhone: true,
|
||||||
notes: true,
|
notes: true,
|
||||||
guardians: {
|
|
||||||
take: 1,
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const person = {
|
const person = {
|
||||||
@@ -37,8 +34,9 @@ const person = {
|
|||||||
fullName: 'Ana Pérez',
|
fullName: 'Ana Pérez',
|
||||||
email: 'ana@example.com',
|
email: 'ana@example.com',
|
||||||
phone: null,
|
phone: null,
|
||||||
|
guardianName: 'Luis Pérez',
|
||||||
|
guardianPhone: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '1199990000', email: null } }],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const attendeeRow = {
|
const attendeeRow = {
|
||||||
@@ -77,10 +75,8 @@ describe('attendees routes', () => {
|
|||||||
fullName: person.fullName,
|
fullName: person.fullName,
|
||||||
email: person.email,
|
email: person.email,
|
||||||
phone: person.phone,
|
phone: person.phone,
|
||||||
guardianPersonId: 'person-9',
|
guardianName: person.guardianName,
|
||||||
guardianName: 'Luis Pérez',
|
guardianPhone: person.guardianPhone,
|
||||||
guardianPhone: '1199990000',
|
|
||||||
guardianEmail: null,
|
|
||||||
notes: person.notes,
|
notes: person.notes,
|
||||||
createdAt: attendeeRow.createdAt.toISOString(),
|
createdAt: attendeeRow.createdAt.toISOString(),
|
||||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||||
|
|||||||
@@ -39,9 +39,9 @@ describe('GetAttentionOverview', () => {
|
|||||||
db.user.findUnique.mockResolvedValue({ country: 'AR' });
|
db.user.findUnique.mockResolvedValue({ country: 'AR' });
|
||||||
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
|
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
|
||||||
db.attendee.findMany.mockResolvedValue([
|
db.attendee.findMany.mockResolvedValue([
|
||||||
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', createdAt: at(90) },
|
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) },
|
||||||
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardians: [{ guardian: { phone: '1166660000' } }], createdAt: at(90) },
|
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) },
|
||||||
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, createdAt: at(90) },
|
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) },
|
||||||
]);
|
]);
|
||||||
db.classSession.findMany.mockResolvedValue([
|
db.classSession.findMany.mockResolvedValue([
|
||||||
{ id: 's1', groupId: 'g1', startsAt: at(1) },
|
{ id: 's1', groupId: 'g1', startsAt: at(1) },
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { describe, expect, it, mock } from 'bun:test';
|
import { describe, expect, it, mock } from 'bun:test';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
planFeatureRequiredProblem,
|
planFeatureRequiredProblem,
|
||||||
planLimitReachedProblem,
|
planLimitReachedProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case';
|
import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case';
|
||||||
import { CreateGroup } from '@/modules/groups/features/create/use-case';
|
import { CreateGroup } from '@/modules/groups/features/create/use-case';
|
||||||
import { UpdateGroupUseCase } from '@/modules/groups/features/update/use-case';
|
|
||||||
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
|
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
|
||||||
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
|
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
|
||||||
|
|
||||||
@@ -15,10 +14,7 @@ const ownerId = 'owner-1';
|
|||||||
describe('plan guards in the use cases', () => {
|
describe('plan guards in the use cases', () => {
|
||||||
it('does not create a group past the Free limit', async () => {
|
it('does not create a group past the Free limit', async () => {
|
||||||
const unitOfWork = { executeResult: mock() };
|
const unitOfWork = { executeResult: mock() };
|
||||||
const planGuard = {
|
const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) };
|
||||||
canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))),
|
|
||||||
requireFeature: mock(async () => ok(undefined)),
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
|
const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
|
||||||
{} as never,
|
{} as never,
|
||||||
@@ -96,100 +92,4 @@ describe('plan guards in the use cases', () => {
|
|||||||
expect(off.ok).toBe(true);
|
expect(off.ok).toBe(true);
|
||||||
expect(db.group.update).toHaveBeenCalled();
|
expect(db.group.update).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('needs the kidsGroups feature to create a kids group, not a regular one', async () => {
|
|
||||||
const unitOfWork = { executeResult: mock(async () => err({ status: 500 } as never)) };
|
|
||||||
const planGuard = {
|
|
||||||
canCreateGroup: mock(async () => ok(undefined)),
|
|
||||||
requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))),
|
|
||||||
};
|
|
||||||
const useCase = new CreateGroup({ unitOfWork: unitOfWork as never, planGuard });
|
|
||||||
|
|
||||||
const kids = await useCase.execute({ audience: 'KIDS' } as never, ownerId);
|
|
||||||
expect(kids.ok).toBe(false);
|
|
||||||
if (!kids.ok) expect(kids.error).toMatchObject({ status: 402, code: 'plan_feature_required', params: { feature: 'kidsGroups' } });
|
|
||||||
expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'kidsGroups');
|
|
||||||
expect(unitOfWork.executeResult).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
planGuard.requireFeature.mockClear();
|
|
||||||
await useCase.execute({ audience: 'ADULTS' } as never, ownerId);
|
|
||||||
expect(planGuard.requireFeature).not.toHaveBeenCalled();
|
|
||||||
expect(unitOfWork.executeResult).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('needs the kidsGroups feature to turn a group into a kids group, never to go back', async () => {
|
|
||||||
const db = {
|
|
||||||
group: {
|
|
||||||
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'ADULTS' })),
|
|
||||||
update: mock(async () => groupRow({ audience: 'ADULTS' })),
|
|
||||||
},
|
|
||||||
attendee: { count: mock(async () => 0) },
|
|
||||||
};
|
|
||||||
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))) };
|
|
||||||
const useCase = new UpdateGroupUseCase({ db: db as never, planGuard });
|
|
||||||
|
|
||||||
const toKids = await useCase.execute('g1', ownerId, { audience: 'KIDS' });
|
|
||||||
expect(toKids.ok).toBe(false);
|
|
||||||
expect(db.group.update).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
// An existing kids group keeps working after a downgrade: editing it does
|
|
||||||
// not ask for the feature again, and it can go back to adults.
|
|
||||||
db.group.findUnique.mockResolvedValue({ id: 'g1', createdById: ownerId, audience: 'KIDS' });
|
|
||||||
const rename = await useCase.execute('g1', ownerId, { name: 'Natación chicos', audience: 'KIDS' });
|
|
||||||
expect(rename.ok).toBe(true);
|
|
||||||
const toAdults = await useCase.execute('g1', ownerId, { audience: 'ADULTS' });
|
|
||||||
expect(toAdults.ok).toBe(true);
|
|
||||||
expect(planGuard.requireFeature).toHaveBeenCalledTimes(1);
|
|
||||||
expect(db.group.update).toHaveBeenLastCalledWith({ where: { id: 'g1' }, data: { audience: 'ADULTS' } });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not turn a kids group back into adults while a kid has no phone of their own', async () => {
|
|
||||||
const db = {
|
|
||||||
group: {
|
|
||||||
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'KIDS' })),
|
|
||||||
update: mock(),
|
|
||||||
},
|
|
||||||
attendee: { count: mock(async () => 2) },
|
|
||||||
};
|
|
||||||
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { audience: 'ADULTS' });
|
|
||||||
|
|
||||||
expect(result.ok).toBe(false);
|
|
||||||
if (!result.ok) {
|
|
||||||
expect(result.error).toMatchObject({ status: 409, code: 'group_has_kids_without_phone', params: { count: 2 } });
|
|
||||||
}
|
|
||||||
expect(db.attendee.count).toHaveBeenCalledWith({
|
|
||||||
where: { groupId: 'g1', status: { not: 'DROPPED' }, person: { phone: null } },
|
|
||||||
});
|
|
||||||
expect(db.group.update).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('only lets the owner edit the group', async () => {
|
|
||||||
const db = {
|
|
||||||
group: { findUnique: mock(async () => ({ id: 'g1', createdById: 'someone-else', audience: 'ADULTS' })), update: mock() },
|
|
||||||
attendee: { count: mock() },
|
|
||||||
};
|
|
||||||
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { name: 'Otro' });
|
|
||||||
expect(result.ok).toBe(false);
|
|
||||||
if (!result.ok) expect(result.error).toMatchObject({ status: 403, code: 'group_owner_required' });
|
|
||||||
expect(db.group.update).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
function groupRow(overrides: Record<string, unknown> = {}) {
|
|
||||||
const at = new Date('2026-11-01T00:00:00.000Z');
|
|
||||||
return {
|
|
||||||
id: 'g1',
|
|
||||||
name: 'Natación',
|
|
||||||
description: null,
|
|
||||||
createdById: ownerId,
|
|
||||||
createdAt: at,
|
|
||||||
updatedAt: at,
|
|
||||||
days: ['MONDAY'],
|
|
||||||
time: '18:00',
|
|
||||||
capacity: 10,
|
|
||||||
price: 1000,
|
|
||||||
billingType: 'MONTHLY',
|
|
||||||
dueDay: 1,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
/* Kids groups against a real Postgres: the student account belongs to the
|
|
||||||
adult in charge and reaches all of their kids. Skipped unless DB_TESTS=1
|
|
||||||
(`bun run test:db`). Creates its own teacher/groups/people and deletes them. */
|
|
||||||
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
|
||||||
import { PrismaClient } from '@generated/prisma/client';
|
|
||||||
import { PrismaPg } from '@prisma/adapter-pg';
|
|
||||||
import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case';
|
|
||||||
import { InviteStudent } from '@/modules/student-access/features/invite/use-case';
|
|
||||||
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
|
|
||||||
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
|
|
||||||
import { findLinkedAttendee } from '@/modules/student-portal/lib/access';
|
|
||||||
|
|
||||||
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
|
|
||||||
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
||||||
|
|
||||||
describe.skipIf(!url)('cuenta del adulto a cargo (real database)', () => {
|
|
||||||
let db: PrismaClient;
|
|
||||||
let unitOfWork: { executeResult: unknown };
|
|
||||||
const ids = {
|
|
||||||
user: `test-user-${suffix}`,
|
|
||||||
swim: `test-swim-${suffix}`,
|
|
||||||
art: `test-art-${suffix}`,
|
|
||||||
ana: `test-ana-${suffix}`,
|
|
||||||
juan: `test-juan-${suffix}`,
|
|
||||||
sofi: `test-sofi-${suffix}`,
|
|
||||||
tomi: `test-tomi-${suffix}`,
|
|
||||||
other: `test-other-${suffix}`,
|
|
||||||
juanSwim: `test-juan-swim-${suffix}`,
|
|
||||||
sofiArt: `test-sofi-art-${suffix}`,
|
|
||||||
tomiArt: `test-tomi-art-${suffix}`,
|
|
||||||
otherSwim: `test-other-swim-${suffix}`,
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
|
|
||||||
unitOfWork = {
|
|
||||||
executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => {
|
|
||||||
const rollback = Symbol('rollback');
|
|
||||||
try {
|
|
||||||
return await db.$transaction(async (tx) => {
|
|
||||||
const result = await callback(tx);
|
|
||||||
if (!result.ok) throw { [rollback]: result };
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (error && typeof error === 'object' && rollback in error) {
|
|
||||||
return (error as Record<symbol, unknown>)[rollback];
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}) as never,
|
|
||||||
};
|
|
||||||
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
|
|
||||||
await db.group.create({ data: { id: ids.swim, name: 'Natación', audience: 'KIDS', createdById: ids.user } });
|
|
||||||
await db.group.create({ data: { id: ids.art, name: 'Plástica', audience: 'KIDS', createdById: ids.user } });
|
|
||||||
await db.person.create({ data: { id: ids.ana, createdById: ids.user, fullName: 'Ana Pérez', phone: `11${suffix.slice(-8)}` } });
|
|
||||||
for (const [id, fullName] of [
|
|
||||||
[ids.juan, 'Juan Pérez'],
|
|
||||||
[ids.sofi, 'Sofi Pérez'],
|
|
||||||
] as const) {
|
|
||||||
await db.person.create({
|
|
||||||
data: { id, createdById: ids.user, fullName, guardians: { create: { guardianId: ids.ana } } },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
await db.person.create({ data: { id: ids.other, createdById: ids.user, fullName: 'Otro Chico' } });
|
|
||||||
await db.attendee.create({ data: { id: ids.juanSwim, groupId: ids.swim, personId: ids.juan } });
|
|
||||||
await db.attendee.create({ data: { id: ids.sofiArt, groupId: ids.art, personId: ids.sofi } });
|
|
||||||
await db.attendee.create({ data: { id: ids.otherSwim, groupId: ids.swim, personId: ids.other } });
|
|
||||||
|
|
||||||
// A legacy account linked to the kid (before kids groups).
|
|
||||||
await db.studentAccount.create({
|
|
||||||
data: { name: 'Juan Pérez', createdById: ids.user, people: { create: { personId: ids.juan } } },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterAll(async () => {
|
|
||||||
await db.studentAccount.deleteMany({ where: { createdById: ids.user } });
|
|
||||||
await db.user.deleteMany({ where: { id: ids.user } });
|
|
||||||
await db.$disconnect();
|
|
||||||
});
|
|
||||||
|
|
||||||
const invite = (groupId: string, attendeeId: string) =>
|
|
||||||
new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(groupId, attendeeId, ids.user);
|
|
||||||
const accountOf = async (personId: string) =>
|
|
||||||
(await db.studentAccountPerson.findFirst({ where: { personId } }))?.accountId ?? null;
|
|
||||||
|
|
||||||
it('invitar a un chico pasa su cuenta vieja al adulto', async () => {
|
|
||||||
const legacy = await accountOf(ids.juan);
|
|
||||||
const result = await invite(ids.swim, ids.juanSwim);
|
|
||||||
if (!result.ok) throw new Error('invite failed');
|
|
||||||
|
|
||||||
expect(await accountOf(ids.ana)).toBe(legacy);
|
|
||||||
expect(await accountOf(ids.juan)).toBeNull();
|
|
||||||
const account = await db.studentAccount.findUniqueOrThrow({ where: { id: legacy as string } });
|
|
||||||
expect(account.name).toBe('Ana Pérez');
|
|
||||||
|
|
||||||
const token = result.value.url.split('/i/')[1] as string;
|
|
||||||
expect(await new GetStudentLinkInfo({ db }).execute(token)).toMatchObject({
|
|
||||||
ok: true,
|
|
||||||
value: { status: 'valid', name: 'Ana Pérez', groupName: 'Natación' },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('invitar a un hermano reutiliza la cuenta del adulto', async () => {
|
|
||||||
const accountId = await accountOf(ids.ana);
|
|
||||||
const result = await invite(ids.art, ids.sofiArt);
|
|
||||||
if (!result.ok) throw new Error('invite failed');
|
|
||||||
expect(await db.studentAccountPerson.count({ where: { personId: ids.ana } })).toBe(1);
|
|
||||||
expect(await accountOf(ids.ana)).toBe(accountId);
|
|
||||||
|
|
||||||
const juan = await new GetStudentAccess({ db }).execute(ids.swim, ids.juanSwim, ids.user);
|
|
||||||
const sofi = await new GetStudentAccess({ db }).execute(ids.art, ids.sofiArt, ids.user);
|
|
||||||
expect(juan).toMatchObject({ ok: true, value: { status: 'invited' } });
|
|
||||||
expect(sofi).toEqual(juan);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('la cuenta del adulto ve a todos sus chicos, también uno nuevo, y a nadie más', async () => {
|
|
||||||
const accountId = (await accountOf(ids.ana)) as string;
|
|
||||||
|
|
||||||
// A kid added after the invitation shows up without reinviting.
|
|
||||||
await db.person.create({
|
|
||||||
data: { id: ids.tomi, createdById: ids.user, fullName: 'Tomi Pérez', guardians: { create: { guardianId: ids.ana } } },
|
|
||||||
});
|
|
||||||
await db.attendee.create({ data: { id: ids.tomiArt, groupId: ids.art, personId: ids.tomi } });
|
|
||||||
|
|
||||||
const me = await new GetStudentMe({ db }).execute(accountId);
|
|
||||||
if (!me.ok) throw new Error('me failed');
|
|
||||||
expect(me.value.account.name).toBe('Ana Pérez');
|
|
||||||
expect(me.value.students.map((s) => [s.fullName, s.groupName])).toEqual([
|
|
||||||
['Juan Pérez', 'Natación'],
|
|
||||||
['Sofi Pérez', 'Plástica'],
|
|
||||||
['Tomi Pérez', 'Plástica'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
for (const attendeeId of [ids.juanSwim, ids.sofiArt, ids.tomiArt]) {
|
|
||||||
expect(await findLinkedAttendee(db, accountId, attendeeId)).not.toBeNull();
|
|
||||||
}
|
|
||||||
expect(await findLinkedAttendee(db, accountId, ids.otherSwim)).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -42,7 +42,6 @@ const group = {
|
|||||||
inviteToken: null,
|
inviteToken: null,
|
||||||
autoPaymentReminders: false,
|
autoPaymentReminders: false,
|
||||||
autoReengagement: false,
|
autoReengagement: false,
|
||||||
audience: 'ADULTS',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function makeApp(userValue: unknown) {
|
function makeApp(userValue: unknown) {
|
||||||
@@ -224,7 +223,6 @@ describe('groups routes', () => {
|
|||||||
price: 500,
|
price: 500,
|
||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
audience: 'ADULTS',
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(prisma.groupMember.create).toHaveBeenCalledWith({
|
expect(prisma.groupMember.create).toHaveBeenCalledWith({
|
||||||
|
|||||||
@@ -1,219 +0,0 @@
|
|||||||
import { describe, expect, it, mock } from 'bun:test';
|
|
||||||
import { ok } from '@gruperly/shared';
|
|
||||||
import { CreateAttendeeUseCase } from '@/modules/attendees/features/create/use-case';
|
|
||||||
import { UpdateAttendeeGuardian } from '@/modules/attendees/features/update-guardian/use-case';
|
|
||||||
import { contactPhone, findPersonSummaryByPhone } from '@/modules/people/lib/people';
|
|
||||||
|
|
||||||
const ownerId = 'owner-1';
|
|
||||||
const at = new Date('2026-11-01T00:00:00.000Z');
|
|
||||||
|
|
||||||
function kidsGroup(overrides: Record<string, unknown> = {}) {
|
|
||||||
return { id: 'g1', createdById: ownerId, capacity: null, audience: 'KIDS', members: [], ...overrides };
|
|
||||||
}
|
|
||||||
|
|
||||||
function createdAttendee(guardian = { id: 'adult-1', fullName: 'Ana Pérez', phone: '1155550000', email: null }) {
|
|
||||||
return {
|
|
||||||
id: 'att-1',
|
|
||||||
groupId: 'g1',
|
|
||||||
personId: 'kid-1',
|
|
||||||
notifyToken: null,
|
|
||||||
createdAt: at,
|
|
||||||
updatedAt: at,
|
|
||||||
person: { id: 'kid-1', fullName: 'Juan Pérez', email: null, phone: null, notes: null, guardians: [{ guardian }] },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeDb(overrides: { adult?: unknown; sameNameKid?: unknown } = {}) {
|
|
||||||
return {
|
|
||||||
group: { findUnique: mock(async () => kidsGroup()) },
|
|
||||||
person: {
|
|
||||||
// 1st call: the adult by phone. 2nd: a kid of that adult with the same name.
|
|
||||||
findFirst: mock()
|
|
||||||
.mockResolvedValueOnce(overrides.adult ?? null)
|
|
||||||
.mockResolvedValueOnce(overrides.sameNameKid ?? null),
|
|
||||||
},
|
|
||||||
attendee: {
|
|
||||||
findFirst: mock(async () => null),
|
|
||||||
count: mock(async () => 0),
|
|
||||||
create: mock(async () => createdAttendee()),
|
|
||||||
update: mock(),
|
|
||||||
},
|
|
||||||
groupWaitlistEntry: { findFirst: mock(), create: mock() },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const planGuard = { canAddAttendees: mock(async () => ok(undefined)) };
|
|
||||||
const guardian = { fullName: 'Ana Pérez', phone: '11 5555-0000' };
|
|
||||||
|
|
||||||
describe('kids groups: adding a kid', () => {
|
|
||||||
it('asks for the adult in charge', async () => {
|
|
||||||
const db = makeDb();
|
|
||||||
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
|
|
||||||
firstName: 'Juan',
|
|
||||||
lastName: 'Pérez',
|
|
||||||
phone: '1144440000',
|
|
||||||
});
|
|
||||||
expect(result.ok).toBe(false);
|
|
||||||
if (!result.ok) expect(result.error).toMatchObject({ status: 400, code: 'guardian_required' });
|
|
||||||
expect(db.attendee.create).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('creates the kid with no phone and a new adult in charge', async () => {
|
|
||||||
const db = makeDb();
|
|
||||||
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
|
|
||||||
firstName: 'Juan',
|
|
||||||
lastName: 'Pérez',
|
|
||||||
guardian,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.ok).toBe(true);
|
|
||||||
if (result.ok && result.value.outcome === 'created') {
|
|
||||||
expect(result.value.attendee).toMatchObject({ guardianName: 'Ana Pérez', guardianPhone: '1155550000', phone: null });
|
|
||||||
}
|
|
||||||
expect(db.attendee.create).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
data: {
|
|
||||||
group: { connect: { id: 'g1' } },
|
|
||||||
person: {
|
|
||||||
create: {
|
|
||||||
createdById: ownerId,
|
|
||||||
fullName: 'Juan Pérez',
|
|
||||||
phone: null,
|
|
||||||
email: null,
|
|
||||||
notes: null,
|
|
||||||
guardians: {
|
|
||||||
create: {
|
|
||||||
guardian: { create: { createdById: ownerId, fullName: 'Ana Pérez', phone: '1155550000', email: null } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('links a sibling to the adult the teacher already has (same phone)', async () => {
|
|
||||||
const db = makeDb({ adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] } });
|
|
||||||
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
|
|
||||||
firstName: 'Sofía',
|
|
||||||
lastName: 'Pérez',
|
|
||||||
guardian,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.ok).toBe(true);
|
|
||||||
// The sibling lookup: same adult, same name, case-insensitive.
|
|
||||||
expect(db.person.findFirst.mock.calls[1]?.[0]).toMatchObject({
|
|
||||||
where: {
|
|
||||||
createdById: ownerId,
|
|
||||||
fullName: { equals: 'Sofía Pérez', mode: 'insensitive' },
|
|
||||||
guardians: { some: { guardianId: 'adult-1' } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({
|
|
||||||
data: { person: { create: { fullName: 'Sofía Pérez', guardians: { create: { guardian: { connect: { id: 'adult-1' } } } } } } },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('recognizes the same kid of the same adult instead of creating a twin', async () => {
|
|
||||||
const db = makeDb({
|
|
||||||
adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] },
|
|
||||||
sameNameKid: { id: 'kid-1', fullName: 'Juan Pérez', phone: null, guardians: [] },
|
|
||||||
});
|
|
||||||
db.attendee.findFirst.mockResolvedValue({ id: 'att-1', status: 'ACTIVE' } as never);
|
|
||||||
|
|
||||||
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
|
|
||||||
firstName: 'juan',
|
|
||||||
lastName: 'pérez',
|
|
||||||
guardian,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.ok).toBe(false);
|
|
||||||
if (!result.ok) expect(result.error).toMatchObject({ code: 'attendee_already_registered' });
|
|
||||||
expect(db.attendee.create).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps asking for a phone in an adults group', async () => {
|
|
||||||
const db = makeDb();
|
|
||||||
db.group.findUnique.mockResolvedValue(kidsGroup({ audience: 'ADULTS' }));
|
|
||||||
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
|
|
||||||
firstName: 'Ana',
|
|
||||||
lastName: '',
|
|
||||||
});
|
|
||||||
expect(result.ok).toBe(true);
|
|
||||||
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({ data: { person: { create: { phone: null } } } });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('kids groups: contact', () => {
|
|
||||||
it('reaches a kid through the adult in charge', () => {
|
|
||||||
expect(contactPhone({ phone: '1144440000', guardians: [{ guardian: { phone: '1155550000' } }] })).toBe('1155550000');
|
|
||||||
expect(contactPhone({ phone: '1144440000', guardians: [] })).toBe('1144440000');
|
|
||||||
expect(contactPhone({ phone: null })).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the lookup by phone offers the kids of that adult', async () => {
|
|
||||||
const db = {
|
|
||||||
person: {
|
|
||||||
findFirst: mock(async () => ({ id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] })),
|
|
||||||
findUnique: mock(async () => ({
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
child: {
|
|
||||||
id: 'kid-1',
|
|
||||||
fullName: 'Juan Pérez',
|
|
||||||
attendees: [{ id: 'att-1', groupId: 'g1', status: 'ACTIVE', group: { name: 'Natación' } }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const summary = await findPersonSummaryByPhone(db as never, ownerId, '1155550000');
|
|
||||||
expect(summary?.children).toEqual([
|
|
||||||
{ id: 'kid-1', fullName: 'Juan Pérez', groups: [{ attendeeId: 'att-1', groupId: 'g1', groupName: 'Natación', status: 'ACTIVE' }] },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('kids groups: editing the adult in charge', () => {
|
|
||||||
function guardianDb(person: Record<string, unknown>) {
|
|
||||||
return {
|
|
||||||
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [] })) },
|
|
||||||
attendee: {
|
|
||||||
findFirst: mock(async () => ({ personId: 'kid-1', person: { id: 'kid-1', ...person } })),
|
|
||||||
findUniqueOrThrow: mock(async () => createdAttendee()),
|
|
||||||
},
|
|
||||||
person: { update: mock(), findFirst: mock(async () => null), create: mock(async () => ({ id: 'adult-2' })) },
|
|
||||||
personGuardian: { create: mock() },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
it('edits the adult the kid already has (shared with the siblings)', async () => {
|
|
||||||
const db = guardianDb({ phone: null, guardians: [{ guardian: { id: 'adult-1', fullName: 'Ana', phone: '1155550000', email: null } }] });
|
|
||||||
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
|
|
||||||
groupId: 'g1',
|
|
||||||
attendeeId: 'att-1',
|
|
||||||
userId: ownerId,
|
|
||||||
input: { fullName: 'Ana Pérez', phone: '11 5555-0001', email: 'ana@example.com' },
|
|
||||||
});
|
|
||||||
expect(result.ok).toBe(true);
|
|
||||||
expect(db.person.update).toHaveBeenCalledWith({
|
|
||||||
where: { id: 'adult-1' },
|
|
||||||
data: { fullName: 'Ana Pérez', phone: '1155550001', email: 'ana@example.com' },
|
|
||||||
});
|
|
||||||
expect(db.personGuardian.create).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('links a new adult when the kid had none', async () => {
|
|
||||||
const db = guardianDb({ phone: null, guardians: [] });
|
|
||||||
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
|
|
||||||
groupId: 'g1',
|
|
||||||
attendeeId: 'att-1',
|
|
||||||
userId: ownerId,
|
|
||||||
input: { fullName: 'Ana Pérez', phone: '1155550000' },
|
|
||||||
});
|
|
||||||
expect(result.ok).toBe(true);
|
|
||||||
expect(db.personGuardian.create).toHaveBeenCalledWith({ data: { childId: 'kid-1', guardianId: 'adult-2' } });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -207,7 +207,6 @@ describe('onboarding routes', () => {
|
|||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
autoPaymentReminders: false,
|
autoPaymentReminders: false,
|
||||||
autoReengagement: false,
|
autoReengagement: false,
|
||||||
audience: 'ADULTS',
|
|
||||||
},
|
},
|
||||||
onboardingCompleted: true,
|
onboardingCompleted: true,
|
||||||
});
|
});
|
||||||
@@ -221,7 +220,6 @@ describe('onboarding routes', () => {
|
|||||||
price: 150.5,
|
price: 150.5,
|
||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
audience: 'ADULTS',
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(prisma.groupMember.create).toHaveBeenCalledWith({
|
expect(prisma.groupMember.create).toHaveBeenCalledWith({
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
|
|||||||
currency: 'ARS',
|
currency: 'ARS',
|
||||||
dueDate: new Date('2026-10-20T15:00:00.000Z'),
|
dueDate: new Date('2026-10-20T15:00:00.000Z'),
|
||||||
checkoutUrl: `https://mpago.la/${id}`,
|
checkoutUrl: `https://mpago.la/${id}`,
|
||||||
attendee: { id: attendee.id, person: { phone: null, ...attendee } },
|
attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -174,7 +174,7 @@ describe('payment reminders', () => {
|
|||||||
|
|
||||||
it('falls back to the guardian phone and skips members without a usable one', async () => {
|
it('falls back to the guardian phone and skips members without a usable one', async () => {
|
||||||
db.payment.findMany.mockResolvedValue([
|
db.payment.findMany.mockResolvedValue([
|
||||||
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardians: [{ guardian: { phone: '1123456789' } }] }),
|
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }),
|
||||||
payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
|
payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -62,11 +62,6 @@ export function PlanLimitsCard({ plan, limits }: { plan: Plan; limits: PlanLimit
|
|||||||
checked={draft.whatsappAutomations}
|
checked={draft.whatsappAutomations}
|
||||||
onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })}
|
onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })}
|
||||||
/>
|
/>
|
||||||
<FeatureSwitch
|
|
||||||
label={t('plans.limits.kidsGroups')}
|
|
||||||
checked={draft.kidsGroups}
|
|
||||||
onChange={(kidsGroups) => setDraft({ ...draft, kidsGroups })}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<LimitsImpact plan={plan} draft={draft} current={limits} />
|
<LimitsImpact plan={plan} draft={draft} current={limits} />
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { useId, useState } from 'react'
|
|||||||
import { Check, Copy, MessageCircle } from 'lucide-react'
|
import { Check, Copy, MessageCircle } from 'lucide-react'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { reachPhone } from './detail'
|
|
||||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
@@ -19,7 +18,7 @@ export function AbsenceLinkSection() {
|
|||||||
const url = token ? `${window.location.origin}/report-absence/${token}` : null
|
const url = token ? `${window.location.origin}/report-absence/${token}` : null
|
||||||
if (!attendee || !url) return null
|
if (!attendee || !url) return null
|
||||||
|
|
||||||
const phoneDigits = reachPhone(attendee)?.replace(/\D/g, '') ?? ''
|
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
|
||||||
const shareUrl = phoneDigits
|
const shareUrl = phoneDigits
|
||||||
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
||||||
t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }),
|
t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }),
|
||||||
|
|||||||
@@ -3,16 +3,15 @@ import { formatPhoneDisplay } from '../../lib/format'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { reachPhone } from './detail'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeeContactActions() {
|
export function AttendeeContactActions() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
const { t } = useTranslation(['attendeeDetail', 'common'])
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
const phone = attendee ? reachPhone(attendee) : null
|
const phone = attendee?.phone
|
||||||
const digits = phone?.replace(/\D/g, '') ?? ''
|
const digits = phone?.replace(/\D/g, '') ?? ''
|
||||||
const label = attendee?.guardianName ?? formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember')
|
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { type ReactNode, useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Mail, Phone } from 'lucide-react'
|
import { Mail, Phone } from 'lucide-react'
|
||||||
import { ApiError } from '../../lib/api'
|
import { ApiError } from '../../lib/api'
|
||||||
import { formatPhoneDisplay } from '../../lib/format'
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { AttendeeContactForm } from './AttendeeContactForm'
|
import { AttendeeContactForm } from './AttendeeContactForm'
|
||||||
import { contactEmailError } from './detail'
|
import { contactEmailError } from './detail'
|
||||||
import { PhoneRowActions } from './PhoneRowActions'
|
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
@@ -100,12 +99,8 @@ export function AttendeeContactSection() {
|
|||||||
icon={Phone}
|
icon={Phone}
|
||||||
label={t('contact.phone')}
|
label={t('contact.phone')}
|
||||||
value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')}
|
value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')}
|
||||||
|
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
|
||||||
placeholder={!attendee.phone}
|
placeholder={!attendee.phone}
|
||||||
actions={
|
|
||||||
attendee.phone ? (
|
|
||||||
<PhoneRowActions phone={attendee.phone} name={attendee.fullName} />
|
|
||||||
) : undefined
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
<ContactRow
|
<ContactRow
|
||||||
icon={Mail}
|
icon={Mail}
|
||||||
@@ -126,11 +121,9 @@ type ContactRowProps = {
|
|||||||
value: string
|
value: string
|
||||||
href?: string
|
href?: string
|
||||||
placeholder: boolean
|
placeholder: boolean
|
||||||
/** Acciones a la derecha (p. ej. WhatsApp y Llamar): la fila deja de ser un link. */
|
|
||||||
actions?: ReactNode
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ContactRow({ icon: Icon, label, value, href, placeholder, actions }: ContactRowProps) {
|
function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) {
|
||||||
const content = (
|
const content = (
|
||||||
<>
|
<>
|
||||||
<Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
@@ -140,12 +133,11 @@ export function ContactRow({ icon: Icon, label, value, href, placeholder, action
|
|||||||
{value}
|
{value}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
{actions}
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
||||||
const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2'
|
const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2'
|
||||||
return href && !actions ? (
|
return href ? (
|
||||||
<a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}>
|
<a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}>
|
||||||
{content}
|
{content}
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import type {
|
|||||||
GroupListItem,
|
GroupListItem,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
UpdateAttendee,
|
UpdateAttendee,
|
||||||
GuardianInput,
|
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { errorMessage } from '../../i18n'
|
import { errorMessage } from '../../i18n'
|
||||||
import { i18n } from '../../i18n/instance'
|
import { i18n } from '../../i18n/instance'
|
||||||
@@ -19,7 +18,6 @@ import {
|
|||||||
getAttendeeHistory,
|
getAttendeeHistory,
|
||||||
getGroup,
|
getGroup,
|
||||||
getGroupAttendee,
|
getGroupAttendee,
|
||||||
updateAttendeeGuardian,
|
|
||||||
getGroups,
|
getGroups,
|
||||||
getGroupWaitlist,
|
getGroupWaitlist,
|
||||||
moveGroupAttendee,
|
moveGroupAttendee,
|
||||||
@@ -44,10 +42,6 @@ type AttendeeDetailContextValue = {
|
|||||||
endContactEdit: () => void
|
endContactEdit: () => void
|
||||||
saveAttendee: (input: UpdateAttendee) => Promise<void>
|
saveAttendee: (input: UpdateAttendee) => Promise<void>
|
||||||
isUpdatingAttendee: boolean
|
isUpdatingAttendee: boolean
|
||||||
/** KIDS: el contacto del chico es su adulto a cargo. */
|
|
||||||
isKidsGroup: boolean
|
|
||||||
saveGuardian: (input: GuardianInput) => Promise<void>
|
|
||||||
isUpdatingGuardian: boolean
|
|
||||||
isRemoveDialogOpen: boolean
|
isRemoveDialogOpen: boolean
|
||||||
openRemoveDialog: () => void
|
openRemoveDialog: () => void
|
||||||
closeRemoveDialog: () => void
|
closeRemoveDialog: () => void
|
||||||
@@ -112,19 +106,6 @@ export function AttendeeDetailProvider({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const guardianMutation = useMutation({
|
|
||||||
mutationFn: (input: GuardianInput) => updateAttendeeGuardian(groupId, attendeeId, input),
|
|
||||||
onSuccess: (updated) => {
|
|
||||||
queryClient.setQueryData<AttendeeDetailDto>(
|
|
||||||
['group-attendee', groupId, attendeeId],
|
|
||||||
(current) => (current ? { ...current, ...updated } : current),
|
|
||||||
)
|
|
||||||
// El adulto es de todos sus chicos: cambia también en las fichas de los hermanos.
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees'] })
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// Same key the analytics screen uses: both read the same history and do not
|
// Same key the analytics screen uses: both read the same history and do not
|
||||||
// clobber each other's cache.
|
// clobber each other's cache.
|
||||||
const historyQuery = useQuery({
|
const historyQuery = useQuery({
|
||||||
@@ -237,11 +218,6 @@ export function AttendeeDetailProvider({
|
|||||||
await updateMutation.mutateAsync(input)
|
await updateMutation.mutateAsync(input)
|
||||||
},
|
},
|
||||||
isUpdatingAttendee: updateMutation.isPending,
|
isUpdatingAttendee: updateMutation.isPending,
|
||||||
isKidsGroup: groupQuery.data?.audience === 'KIDS',
|
|
||||||
saveGuardian: async (input) => {
|
|
||||||
await guardianMutation.mutateAsync(input)
|
|
||||||
},
|
|
||||||
isUpdatingGuardian: guardianMutation.isPending,
|
|
||||||
isRemoveDialogOpen,
|
isRemoveDialogOpen,
|
||||||
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
openRemoveDialog: () => setIsRemoveDialogOpen(true),
|
||||||
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
closeRemoveDialog: () => setIsRemoveDialogOpen(false),
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import { AttendeeContactActions } from './AttendeeContactActions'
|
|||||||
import { AttendeeContactSection } from './AttendeeContactSection'
|
import { AttendeeContactSection } from './AttendeeContactSection'
|
||||||
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
||||||
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
||||||
import { GuardianSection } from './GuardianSection'
|
|
||||||
import { OtherGroupsSection } from './OtherGroupsSection'
|
import { OtherGroupsSection } from './OtherGroupsSection'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { ChangeGroupDialog } from './ChangeGroupDialog'
|
import { ChangeGroupDialog } from './ChangeGroupDialog'
|
||||||
@@ -92,7 +91,6 @@ export function AttendeeDetailView() {
|
|||||||
|
|
||||||
<div className="mt-6">
|
<div className="mt-6">
|
||||||
<AttendeeContactSection />
|
<AttendeeContactSection />
|
||||||
<GuardianSection />
|
|
||||||
<OtherGroupsSection />
|
<OtherGroupsSection />
|
||||||
<StudentAccessSection />
|
<StudentAccessSection />
|
||||||
<AttendeePaymentsSection />
|
<AttendeePaymentsSection />
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
import { formatPhoneDisplay } from '../../lib/format'
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { reachPhone } from './detail'
|
|
||||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
@@ -16,7 +15,7 @@ export function AttendeePhoneLine() {
|
|||||||
const { copied, copy } = useCopyToClipboard()
|
const { copied, copy } = useCopyToClipboard()
|
||||||
const { t } = useTranslation(['attendeeDetail', 'common'])
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
const phone = attendee ? reachPhone(attendee) : null
|
const phone = attendee?.phone
|
||||||
const label = formatPhoneDisplay(phone)
|
const label = formatPhoneDisplay(phone)
|
||||||
if (!phone || !label) return null
|
if (!phone || !label) return null
|
||||||
|
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { Loader2, Mail, Phone, UserRound, Users } from 'lucide-react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
import { Button, Input } from '../../components/ui'
|
|
||||||
import { ApiError } from '../../lib/api'
|
|
||||||
import { formatPhoneDisplay } from '../../lib/format'
|
|
||||||
import { ContactRow } from './AttendeeContactSection'
|
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
|
||||||
import { contactEmailError } from './detail'
|
|
||||||
import { PhoneRowActions } from './PhoneRowActions'
|
|
||||||
import { Section } from './Section'
|
|
||||||
|
|
||||||
/* El adulto a cargo de un chico: es una persona propia (compartida entre
|
|
||||||
hermanos), así que editarlo cambia en la ficha de todos sus chicos. Se
|
|
||||||
muestra si el chico tiene adulto o si el grupo es de chicos (para cargarlo). */
|
|
||||||
export function GuardianSection() {
|
|
||||||
const { attendee, isKidsGroup, saveGuardian, isUpdatingGuardian } = useAttendeeDetail()
|
|
||||||
const { t } = useTranslation(['attendeeDetail', 'common'])
|
|
||||||
const [isEditing, setIsEditing] = useState(false)
|
|
||||||
const [fullName, setFullName] = useState('')
|
|
||||||
const [phone, setPhone] = useState('')
|
|
||||||
const [email, setEmail] = useState('')
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
|
|
||||||
if (!attendee || (!attendee.guardianPersonId && !isKidsGroup)) return null
|
|
||||||
const hasGuardian = Boolean(attendee.guardianPersonId)
|
|
||||||
|
|
||||||
const beginEdit = () => {
|
|
||||||
setFullName(attendee.guardianName ?? '')
|
|
||||||
setPhone(attendee.guardianPhone ?? '')
|
|
||||||
setEmail(attendee.guardianEmail ?? '')
|
|
||||||
setError(null)
|
|
||||||
setIsEditing(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
const save = async () => {
|
|
||||||
if (!fullName.trim() || phone.replace(/\D/g, '').length < 6) {
|
|
||||||
setError(t('guardian.required'))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const emailError = contactEmailError(email)
|
|
||||||
if (emailError) {
|
|
||||||
setError(emailError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await saveGuardian({ fullName: fullName.trim(), phone: phone.trim(), email: email.trim() || undefined })
|
|
||||||
setIsEditing(false)
|
|
||||||
} catch (err) {
|
|
||||||
setError(
|
|
||||||
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
|
|
||||||
? t('contact.phoneTaken')
|
|
||||||
: t('contact.saveError'),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const siblings = attendee.siblings.map((sibling) => sibling.fullName).join(', ')
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Section
|
|
||||||
id="attendee-guardian"
|
|
||||||
title={t('guardian.title')}
|
|
||||||
trailing={
|
|
||||||
!isEditing ? (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={beginEdit}
|
|
||||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
|
||||||
>
|
|
||||||
{hasGuardian ? t('contact.edit') : t('guardian.add')}
|
|
||||||
</button>
|
|
||||||
) : null
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{isEditing ? (
|
|
||||||
<div className="space-y-3 px-3 pb-1">
|
|
||||||
<Input
|
|
||||||
value={fullName}
|
|
||||||
onChange={(event) => setFullName(event.target.value)}
|
|
||||||
autoFocus
|
|
||||||
autoComplete="name"
|
|
||||||
placeholder={t('guardian.namePlaceholder')}
|
|
||||||
aria-label={t('guardian.name')}
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="tel"
|
|
||||||
value={phone}
|
|
||||||
onChange={(event) => setPhone(event.target.value)}
|
|
||||||
autoComplete="tel"
|
|
||||||
placeholder={t('contact.phone')}
|
|
||||||
aria-label={t('contact.phone')}
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(event) => setEmail(event.target.value)}
|
|
||||||
autoComplete="email"
|
|
||||||
placeholder={t('contact.email')}
|
|
||||||
aria-label={t('contact.email')}
|
|
||||||
/>
|
|
||||||
{hasGuardian && attendee.siblings.length > 0 ? (
|
|
||||||
<p className="text-xs text-secondary">{t('guardian.shared')}</p>
|
|
||||||
) : null}
|
|
||||||
{error ? (
|
|
||||||
<p role="alert" className="text-sm text-danger-fg">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
<div className="flex justify-end gap-2 pt-1">
|
|
||||||
<Button variant="ghost" onClick={() => setIsEditing(false)} disabled={isUpdatingGuardian}>
|
|
||||||
{t('common:actions.cancel')}
|
|
||||||
</Button>
|
|
||||||
<Button variant="primary" onClick={() => void save()} disabled={isUpdatingGuardian}>
|
|
||||||
{isUpdatingGuardian ? <Loader2 className="size-4 animate-spin" /> : null}
|
|
||||||
{t('common:actions.save')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : hasGuardian ? (
|
|
||||||
<div className="divide-y divide-border/60">
|
|
||||||
<ContactRow icon={UserRound} label={t('guardian.name')} value={attendee.guardianName ?? ''} placeholder={false} />
|
|
||||||
<ContactRow
|
|
||||||
icon={Phone}
|
|
||||||
label={t('contact.phone')}
|
|
||||||
value={formatPhoneDisplay(attendee.guardianPhone) ?? t('contact.addPhone')}
|
|
||||||
placeholder={!attendee.guardianPhone}
|
|
||||||
actions={
|
|
||||||
attendee.guardianPhone ? (
|
|
||||||
<PhoneRowActions
|
|
||||||
phone={attendee.guardianPhone}
|
|
||||||
name={attendee.guardianName ?? attendee.fullName}
|
|
||||||
/>
|
|
||||||
) : undefined
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<ContactRow
|
|
||||||
icon={Mail}
|
|
||||||
label={t('contact.email')}
|
|
||||||
value={attendee.guardianEmail ?? t('contact.addEmail')}
|
|
||||||
href={attendee.guardianEmail ? `mailto:${attendee.guardianEmail}` : undefined}
|
|
||||||
placeholder={!attendee.guardianEmail}
|
|
||||||
/>
|
|
||||||
{siblings ? (
|
|
||||||
<ContactRow icon={Users} label={t('guardian.siblings')} value={siblings} placeholder={false} />
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="px-3 text-sm text-secondary">{t('guardian.missing')}</p>
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -16,8 +16,6 @@ type InviteToAppSheetProps = {
|
|||||||
groupName: string
|
groupName: string
|
||||||
attendeeId: string
|
attendeeId: string
|
||||||
fullName: string
|
fullName: string
|
||||||
/** Kids groups: the account (and the message) belong to the adult in charge. */
|
|
||||||
guardianName?: string | null
|
|
||||||
hasPhone: boolean
|
hasPhone: boolean
|
||||||
/** Reinviting closes the current access: the copy says so. */
|
/** Reinviting closes the current access: the copy says so. */
|
||||||
reinvite: boolean
|
reinvite: boolean
|
||||||
@@ -33,7 +31,6 @@ export function InviteToAppSheet({
|
|||||||
groupName,
|
groupName,
|
||||||
attendeeId,
|
attendeeId,
|
||||||
fullName,
|
fullName,
|
||||||
guardianName,
|
|
||||||
hasPhone,
|
hasPhone,
|
||||||
reinvite,
|
reinvite,
|
||||||
}: InviteToAppSheetProps) {
|
}: InviteToAppSheetProps) {
|
||||||
@@ -42,7 +39,6 @@ export function InviteToAppSheet({
|
|||||||
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
|
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
|
||||||
const [copied, setCopied] = useState(false)
|
const [copied, setCopied] = useState(false)
|
||||||
const firstName = fullName.split(' ')[0] ?? fullName
|
const firstName = fullName.split(' ')[0] ?? fullName
|
||||||
const guardianFirstName = guardianName ? (guardianName.split(' ')[0] ?? guardianName) : null
|
|
||||||
|
|
||||||
const mutation = useMutation({
|
const mutation = useMutation({
|
||||||
mutationFn: () => inviteStudent(groupId, attendeeId),
|
mutationFn: () => inviteStudent(groupId, attendeeId),
|
||||||
@@ -67,7 +63,7 @@ export function InviteToAppSheet({
|
|||||||
const popup = window.open('', '_blank')
|
const popup = window.open('', '_blank')
|
||||||
try {
|
try {
|
||||||
const result = await ensureInvitation()
|
const result = await ensureInvitation()
|
||||||
const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url, guardianFirstName))
|
const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url))
|
||||||
const target = result.whatsappPhone
|
const target = result.whatsappPhone
|
||||||
? `https://wa.me/${result.whatsappPhone.replace(/\D/g, '')}?text=${text}`
|
? `https://wa.me/${result.whatsappPhone.replace(/\D/g, '')}?text=${text}`
|
||||||
: `https://wa.me/?text=${text}`
|
: `https://wa.me/?text=${text}`
|
||||||
@@ -95,12 +91,7 @@ export function InviteToAppSheet({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const preview = invitationMessage(
|
const preview = invitationMessage(firstName, groupName, invitation?.url ?? t('inviteSheet.linkPlaceholder'))
|
||||||
firstName,
|
|
||||||
groupName,
|
|
||||||
invitation?.url ?? t('inviteSheet.linkPlaceholder'),
|
|
||||||
guardianFirstName,
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet
|
<Sheet
|
||||||
@@ -109,10 +100,8 @@ export function InviteToAppSheet({
|
|||||||
title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')}
|
title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')}
|
||||||
description={
|
description={
|
||||||
reinvite
|
reinvite
|
||||||
? t('inviteSheet.descriptionReinvite', { name: guardianFirstName ?? firstName })
|
? t('inviteSheet.descriptionReinvite', { name: firstName })
|
||||||
: guardianFirstName
|
: t('inviteSheet.description', { name: firstName })
|
||||||
? t('inviteSheet.descriptionGuardian', { guardian: guardianFirstName, name: firstName })
|
|
||||||
: t('inviteSheet.description', { name: firstName })
|
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
import { MessageCircle, Phone } from 'lucide-react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
|
|
||||||
const ICON_ACTION_CLASS =
|
|
||||||
'inline-flex size-11 shrink-0 items-center justify-center rounded-lg text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
|
||||||
|
|
||||||
/* WhatsApp y Llamar al número de la fila. Los dígitos se arman igual que en
|
|
||||||
`AttendeeContactActions`, así los dos lugares abren el mismo número. */
|
|
||||||
export function PhoneRowActions({ phone, name }: { phone: string; name: string }) {
|
|
||||||
const { t } = useTranslation('attendeeDetail')
|
|
||||||
const digits = phone.replace(/\D/g, '')
|
|
||||||
if (!digits) return null
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1">
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${digits}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
aria-label={t('actions.whatsappLabel', { name })}
|
|
||||||
title={t('actions.whatsappLabel', { name })}
|
|
||||||
className={ICON_ACTION_CLASS}
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-4" aria-hidden="true" />
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
href={`tel:${digits}`}
|
|
||||||
aria-label={t('actions.callLabel', { name })}
|
|
||||||
title={t('actions.callLabel', { name })}
|
|
||||||
className={ICON_ACTION_CLASS}
|
|
||||||
>
|
|
||||||
<Phone className="size-4" aria-hidden="true" />
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -76,7 +76,6 @@ export function StudentAccessSection() {
|
|||||||
groupName={groupName ?? t('access.yourGroup')}
|
groupName={groupName ?? t('access.yourGroup')}
|
||||||
attendeeId={attendee.id}
|
attendeeId={attendee.id}
|
||||||
fullName={attendee.fullName}
|
fullName={attendee.fullName}
|
||||||
guardianName={attendee.guardianName}
|
|
||||||
hasPhone={hasPhone}
|
hasPhone={hasPhone}
|
||||||
reinvite={invited}
|
reinvite={invited}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -3,12 +3,6 @@ import { UpdateAttendeeSchema } from '@gruperly/shared'
|
|||||||
import { validationMessage } from '../../i18n/validation'
|
import { validationMessage } from '../../i18n/validation'
|
||||||
import { i18n } from '../../i18n/instance'
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
/* El número por el que se contacta al miembro: el del adulto a cargo si es un
|
|
||||||
chico (es quien responde por él), si no el suyo. Misma regla que el backend. */
|
|
||||||
export function reachPhone(attendee: { phone: string | null; guardianPhone: string | null }): string | null {
|
|
||||||
return attendee.guardianPhone ?? attendee.phone
|
|
||||||
}
|
|
||||||
|
|
||||||
export function contactEmailError(email: string): string | null {
|
export function contactEmailError(email: string): string | null {
|
||||||
const result = UpdateAttendeeSchema.safeParse({ email })
|
const result = UpdateAttendeeSchema.safeParse({ email })
|
||||||
if (result.success) return null
|
if (result.success) return null
|
||||||
|
|||||||
@@ -38,19 +38,6 @@ export function formatSince(iso: string): string {
|
|||||||
return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' })
|
return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' })
|
||||||
}
|
}
|
||||||
|
|
||||||
/* With an adult in charge the message goes to the adult, about the kid. */
|
export function invitationMessage(firstName: string, groupName: string, url: string): string {
|
||||||
export function invitationMessage(
|
return i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url })
|
||||||
firstName: string,
|
|
||||||
groupName: string,
|
|
||||||
url: string,
|
|
||||||
guardianFirstName?: string | null,
|
|
||||||
): string {
|
|
||||||
return guardianFirstName
|
|
||||||
? i18n.t('attendeeDetail:inviteSheet.messageGuardian', {
|
|
||||||
guardian: guardianFirstName,
|
|
||||||
name: firstName,
|
|
||||||
group: groupName,
|
|
||||||
url,
|
|
||||||
})
|
|
||||||
: i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url })
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ export function planFeatureList(limits: PlanLimits): { label: string; included:
|
|||||||
},
|
},
|
||||||
{ label: i18n.t('billing:features.mpCharges'), included: limits.mpCharges },
|
{ label: i18n.t('billing:features.mpCharges'), included: limits.mpCharges },
|
||||||
{ label: i18n.t('billing:features.whatsapp'), included: limits.whatsappAutomations },
|
{ label: i18n.t('billing:features.whatsapp'), included: limits.whatsappAutomations },
|
||||||
{ label: i18n.t('billing:features.kidsGroups'), included: limits.kidsGroups },
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
|
||||||
import type { CreateFirstGroup, GroupDto } from '@gruperly/shared'
|
|
||||||
import { ChevronLeft, Loader2 } from 'lucide-react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
import { errorMessage } from '../../i18n'
|
|
||||||
import { getGroup, updateGroup } from '../../lib/api'
|
|
||||||
import { GroupForm } from './GroupForm'
|
|
||||||
|
|
||||||
/* "Editar grupo": el mismo formulario que el alta, con los datos del grupo. */
|
|
||||||
export function EditGroupView({ groupId }: { groupId: string }) {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { t } = useTranslation('groups')
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
|
||||||
queryKey: ['group', groupId],
|
|
||||||
queryFn: () => getGroup(groupId),
|
|
||||||
})
|
|
||||||
|
|
||||||
const update = useMutation({
|
|
||||||
// El país vive en el usuario, no en el grupo: el formulario lo trae pero no se manda.
|
|
||||||
mutationFn: ({ country: _country, ...values }: CreateFirstGroup) => updateGroup(groupId, values),
|
|
||||||
onSuccess: (group) => {
|
|
||||||
queryClient.setQueryData<GroupDto>(['group', groupId], (current) => (current ? { ...current, ...group } : group))
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ['groups'] })
|
|
||||||
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const group = groupQuery.data
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className="mx-auto w-full max-w-md">
|
|
||||||
<Link
|
|
||||||
to="/groups/$groupId"
|
|
||||||
params={{ groupId }}
|
|
||||||
className="mb-6 hidden items-center gap-1 text-sm font-medium text-foreground/70 transition-colors hover:text-primary lg:inline-flex"
|
|
||||||
>
|
|
||||||
<ChevronLeft className="size-4" />
|
|
||||||
{group?.name ?? t('title')}
|
|
||||||
</Link>
|
|
||||||
|
|
||||||
{group ? (
|
|
||||||
<GroupForm
|
|
||||||
heading={t('edit.heading')}
|
|
||||||
description={t('edit.description')}
|
|
||||||
submitLabel={t('edit.submit')}
|
|
||||||
isSubmitting={update.isPending}
|
|
||||||
errorMessage={update.isError ? errorMessage(update.error, t('edit.error')) : null}
|
|
||||||
initialValues={toFormValues(group)}
|
|
||||||
onSubmit={(values) => update.mutate(values)}
|
|
||||||
/>
|
|
||||||
) : groupQuery.isError ? (
|
|
||||||
<p role="alert" className="text-sm text-danger-fg">
|
|
||||||
{errorMessage(groupQuery.error, t('edit.loadError'))}
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div className="flex justify-center py-20">
|
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function toFormValues(group: GroupDto): Partial<CreateFirstGroup> {
|
|
||||||
return {
|
|
||||||
name: group.name,
|
|
||||||
days: group.days ?? [],
|
|
||||||
time: group.time ?? '09:00',
|
|
||||||
capacity: group.capacity ?? undefined,
|
|
||||||
price: group.price ?? undefined,
|
|
||||||
billingType: group.billingType ?? 'MONTHLY',
|
|
||||||
dueDay: group.dueDay ?? 1,
|
|
||||||
audience: group.audience,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,16 @@
|
|||||||
import { type DefaultValues, useForm } from 'react-hook-form'
|
import { type DefaultValues, useForm } from 'react-hook-form'
|
||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import type { BillingType, CountryCode, CreateFirstGroup, GroupAudience, WeekDay } from '@gruperly/shared'
|
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
||||||
import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||||
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { useId, useState } from 'react'
|
import { useId } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { currencySymbol, sortWeekDays } from '../../lib/format'
|
import { currencySymbol, sortWeekDays } from '../../lib/format'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Badge, Button, FieldError, Input, Label } from '../../components/ui'
|
import { Button, FieldError, Input, Label } from '../../components/ui'
|
||||||
import { hasPlanFeature, planFeatureRequiredMessage, useBillingStatus } from '../billing'
|
|
||||||
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
|
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
|
||||||
|
|
||||||
const AUDIENCES: readonly GroupAudience[] = ['ADULTS', 'KIDS']
|
|
||||||
|
|
||||||
type GroupFormProps = {
|
type GroupFormProps = {
|
||||||
heading: string
|
heading: string
|
||||||
description: string
|
description: string
|
||||||
@@ -26,8 +23,6 @@ type GroupFormProps = {
|
|||||||
country?: CountryCode
|
country?: CountryCode
|
||||||
onSubmit: (values: CreateFirstGroup) => void
|
onSubmit: (values: CreateFirstGroup) => void
|
||||||
onBack?: () => void
|
onBack?: () => void
|
||||||
/** Editar grupo: arranca con los datos del grupo. */
|
|
||||||
initialValues?: Partial<CreateFirstGroup>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function GroupForm({
|
export function GroupForm({
|
||||||
@@ -40,7 +35,6 @@ export function GroupForm({
|
|||||||
country,
|
country,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onBack,
|
onBack,
|
||||||
initialValues,
|
|
||||||
}: GroupFormProps) {
|
}: GroupFormProps) {
|
||||||
const { t } = useTranslation(['groups', 'common'])
|
const { t } = useTranslation(['groups', 'common'])
|
||||||
// The price starts empty on purpose: a pre-filled $0 got submitted as is and
|
// The price starts empty on purpose: a pre-filled $0 got submitted as is and
|
||||||
@@ -54,20 +48,12 @@ export function GroupForm({
|
|||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 1,
|
dueDay: 1,
|
||||||
country: country ?? DEFAULT_COUNTRY,
|
country: country ?? DEFAULT_COUNTRY,
|
||||||
audience: 'ADULTS',
|
|
||||||
...initialValues,
|
|
||||||
}
|
}
|
||||||
// Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador,
|
// Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador,
|
||||||
// igual que el resto de los montos de la app.
|
// igual que el resto de los montos de la app.
|
||||||
const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined)
|
const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined)
|
||||||
const daysLabelId = useId()
|
const daysLabelId = useId()
|
||||||
const billingLabelId = useId()
|
const billingLabelId = useId()
|
||||||
const audienceLabelId = useId()
|
|
||||||
const billingQuery = useBillingStatus()
|
|
||||||
// Un grupo que ya es de chicos sigue siéndolo aunque el plan ya no lo incluya.
|
|
||||||
const kidsIncluded = initialValues?.audience === 'KIDS' || hasPlanFeature(billingQuery.data, 'kidsGroups')
|
|
||||||
// Se avisa inline y no con el aviso global de Pro: el onboarding no lo monta.
|
|
||||||
const [kidsLocked, setKidsLocked] = useState(false)
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -84,7 +70,6 @@ export function GroupForm({
|
|||||||
const days = watch('days')
|
const days = watch('days')
|
||||||
const billingType = watch('billingType')
|
const billingType = watch('billingType')
|
||||||
const dueDay = watch('dueDay')
|
const dueDay = watch('dueDay')
|
||||||
const audience = watch('audience')
|
|
||||||
|
|
||||||
const toggleDay = (day: WeekDay) => {
|
const toggleDay = (day: WeekDay) => {
|
||||||
const next = days.includes(day) ? days.filter((d) => d !== day) : sortWeekDays([...days, day])
|
const next = days.includes(day) ? days.filter((d) => d !== day) : sortWeekDays([...days, day])
|
||||||
@@ -95,15 +80,6 @@ export function GroupForm({
|
|||||||
setValue('billingType', type, { shouldValidate: true })
|
setValue('billingType', type, { shouldValidate: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectAudience = (value: GroupAudience) => {
|
|
||||||
if (value === 'KIDS' && !kidsIncluded) {
|
|
||||||
setKidsLocked(true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setKidsLocked(false)
|
|
||||||
setValue('audience', value, { shouldValidate: true })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-5">
|
<form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-5">
|
||||||
<header className="space-y-1">
|
<header className="space-y-1">
|
||||||
@@ -123,42 +99,6 @@ export function GroupForm({
|
|||||||
<FieldError message={errors.name?.message} />
|
<FieldError message={errors.name?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
|
||||||
<Label id={audienceLabelId}>{t('form.audience')}</Label>
|
|
||||||
<div role="group" aria-labelledby={audienceLabelId} className="grid grid-cols-2 gap-2">
|
|
||||||
{AUDIENCES.map((value) => {
|
|
||||||
const isActive = audience === value
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={value}
|
|
||||||
type="button"
|
|
||||||
aria-pressed={isActive}
|
|
||||||
onClick={() => selectAudience(value)}
|
|
||||||
className={cn(
|
|
||||||
'rounded-xl border px-3 py-2.5 text-left transition-colors',
|
|
||||||
isActive
|
|
||||||
? 'border-accent bg-accent-soft'
|
|
||||||
: 'border-border bg-surface hover:bg-primary-soft',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<span className={cn('text-sm font-semibold', isActive ? 'text-accent' : 'text-primary')}>
|
|
||||||
{t(`form.audienceOption.${value}`)}
|
|
||||||
</span>
|
|
||||||
{value === 'KIDS' && !kidsIncluded ? <Badge variant="info">Pro</Badge> : null}
|
|
||||||
</span>
|
|
||||||
<span className="block text-xs text-foreground/50">{t(`form.audienceHint.${value}`)}</span>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
{kidsLocked ? (
|
|
||||||
<p role="status" className="mt-2 text-xs text-foreground/60">
|
|
||||||
{planFeatureRequiredMessage('kidsGroups')}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<fieldset className="space-y-4">
|
<fieldset className="space-y-4">
|
||||||
<legend className="mb-3 text-base font-semibold text-primary">
|
<legend className="mb-3 text-base font-semibold text-primary">
|
||||||
{t('form.whenLegend')}
|
{t('form.whenLegend')}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { useAddAttendee } from './AddAttendeeProvider'
|
|||||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||||
import { BulkImportPanel } from './BulkImportPanel'
|
import { BulkImportPanel } from './BulkImportPanel'
|
||||||
import { CapacityModal } from './CapacityModal'
|
import { CapacityModal } from './CapacityModal'
|
||||||
import { KidQuickAddForm } from './KidQuickAddForm'
|
|
||||||
import { QuickAddForm } from './QuickAddForm'
|
import { QuickAddForm } from './QuickAddForm'
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
@@ -15,10 +14,8 @@ const TABS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
export function AddAttendeePage() {
|
export function AddAttendeePage() {
|
||||||
const { groupId, groupName, groupAudience, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
||||||
useAddAttendee()
|
useAddAttendee()
|
||||||
// La carga masiva todavía no lleva los datos del adulto a cargo.
|
|
||||||
const isKidsGroup = groupAudience === 'KIDS'
|
|
||||||
const { t } = useTranslation('groupAdd')
|
const { t } = useTranslation('groupAdd')
|
||||||
|
|
||||||
if (groupPending) {
|
if (groupPending) {
|
||||||
@@ -62,7 +59,6 @@ export function AddAttendeePage() {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
|
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
|
||||||
{isKidsGroup ? null : (
|
|
||||||
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
|
||||||
{TABS.map((tab) => (
|
{TABS.map((tab) => (
|
||||||
<button
|
<button
|
||||||
@@ -80,9 +76,8 @@ export function AddAttendeePage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{isKidsGroup ? <KidQuickAddForm /> : activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CapacityModal />
|
<CapacityModal />
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import type {
|
|||||||
CreateAttendee,
|
CreateAttendee,
|
||||||
CreateAttendeeResult,
|
CreateAttendeeResult,
|
||||||
CreateGroupWaitlistEntry,
|
CreateGroupWaitlistEntry,
|
||||||
GroupAudience,
|
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
GroupWaitlistList,
|
GroupWaitlistList,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
@@ -39,8 +38,6 @@ export type AddAttendeeTab = 'quick' | 'bulk'
|
|||||||
type AddAttendeeContextValue = {
|
type AddAttendeeContextValue = {
|
||||||
groupId: string
|
groupId: string
|
||||||
groupName: string | undefined
|
groupName: string | undefined
|
||||||
/** KIDS: cada alta es un chico con su adulto a cargo. */
|
|
||||||
groupAudience: GroupAudience
|
|
||||||
groupPending: boolean
|
groupPending: boolean
|
||||||
attendeesTotal: number
|
attendeesTotal: number
|
||||||
capacity: number | null
|
capacity: number | null
|
||||||
@@ -265,7 +262,6 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
const value: AddAttendeeContextValue = {
|
const value: AddAttendeeContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
groupName: group?.name,
|
groupName: group?.name,
|
||||||
groupAudience: group?.audience ?? 'ADULTS',
|
|
||||||
groupPending: groupQuery.isPending,
|
groupPending: groupQuery.isPending,
|
||||||
attendeesTotal,
|
attendeesTotal,
|
||||||
capacity,
|
capacity,
|
||||||
@@ -300,14 +296,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
submitWaitlistEntry: () => {
|
submitWaitlistEntry: () => {
|
||||||
if (pendingCapacityPayload) {
|
if (pendingCapacityPayload) {
|
||||||
// Un chico entra a la lista de espera con el teléfono del adulto a cargo
|
addToWaitlistMutation.mutate({ ...pendingCapacityPayload })
|
||||||
// (la lista de espera de grupos de chicos se completa en otra entrega).
|
|
||||||
const { guardian, personId: _personId, ...entry } = pendingCapacityPayload
|
|
||||||
addToWaitlistMutation.mutate({
|
|
||||||
...entry,
|
|
||||||
phone: entry.phone || guardian?.phone || '',
|
|
||||||
email: entry.email || guardian?.email || undefined,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
requestBulkImport,
|
requestBulkImport,
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
import { UserCheck } from 'lucide-react'
|
|
||||||
import { Trans, useTranslation } from 'react-i18next'
|
|
||||||
import type { PersonSummary } from '@gruperly/shared'
|
|
||||||
import { cn } from '../../../lib/utils'
|
|
||||||
|
|
||||||
type ExistingGuardianNoticeProps = {
|
|
||||||
guardian: PersonSummary
|
|
||||||
groupId: string
|
|
||||||
/** El chico ya cargado que se eligió, o `null` si es un chico nuevo. */
|
|
||||||
selectedKidId: string | null
|
|
||||||
onSelectKid: (kidId: string | null) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
/* El teléfono del adulto ya es de alguien que el profe tiene: queda como adulto
|
|
||||||
a cargo con sus datos, y si ya tiene chicos se ofrece elegir uno (para no
|
|
||||||
duplicarlo) o seguir con un hermano nuevo. */
|
|
||||||
export function ExistingGuardianNotice({ guardian, groupId, selectedKidId, onSelectKid }: ExistingGuardianNoticeProps) {
|
|
||||||
const { t } = useTranslation('groupAdd')
|
|
||||||
const kids = guardian.children
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div role="status" className="mt-2 rounded-xl border border-border bg-accent-soft/40 px-3 py-3 text-sm text-primary">
|
|
||||||
<div className="flex items-start gap-2.5">
|
|
||||||
<UserCheck className="mt-0.5 size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
|
||||||
<p className="min-w-0">
|
|
||||||
<Trans
|
|
||||||
t={t}
|
|
||||||
i18nKey={kids.length > 0 ? 'kid.existing.foundWithKids' : 'kid.existing.found'}
|
|
||||||
values={{ name: guardian.fullName }}
|
|
||||||
components={{ strong: <strong /> }}
|
|
||||||
/>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{kids.length > 0 ? (
|
|
||||||
<div className="mt-2.5 flex flex-wrap gap-2" role="group" aria-label={t('kid.existing.pickLabel')}>
|
|
||||||
{kids.map((kid) => {
|
|
||||||
const inGroup = kid.groups.some((group) => group.groupId === groupId && group.status !== 'DROPPED')
|
|
||||||
const isSelected = selectedKidId === kid.id
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={kid.id}
|
|
||||||
type="button"
|
|
||||||
disabled={inGroup}
|
|
||||||
aria-pressed={isSelected}
|
|
||||||
onClick={() => onSelectKid(isSelected ? null : kid.id)}
|
|
||||||
className={cn(
|
|
||||||
'rounded-full border px-3 py-1.5 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50',
|
|
||||||
isSelected
|
|
||||||
? 'border-accent bg-accent text-on-accent'
|
|
||||||
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{inGroup ? t('kid.existing.kidInGroup', { name: kid.fullName }) : kid.fullName}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-pressed={selectedKidId === null}
|
|
||||||
onClick={() => onSelectKid(null)}
|
|
||||||
className={cn(
|
|
||||||
'rounded-full border px-3 py-1.5 text-xs font-medium transition-colors',
|
|
||||||
selectedKidId === null
|
|
||||||
? 'border-accent bg-accent text-on-accent'
|
|
||||||
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{t('kid.existing.newSibling')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { Check, Loader2 } from 'lucide-react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
import { Button, Input, Label, useToast } from '../../../components/ui'
|
|
||||||
import { useAddAttendee } from './AddAttendeeProvider'
|
|
||||||
import { ExistingGuardianNotice } from './ExistingGuardianNotice'
|
|
||||||
import { usePersonLookup } from './usePersonLookup'
|
|
||||||
|
|
||||||
/* Alta en un grupo de chicos: el chico y su adulto a cargo. El teléfono del
|
|
||||||
adulto lo identifica, así que dos hermanos comparten el mismo adulto; si ese
|
|
||||||
adulto ya tiene chicos cargados, se puede elegir uno en vez de duplicarlo. */
|
|
||||||
export function KidQuickAddForm() {
|
|
||||||
const { groupId, submitQuickAttendee, isSubmittingAttendee, cancelAddAttendee } = useAddAttendee()
|
|
||||||
const toast = useToast()
|
|
||||||
const { t } = useTranslation(['groupAdd', 'common'])
|
|
||||||
const [firstName, setFirstName] = useState('')
|
|
||||||
const [lastName, setLastName] = useState('')
|
|
||||||
const [notes, setNotes] = useState('')
|
|
||||||
const [guardianName, setGuardianName] = useState('')
|
|
||||||
const [guardianPhone, setGuardianPhone] = useState('')
|
|
||||||
const [guardianEmail, setGuardianEmail] = useState('')
|
|
||||||
const [selectedKidId, setSelectedKidId] = useState<string | null>(null)
|
|
||||||
|
|
||||||
const { person: existingGuardian } = usePersonLookup(groupId, guardianPhone)
|
|
||||||
const selectedKid = existingGuardian?.children.find((kid) => kid.id === selectedKidId) ?? null
|
|
||||||
const kidLocked = Boolean(selectedKid)
|
|
||||||
const guardianLocked = Boolean(existingGuardian)
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
if (selectedKid) {
|
|
||||||
submitQuickAttendee({ firstName: selectedKid.fullName, lastName: '', personId: selectedKid.id })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const adultName = existingGuardian?.fullName ?? guardianName.trim()
|
|
||||||
if (!firstName.trim() || !adultName || !guardianPhone.trim()) {
|
|
||||||
toast.error(t('kid.required'))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
submitQuickAttendee({
|
|
||||||
firstName: firstName.trim(),
|
|
||||||
lastName: lastName.trim(),
|
|
||||||
notes: notes.trim() || undefined,
|
|
||||||
guardian: {
|
|
||||||
fullName: adultName,
|
|
||||||
phone: guardianPhone.trim(),
|
|
||||||
email: (existingGuardian ? '' : guardianEmail.trim()) || undefined,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setFirstName('')
|
|
||||||
setLastName('')
|
|
||||||
setNotes('')
|
|
||||||
setGuardianName('')
|
|
||||||
setGuardianPhone('')
|
|
||||||
setGuardianEmail('')
|
|
||||||
setSelectedKidId(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-5">
|
|
||||||
<fieldset className="space-y-3">
|
|
||||||
<legend className="mb-2 text-sm font-semibold text-primary">{t('kid.kidSection')}</legend>
|
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="kid-first-name" className="mb-1 block text-xs">
|
|
||||||
{t('quick.firstName')} <span className="text-danger">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="kid-first-name"
|
|
||||||
autoFocus
|
|
||||||
placeholder={t('quick.firstNamePlaceholder')}
|
|
||||||
value={selectedKid ? selectedKid.fullName : firstName}
|
|
||||||
onChange={(e) => setFirstName(e.target.value)}
|
|
||||||
disabled={kidLocked}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="kid-last-name" className="mb-1 block text-xs">
|
|
||||||
{t('quick.lastName')}
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="kid-last-name"
|
|
||||||
placeholder={t('quick.lastNamePlaceholder')}
|
|
||||||
value={kidLocked ? '' : lastName}
|
|
||||||
onChange={(e) => setLastName(e.target.value)}
|
|
||||||
disabled={kidLocked}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="kid-notes" className="mb-1 block text-xs">
|
|
||||||
{t('quick.notes')}
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="kid-notes"
|
|
||||||
placeholder={t('kid.notesPlaceholder')}
|
|
||||||
value={notes}
|
|
||||||
onChange={(e) => setNotes(e.target.value)}
|
|
||||||
disabled={kidLocked}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<fieldset className="space-y-3">
|
|
||||||
<legend className="mb-2 text-sm font-semibold text-primary">{t('kid.guardianSection')}</legend>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="guardian-phone" className="mb-1 block text-xs">
|
|
||||||
{t('quick.phone')} <span className="text-danger">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="guardian-phone"
|
|
||||||
placeholder={t('quick.phonePlaceholder')}
|
|
||||||
value={guardianPhone}
|
|
||||||
onChange={(e) => {
|
|
||||||
setGuardianPhone(e.target.value)
|
|
||||||
setSelectedKidId(null)
|
|
||||||
}}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
{existingGuardian ? (
|
|
||||||
<ExistingGuardianNotice
|
|
||||||
guardian={existingGuardian}
|
|
||||||
groupId={groupId}
|
|
||||||
selectedKidId={selectedKidId}
|
|
||||||
onSelectKid={setSelectedKidId}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<p className="mt-1 text-[11px] text-foreground/50">{t('kid.guardianPhoneHint')}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="guardian-name" className="mb-1 block text-xs">
|
|
||||||
{t('kid.guardianName')} <span className="text-danger">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="guardian-name"
|
|
||||||
placeholder={t('kid.guardianNamePlaceholder')}
|
|
||||||
value={existingGuardian ? existingGuardian.fullName : guardianName}
|
|
||||||
onChange={(e) => setGuardianName(e.target.value)}
|
|
||||||
disabled={guardianLocked}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="guardian-email" className="mb-1 block text-xs">
|
|
||||||
{t('quick.email')}
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="guardian-email"
|
|
||||||
type="email"
|
|
||||||
placeholder={t('kid.guardianEmailPlaceholder')}
|
|
||||||
value={existingGuardian ? (existingGuardian.email ?? '') : guardianEmail}
|
|
||||||
onChange={(e) => setGuardianEmail(e.target.value)}
|
|
||||||
disabled={guardianLocked}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
onClick={() => {
|
|
||||||
resetForm()
|
|
||||||
cancelAddAttendee()
|
|
||||||
}}
|
|
||||||
className="w-full sm:w-auto"
|
|
||||||
>
|
|
||||||
{t('common:actions.cancel')}
|
|
||||||
</Button>
|
|
||||||
<Button variant="primary" type="submit" disabled={isSubmittingAttendee} className="w-full sm:w-auto">
|
|
||||||
{isSubmittingAttendee ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
|
||||||
<span>{t('quick.submit')}</span>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, BarChart3, Pencil, Share2, UserPlus, Wallet } from 'lucide-react'
|
import { ArrowLeft, BarChart3, Share2, UserPlus, Wallet } from 'lucide-react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Badge, Button, Tooltip } from '../../../components/ui'
|
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||||
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||||
@@ -19,7 +19,6 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
|
|||||||
preRegistrationsPending,
|
preRegistrationsPending,
|
||||||
waitlistTotal,
|
waitlistTotal,
|
||||||
waitlistPending,
|
waitlistPending,
|
||||||
isGroupOwner,
|
|
||||||
} = useGroupDetail()
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { t } = useTranslation(['groupDetail', 'groups'])
|
const { t } = useTranslation(['groupDetail', 'groups'])
|
||||||
@@ -79,21 +78,6 @@ export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
|
|||||||
</Badge>
|
</Badge>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
) : null}
|
) : null}
|
||||||
{group?.audience === 'KIDS' ? (
|
|
||||||
<Badge variant="info" className="text-[11px]">
|
|
||||||
{t('groups:form.audienceOption.KIDS')}
|
|
||||||
</Badge>
|
|
||||||
) : null}
|
|
||||||
{isGroupOwner ? (
|
|
||||||
<Link
|
|
||||||
to="/groups/$groupId/edit"
|
|
||||||
params={{ groupId }}
|
|
||||||
className="inline-flex min-h-8 items-center gap-1 rounded-lg px-1.5 text-xs font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
|
||||||
>
|
|
||||||
<Pencil className="size-3.5" aria-hidden="true" />
|
|
||||||
{t('groups:edit.link')}
|
|
||||||
</Link>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { WeekClassesList } from './WeekClassesList'
|
|||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function StudentHomeView() {
|
export function StudentHomeView() {
|
||||||
const { me, student, classes, classesPending, fees } = useStudentApp()
|
const { student, classes, classesPending, fees } = useStudentApp()
|
||||||
const { t } = useTranslation(['student', 'common'])
|
const { t } = useTranslation(['student', 'common'])
|
||||||
if (!student) return null
|
if (!student) return null
|
||||||
|
|
||||||
@@ -20,8 +20,7 @@ export function StudentHomeView() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* The account holder: the student, or the adult in charge of several kids. */}
|
<h1 className="text-2xl font-bold text-primary">{t('home.greeting', { name: firstName(student.fullName) })}</h1>
|
||||||
<h1 className="text-2xl font-bold text-primary">{t('home.greeting', { name: firstName(me?.account.name ?? student.fullName) })}</h1>
|
|
||||||
|
|
||||||
{fees ? <PaymentReviewBanner reports={fees.reports} /> : null}
|
{fees ? <PaymentReviewBanner reports={fees.reports} /> : null}
|
||||||
|
|
||||||
|
|||||||
@@ -20,14 +20,7 @@ export function StudentProfileView() {
|
|||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate font-semibold text-primary">{me.account.name}</p>
|
<p className="truncate font-semibold text-primary">{me.account.name}</p>
|
||||||
<p className="truncate text-sm text-secondary">
|
<p className="truncate text-sm text-secondary">
|
||||||
{me.students
|
{me.students.map((student) => `${student.groupName} · ${student.teacherName}`).join(' / ')}
|
||||||
.map((student) =>
|
|
||||||
// An adult in charge sees whose group each one is.
|
|
||||||
student.fullName === me.account.name
|
|
||||||
? `${student.groupName} · ${student.teacherName}`
|
|
||||||
: `${student.fullName} · ${student.groupName}`,
|
|
||||||
)
|
|
||||||
.join(' / ')}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -105,7 +105,6 @@
|
|||||||
"unlimitedFor": "{{label}} with no limit",
|
"unlimitedFor": "{{label}} with no limit",
|
||||||
"mpCharges": "Mercado Pago charges",
|
"mpCharges": "Mercado Pago charges",
|
||||||
"whatsappAutomations": "Automatic WhatsApp messages",
|
"whatsappAutomations": "Automatic WhatsApp messages",
|
||||||
"kidsGroups": "Kids groups with an adult in charge",
|
|
||||||
"impact_one": "{{count}} account already exceeds these limits and will become read only when you save.",
|
"impact_one": "{{count}} account already exceeds these limits and will become read only when you save.",
|
||||||
"impact_other": "{{count}} accounts already exceed these limits and will become read only when you save.",
|
"impact_other": "{{count}} accounts already exceed these limits and will become read only when you save.",
|
||||||
"saved": "Limits saved."
|
"saved": "Limits saved."
|
||||||
|
|||||||
@@ -58,7 +58,6 @@
|
|||||||
"title": "Invite to the app",
|
"title": "Invite to the app",
|
||||||
"descriptionReinvite": "Send {{name}} a new link. The previous access stops working.",
|
"descriptionReinvite": "Send {{name}} a new link. The previous access stops working.",
|
||||||
"description": "{{name}} will be able to report absences, report payments and see their upcoming classes. No passwords or new details.",
|
"description": "{{name}} will be able to report absences, report payments and see their upcoming classes. No passwords or new details.",
|
||||||
"descriptionGuardian": "{{guardian}} will be able to report absences, report payments and see the classes of {{name}} and their other kids. No passwords or new details.",
|
|
||||||
"preview": "Message preview",
|
"preview": "Message preview",
|
||||||
"linkPlaceholder": "🔗 personal link",
|
"linkPlaceholder": "🔗 personal link",
|
||||||
"security": "The link is personal, works only once and expires in 72 hours. The first phone that opens it stays connected.",
|
"security": "The link is personal, works only once and expires in 72 hours. The first phone that opens it stays connected.",
|
||||||
@@ -66,8 +65,7 @@
|
|||||||
"sendWhatsapp": "Send on WhatsApp",
|
"sendWhatsapp": "Send on WhatsApp",
|
||||||
"copied": "Link copied",
|
"copied": "Link copied",
|
||||||
"copy": "Copy link",
|
"copy": "Copy link",
|
||||||
"message": "Hi {{name}}! I'm inviting you to gruperly to report absences and payments for {{group}}. {{url}}",
|
"message": "Hi {{name}}! I'm inviting you to gruperly to report absences and payments for {{group}}. {{url}}"
|
||||||
"messageGuardian": "Hi {{guardian}}! I'm inviting you to gruperly to report absences and payments for {{name}} in {{group}}. {{url}}"
|
|
||||||
},
|
},
|
||||||
"payments": {
|
"payments": {
|
||||||
"title": "Payments",
|
"title": "Payments",
|
||||||
@@ -160,15 +158,5 @@
|
|||||||
"alreadyMember": "This person is already a member of that group.",
|
"alreadyMember": "This person is already a member of that group.",
|
||||||
"moveError": "We couldn't change the group.",
|
"moveError": "We couldn't change the group.",
|
||||||
"addError": "We couldn't add them to the group."
|
"addError": "We couldn't add them to the group."
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"title": "Adult in charge",
|
|
||||||
"add": "Add",
|
|
||||||
"name": "Name",
|
|
||||||
"namePlaceholder": "Full name",
|
|
||||||
"required": "Fill in the adult's name and a valid phone.",
|
|
||||||
"shared": "The change shows on all their kids.",
|
|
||||||
"siblings": "Siblings",
|
|
||||||
"missing": "This kid has no adult in charge yet."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
"unlimitedStudents": "Unlimited students",
|
"unlimitedStudents": "Unlimited students",
|
||||||
"students": "Up to {{count}} active students",
|
"students": "Up to {{count}} active students",
|
||||||
"mpCharges": "Payments with Mercado Pago",
|
"mpCharges": "Payments with Mercado Pago",
|
||||||
"whatsapp": "Automatic WhatsApp messages",
|
"whatsapp": "Automatic WhatsApp messages"
|
||||||
"kidsGroups": "Kids groups with an adult in charge"
|
|
||||||
},
|
},
|
||||||
"subscriptionStatus": {
|
"subscriptionStatus": {
|
||||||
"AUTHORIZED": "Active",
|
"AUTHORIZED": "Active",
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
"group_capacity_reached": "The group is full.",
|
"group_capacity_reached": "The group is full.",
|
||||||
"group_capacity_reached_one": "The group is full ({{count}} member max).",
|
"group_capacity_reached_one": "The group is full ({{count}} member max).",
|
||||||
"group_capacity_reached_other": "The group is full ({{count}} members max).",
|
"group_capacity_reached_other": "The group is full ({{count}} members max).",
|
||||||
"group_owner_required": "Only the group's creator can make this change.",
|
"group_owner_required": "Only the group's creator can change its automations.",
|
||||||
"group_without_price": "Set the group's price before creating payments.",
|
"group_without_price": "Set the group's price before creating payments.",
|
||||||
"mp_account_in_use": "That Mercado Pago account is already linked to another teacher.",
|
"mp_account_in_use": "That Mercado Pago account is already linked to another teacher.",
|
||||||
"mp_not_configured": "Linking with Mercado Pago isn't available right now.",
|
"mp_not_configured": "Linking with Mercado Pago isn't available right now.",
|
||||||
@@ -41,7 +41,6 @@
|
|||||||
"plan_feature_required": "This feature is available on the Pro plan.",
|
"plan_feature_required": "This feature is available on the Pro plan.",
|
||||||
"plan_feature_required_mpCharges": "Collecting with Mercado Pago is available on the Pro plan.",
|
"plan_feature_required_mpCharges": "Collecting with Mercado Pago is available on the Pro plan.",
|
||||||
"plan_feature_required_whatsappAutomations": "Automatic WhatsApp messages are available on the Pro plan.",
|
"plan_feature_required_whatsappAutomations": "Automatic WhatsApp messages are available on the Pro plan.",
|
||||||
"plan_feature_required_kidsGroups": "Kids groups with an adult in charge are available on the Pro plan.",
|
|
||||||
"plan_limit_reached": "You've reached the Free plan's limit. Upgrade to Pro to keep growing.",
|
"plan_limit_reached": "You've reached the Free plan's limit. Upgrade to Pro to keep growing.",
|
||||||
"plan_limit_reached_groups_one": "The Free plan allows up to {{count}} group. Upgrade to Pro to create more.",
|
"plan_limit_reached_groups_one": "The Free plan allows up to {{count}} group. Upgrade to Pro to create more.",
|
||||||
"plan_limit_reached_groups_other": "The Free plan allows up to {{count}} groups. Upgrade to Pro to create more.",
|
"plan_limit_reached_groups_other": "The Free plan allows up to {{count}} groups. Upgrade to Pro to create more.",
|
||||||
@@ -63,9 +62,7 @@
|
|||||||
"whatsapp_number_in_use": "That WhatsApp number is already linked to another teacher.",
|
"whatsapp_number_in_use": "That WhatsApp number is already linked to another teacher.",
|
||||||
"whatsapp_pairing_not_ready": "WhatsApp is still getting ready to link. Try again in a few seconds.",
|
"whatsapp_pairing_not_ready": "WhatsApp is still getting ready to link. Try again in a few seconds.",
|
||||||
"whatsapp_pairing_unsupported": "This WhatsApp provider doesn't support linking by phone number.",
|
"whatsapp_pairing_unsupported": "This WhatsApp provider doesn't support linking by phone number.",
|
||||||
"whatsapp_provider_error": "We couldn't reach WhatsApp. Try again in a few minutes.",
|
"whatsapp_provider_error": "We couldn't reach WhatsApp. Try again in a few minutes."
|
||||||
"guardian_required": "In a kids group you need to add the adult in charge.",
|
|
||||||
"group_has_kids_without_phone": "Some kids have no phone of their own: add one before switching the group to adults."
|
|
||||||
},
|
},
|
||||||
"auth": {
|
"auth": {
|
||||||
"INVALID_EMAIL_OR_PASSWORD": "The email or password is incorrect.",
|
"INVALID_EMAIL_OR_PASSWORD": "The email or password is incorrect.",
|
||||||
|
|||||||
@@ -93,22 +93,5 @@
|
|||||||
"importedLinked": "{{count}} were already in your other groups.",
|
"importedLinked": "{{count}} were already in your other groups.",
|
||||||
"importedDuplicates_one": "{{count}} duplicate skipped.",
|
"importedDuplicates_one": "{{count}} duplicate skipped.",
|
||||||
"importedDuplicates_other": "{{count}} duplicates skipped."
|
"importedDuplicates_other": "{{count}} duplicates skipped."
|
||||||
},
|
|
||||||
"kid": {
|
|
||||||
"kidSection": "The kid",
|
|
||||||
"guardianSection": "Adult in charge",
|
|
||||||
"guardianName": "Full name",
|
|
||||||
"guardianNamePlaceholder": "E.g. Anna Smith",
|
|
||||||
"guardianEmailPlaceholder": "adult@example.com",
|
|
||||||
"guardianPhoneHint": "They get the kid's notices and reminders. If you already have them, we recognize them by phone.",
|
|
||||||
"notesPlaceholder": "E.g. Allergies, who picks them up",
|
|
||||||
"required": "Fill in the kid's name and the adult's name and phone.",
|
|
||||||
"existing": {
|
|
||||||
"found": "<strong>{{name}}</strong> is already saved with that phone: they will be the adult in charge.",
|
|
||||||
"foundWithKids": "<strong>{{name}}</strong> is already in charge of these kids. Is it one of them or a new sibling?",
|
|
||||||
"pickLabel": "Pick the kid",
|
|
||||||
"kidInGroup": "{{name}} (already in the group)",
|
|
||||||
"newSibling": "Another kid"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,15 +55,6 @@
|
|||||||
"form": {
|
"form": {
|
||||||
"name": "Group name",
|
"name": "Group name",
|
||||||
"namePlaceholder": "E.g. Vinyasa Yoga · Level 1",
|
"namePlaceholder": "E.g. Vinyasa Yoga · Level 1",
|
||||||
"audience": "Who is it for?",
|
|
||||||
"audienceOption": {
|
|
||||||
"ADULTS": "Adults",
|
|
||||||
"KIDS": "Kids"
|
|
||||||
},
|
|
||||||
"audienceHint": {
|
|
||||||
"ADULTS": "Each student is their own contact",
|
|
||||||
"KIDS": "You talk to the adult in charge"
|
|
||||||
},
|
|
||||||
"days": "Class days",
|
"days": "Class days",
|
||||||
"time": "Time",
|
"time": "Time",
|
||||||
"capacity": "Capacity",
|
"capacity": "Capacity",
|
||||||
@@ -75,13 +66,5 @@
|
|||||||
"submitting": "Creating…",
|
"submitting": "Creating…",
|
||||||
"whenLegend": "Classes",
|
"whenLegend": "Classes",
|
||||||
"priceLegend": "Billing"
|
"priceLegend": "Billing"
|
||||||
},
|
|
||||||
"edit": {
|
|
||||||
"link": "Edit",
|
|
||||||
"heading": "Edit group",
|
|
||||||
"description": "Changes apply from now on; charges already created stay as they are.",
|
|
||||||
"submit": "Save changes",
|
|
||||||
"error": "We couldn't save the changes. Check the details and try again.",
|
|
||||||
"loadError": "We couldn't load the group."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,8 +63,5 @@
|
|||||||
},
|
},
|
||||||
"billing": {
|
"billing": {
|
||||||
"priceInvalid": "Enter a price greater than zero"
|
"priceInvalid": "Enter a price greater than zero"
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"nameRequired": "Enter the name of the adult in charge"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,7 +105,6 @@
|
|||||||
"unlimitedFor": "{{label}} sin límite",
|
"unlimitedFor": "{{label}} sin límite",
|
||||||
"mpCharges": "Cobros con Mercado Pago",
|
"mpCharges": "Cobros con Mercado Pago",
|
||||||
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
|
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
|
||||||
"kidsGroups": "Grupos de niños con adulto a cargo",
|
|
||||||
"impact_one": "{{count}} cuenta ya supera estos límites y quedará en solo lectura al guardar.",
|
"impact_one": "{{count}} cuenta ya supera estos límites y quedará en solo lectura al guardar.",
|
||||||
"impact_other": "{{count}} cuentas ya superan estos límites y quedarán en solo lectura al guardar.",
|
"impact_other": "{{count}} cuentas ya superan estos límites y quedarán en solo lectura al guardar.",
|
||||||
"saved": "Límites guardados."
|
"saved": "Límites guardados."
|
||||||
|
|||||||
@@ -58,7 +58,6 @@
|
|||||||
"title": "Invitar a la app",
|
"title": "Invitar a la app",
|
||||||
"descriptionReinvite": "Envíale un link nuevo a {{name}}. El acceso anterior deja de funcionar.",
|
"descriptionReinvite": "Envíale un link nuevo a {{name}}. El acceso anterior deja de funcionar.",
|
||||||
"description": "{{name}} podrá avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.",
|
"description": "{{name}} podrá avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.",
|
||||||
"descriptionGuardian": "{{guardian}} podrá avisar faltas, informar pagos y ver las clases de {{name}} y del resto de sus hijos. Sin contraseñas ni datos nuevos.",
|
|
||||||
"preview": "Vista previa del mensaje",
|
"preview": "Vista previa del mensaje",
|
||||||
"linkPlaceholder": "🔗 link personal",
|
"linkPlaceholder": "🔗 link personal",
|
||||||
"security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.",
|
"security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.",
|
||||||
@@ -66,8 +65,7 @@
|
|||||||
"sendWhatsapp": "Enviar por WhatsApp",
|
"sendWhatsapp": "Enviar por WhatsApp",
|
||||||
"copied": "Link copiado",
|
"copied": "Link copiado",
|
||||||
"copy": "Copiar link",
|
"copy": "Copiar link",
|
||||||
"message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}",
|
"message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}"
|
||||||
"messageGuardian": "¡Hola {{guardian}}! Te invito a gruperly para avisar faltas e informar pagos de {{name}} en {{group}}. {{url}}"
|
|
||||||
},
|
},
|
||||||
"payments": {
|
"payments": {
|
||||||
"title": "Cobros",
|
"title": "Cobros",
|
||||||
@@ -160,15 +158,5 @@
|
|||||||
"alreadyMember": "Esta persona ya es miembro de ese grupo.",
|
"alreadyMember": "Esta persona ya es miembro de ese grupo.",
|
||||||
"moveError": "No se pudo cambiar de grupo.",
|
"moveError": "No se pudo cambiar de grupo.",
|
||||||
"addError": "No se pudo agregar al grupo."
|
"addError": "No se pudo agregar al grupo."
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"title": "Adulto a cargo",
|
|
||||||
"add": "Agregar",
|
|
||||||
"name": "Nombre",
|
|
||||||
"namePlaceholder": "Nombre y apellido",
|
|
||||||
"required": "Completa el nombre y un teléfono válido del adulto.",
|
|
||||||
"shared": "El cambio se ve en la ficha de todos sus niños.",
|
|
||||||
"siblings": "Hermanos",
|
|
||||||
"missing": "Este niño todavía no tiene un adulto a cargo registrado."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
"unlimitedStudents": "Alumnos ilimitados",
|
"unlimitedStudents": "Alumnos ilimitados",
|
||||||
"students": "Hasta {{count}} alumnos activos",
|
"students": "Hasta {{count}} alumnos activos",
|
||||||
"mpCharges": "Cobros con Mercado Pago",
|
"mpCharges": "Cobros con Mercado Pago",
|
||||||
"whatsapp": "Mensajes automáticos por WhatsApp",
|
"whatsapp": "Mensajes automáticos por WhatsApp"
|
||||||
"kidsGroups": "Grupos de niños con adulto a cargo"
|
|
||||||
},
|
},
|
||||||
"subscriptionStatus": {
|
"subscriptionStatus": {
|
||||||
"AUTHORIZED": "Activa",
|
"AUTHORIZED": "Activa",
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
|
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
|
||||||
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
|
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
|
||||||
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
|
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
|
||||||
"group_owner_required": "Solo quien creó el grupo puede hacer este cambio.",
|
"group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.",
|
||||||
"group_without_price": "Define el precio del grupo antes de generar los cobros.",
|
"group_without_price": "Define el precio del grupo antes de generar los cobros.",
|
||||||
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
|
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
|
||||||
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
|
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
|
||||||
@@ -41,7 +41,6 @@
|
|||||||
"plan_feature_required": "Esta función está disponible en el plan Pro.",
|
"plan_feature_required": "Esta función está disponible en el plan Pro.",
|
||||||
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
|
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
|
||||||
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
|
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
|
||||||
"plan_feature_required_kidsGroups": "Los grupos de niños con adulto a cargo están disponibles en el plan Pro.",
|
|
||||||
"plan_limit_reached": "Llegaste al límite del plan Free. Cámbiate a Pro para seguir creciendo.",
|
"plan_limit_reached": "Llegaste al límite del plan Free. Cámbiate a Pro para seguir creciendo.",
|
||||||
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Cámbiate a Pro para crear más.",
|
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Cámbiate a Pro para crear más.",
|
||||||
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Cámbiate a Pro para crear más.",
|
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Cámbiate a Pro para crear más.",
|
||||||
@@ -63,9 +62,7 @@
|
|||||||
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
|
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
|
||||||
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Inténtalo de nuevo en unos segundos.",
|
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Inténtalo de nuevo en unos segundos.",
|
||||||
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
|
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
|
||||||
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Inténtalo de nuevo en unos minutos.",
|
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Inténtalo de nuevo en unos minutos."
|
||||||
"guardian_required": "En un grupo de niños tienes que registrar al adulto a cargo.",
|
|
||||||
"group_has_kids_without_phone": "Hay niños sin teléfono propio: regístrales uno antes de pasar el grupo a adultos."
|
|
||||||
},
|
},
|
||||||
"auth": {
|
"auth": {
|
||||||
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
|
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
|
||||||
|
|||||||
@@ -93,22 +93,5 @@
|
|||||||
"importedLinked": "{{count}} ya estaban en otros de tus grupos.",
|
"importedLinked": "{{count}} ya estaban en otros de tus grupos.",
|
||||||
"importedDuplicates_one": "{{count}} duplicado omitido.",
|
"importedDuplicates_one": "{{count}} duplicado omitido.",
|
||||||
"importedDuplicates_other": "{{count}} duplicados omitidos."
|
"importedDuplicates_other": "{{count}} duplicados omitidos."
|
||||||
},
|
|
||||||
"kid": {
|
|
||||||
"kidSection": "El niño",
|
|
||||||
"guardianSection": "Adulto a cargo",
|
|
||||||
"guardianName": "Nombre y apellido",
|
|
||||||
"guardianNamePlaceholder": "Ej.: Ana Pérez",
|
|
||||||
"guardianEmailPlaceholder": "adulto@ejemplo.com",
|
|
||||||
"guardianPhoneHint": "Recibe los avisos y recordatorios del niño. Si ya lo tienes registrado, lo reconocemos por el teléfono.",
|
|
||||||
"notesPlaceholder": "Ej.: Alergias, quién lo recoge",
|
|
||||||
"required": "Completa el nombre del niño y el nombre y teléfono del adulto.",
|
|
||||||
"existing": {
|
|
||||||
"found": "<strong>{{name}}</strong> ya está registrado con ese teléfono: queda como adulto a cargo.",
|
|
||||||
"foundWithKids": "<strong>{{name}}</strong> ya es adulto a cargo de estos niños. ¿Es alguno de ellos o un hermano nuevo?",
|
|
||||||
"pickLabel": "Elige al niño",
|
|
||||||
"kidInGroup": "{{name}} (ya está en el grupo)",
|
|
||||||
"newSibling": "Otro niño"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,15 +55,6 @@
|
|||||||
"form": {
|
"form": {
|
||||||
"name": "Nombre del grupo",
|
"name": "Nombre del grupo",
|
||||||
"namePlaceholder": "Ej.: Yoga Vinyasa · Nivel 1",
|
"namePlaceholder": "Ej.: Yoga Vinyasa · Nivel 1",
|
||||||
"audience": "¿Para quién es?",
|
|
||||||
"audienceOption": {
|
|
||||||
"ADULTS": "Adultos",
|
|
||||||
"KIDS": "Niños"
|
|
||||||
},
|
|
||||||
"audienceHint": {
|
|
||||||
"ADULTS": "Cada alumno es su propio contacto",
|
|
||||||
"KIDS": "Hablas con el adulto a cargo"
|
|
||||||
},
|
|
||||||
"days": "Días de clase",
|
"days": "Días de clase",
|
||||||
"time": "Horario",
|
"time": "Horario",
|
||||||
"capacity": "Cupo máximo",
|
"capacity": "Cupo máximo",
|
||||||
@@ -75,13 +66,5 @@
|
|||||||
"submitting": "Creando…",
|
"submitting": "Creando…",
|
||||||
"whenLegend": "Las clases",
|
"whenLegend": "Las clases",
|
||||||
"priceLegend": "El cobro"
|
"priceLegend": "El cobro"
|
||||||
},
|
|
||||||
"edit": {
|
|
||||||
"link": "Editar",
|
|
||||||
"heading": "Editar grupo",
|
|
||||||
"description": "Los cambios se aplican desde ahora; las cuotas ya generadas no cambian.",
|
|
||||||
"submit": "Guardar cambios",
|
|
||||||
"error": "No pudimos guardar los cambios. Revisa los datos e inténtalo de nuevo.",
|
|
||||||
"loadError": "No pudimos cargar el grupo."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,8 +63,5 @@
|
|||||||
},
|
},
|
||||||
"billing": {
|
"billing": {
|
||||||
"priceInvalid": "Ingresa un precio mayor a cero"
|
"priceInvalid": "Ingresa un precio mayor a cero"
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"nameRequired": "Ingresa el nombre del adulto a cargo"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,7 +105,6 @@
|
|||||||
"unlimitedFor": "{{label}} sin límite",
|
"unlimitedFor": "{{label}} sin límite",
|
||||||
"mpCharges": "Cobros con Mercado Pago",
|
"mpCharges": "Cobros con Mercado Pago",
|
||||||
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
|
"whatsappAutomations": "Mensajes automáticos por WhatsApp",
|
||||||
"kidsGroups": "Grupos de chicos con adulto a cargo",
|
|
||||||
"impact_one": "{{count}} cuenta ya supera estos límites y va a quedar en solo lectura al guardar.",
|
"impact_one": "{{count}} cuenta ya supera estos límites y va a quedar en solo lectura al guardar.",
|
||||||
"impact_other": "{{count}} cuentas ya superan estos límites y van a quedar en solo lectura al guardar.",
|
"impact_other": "{{count}} cuentas ya superan estos límites y van a quedar en solo lectura al guardar.",
|
||||||
"saved": "Límites guardados."
|
"saved": "Límites guardados."
|
||||||
|
|||||||
@@ -58,7 +58,6 @@
|
|||||||
"title": "Invitar a la app",
|
"title": "Invitar a la app",
|
||||||
"descriptionReinvite": "Mandale un link nuevo a {{name}}. El acceso anterior deja de funcionar.",
|
"descriptionReinvite": "Mandale un link nuevo a {{name}}. El acceso anterior deja de funcionar.",
|
||||||
"description": "{{name}} va a poder avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.",
|
"description": "{{name}} va a poder avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.",
|
||||||
"descriptionGuardian": "{{guardian}} va a poder avisar faltas, informar pagos y ver las clases de {{name}} y del resto de sus chicos. Sin contraseñas ni datos nuevos.",
|
|
||||||
"preview": "Vista previa del mensaje",
|
"preview": "Vista previa del mensaje",
|
||||||
"linkPlaceholder": "🔗 link personal",
|
"linkPlaceholder": "🔗 link personal",
|
||||||
"security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.",
|
"security": "El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.",
|
||||||
@@ -66,8 +65,7 @@
|
|||||||
"sendWhatsapp": "Enviar por WhatsApp",
|
"sendWhatsapp": "Enviar por WhatsApp",
|
||||||
"copied": "Link copiado",
|
"copied": "Link copiado",
|
||||||
"copy": "Copiar link",
|
"copy": "Copiar link",
|
||||||
"message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}",
|
"message": "¡Hola {{name}}! Te invito a gruperly para avisar faltas e informar pagos de {{group}}. {{url}}"
|
||||||
"messageGuardian": "¡Hola {{guardian}}! Te invito a gruperly para avisar faltas e informar pagos de {{name}} en {{group}}. {{url}}"
|
|
||||||
},
|
},
|
||||||
"payments": {
|
"payments": {
|
||||||
"title": "Cobros",
|
"title": "Cobros",
|
||||||
@@ -160,15 +158,5 @@
|
|||||||
"alreadyMember": "Esta persona ya es miembro de ese grupo.",
|
"alreadyMember": "Esta persona ya es miembro de ese grupo.",
|
||||||
"moveError": "No se pudo cambiar de grupo.",
|
"moveError": "No se pudo cambiar de grupo.",
|
||||||
"addError": "No se pudo agregar al grupo."
|
"addError": "No se pudo agregar al grupo."
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"title": "Adulto a cargo",
|
|
||||||
"add": "Agregar",
|
|
||||||
"name": "Nombre",
|
|
||||||
"namePlaceholder": "Nombre y apellido",
|
|
||||||
"required": "Completá el nombre y un teléfono válido del adulto.",
|
|
||||||
"shared": "El cambio se ve en la ficha de todos sus chicos.",
|
|
||||||
"siblings": "Hermanos",
|
|
||||||
"missing": "Este chico todavía no tiene un adulto a cargo cargado."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
"unlimitedStudents": "Alumnos ilimitados",
|
"unlimitedStudents": "Alumnos ilimitados",
|
||||||
"students": "Hasta {{count}} alumnos activos",
|
"students": "Hasta {{count}} alumnos activos",
|
||||||
"mpCharges": "Cobros con Mercado Pago",
|
"mpCharges": "Cobros con Mercado Pago",
|
||||||
"whatsapp": "Mensajes automáticos por WhatsApp",
|
"whatsapp": "Mensajes automáticos por WhatsApp"
|
||||||
"kidsGroups": "Grupos de chicos con adulto a cargo"
|
|
||||||
},
|
},
|
||||||
"subscriptionStatus": {
|
"subscriptionStatus": {
|
||||||
"AUTHORIZED": "Activa",
|
"AUTHORIZED": "Activa",
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
|
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
|
||||||
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
|
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
|
||||||
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
|
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
|
||||||
"group_owner_required": "Solo quien creó el grupo puede hacer este cambio.",
|
"group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.",
|
||||||
"group_without_price": "Definí el precio del grupo antes de generar los cobros.",
|
"group_without_price": "Definí el precio del grupo antes de generar los cobros.",
|
||||||
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
|
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
|
||||||
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
|
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
|
||||||
@@ -41,7 +41,6 @@
|
|||||||
"plan_feature_required": "Esta función está disponible en el plan Pro.",
|
"plan_feature_required": "Esta función está disponible en el plan Pro.",
|
||||||
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
|
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
|
||||||
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
|
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
|
||||||
"plan_feature_required_kidsGroups": "Los grupos de chicos con adulto a cargo están disponibles en el plan Pro.",
|
|
||||||
"plan_limit_reached": "Llegaste al límite del plan Free. Pasate a Pro para seguir creciendo.",
|
"plan_limit_reached": "Llegaste al límite del plan Free. Pasate a Pro para seguir creciendo.",
|
||||||
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Pasate a Pro para crear más.",
|
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Pasate a Pro para crear más.",
|
||||||
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Pasate a Pro para crear más.",
|
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Pasate a Pro para crear más.",
|
||||||
@@ -63,9 +62,7 @@
|
|||||||
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
|
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
|
||||||
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.",
|
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.",
|
||||||
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
|
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
|
||||||
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos.",
|
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos."
|
||||||
"guardian_required": "En un grupo de chicos tenés que cargar al adulto a cargo.",
|
|
||||||
"group_has_kids_without_phone": "Hay chicos sin teléfono propio: cargales uno antes de pasar el grupo a adultos."
|
|
||||||
},
|
},
|
||||||
"auth": {
|
"auth": {
|
||||||
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
|
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
|
||||||
|
|||||||
@@ -93,22 +93,5 @@
|
|||||||
"importedLinked": "{{count}} ya estaban en otros de tus grupos.",
|
"importedLinked": "{{count}} ya estaban en otros de tus grupos.",
|
||||||
"importedDuplicates_one": "{{count}} duplicado omitido.",
|
"importedDuplicates_one": "{{count}} duplicado omitido.",
|
||||||
"importedDuplicates_other": "{{count}} duplicados omitidos."
|
"importedDuplicates_other": "{{count}} duplicados omitidos."
|
||||||
},
|
|
||||||
"kid": {
|
|
||||||
"kidSection": "El chico",
|
|
||||||
"guardianSection": "Adulto a cargo",
|
|
||||||
"guardianName": "Nombre y apellido",
|
|
||||||
"guardianNamePlaceholder": "Ej.: Ana Pérez",
|
|
||||||
"guardianEmailPlaceholder": "adulto@ejemplo.com",
|
|
||||||
"guardianPhoneHint": "Le llegan los avisos y recordatorios del chico. Si ya lo tenés cargado, lo reconocemos por el teléfono.",
|
|
||||||
"notesPlaceholder": "Ej.: Alergias, quién lo retira",
|
|
||||||
"required": "Completá el nombre del chico y el nombre y teléfono del adulto.",
|
|
||||||
"existing": {
|
|
||||||
"found": "<strong>{{name}}</strong> ya está registrado con ese teléfono: queda como adulto a cargo.",
|
|
||||||
"foundWithKids": "<strong>{{name}}</strong> ya es adulto a cargo de estos chicos. ¿Es alguno de ellos o un hermano nuevo?",
|
|
||||||
"pickLabel": "Elegí el chico",
|
|
||||||
"kidInGroup": "{{name}} (ya está en el grupo)",
|
|
||||||
"newSibling": "Otro chico"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,15 +55,6 @@
|
|||||||
"form": {
|
"form": {
|
||||||
"name": "Nombre del grupo",
|
"name": "Nombre del grupo",
|
||||||
"namePlaceholder": "Ej: Yoga Vinyasa · Nivel 1",
|
"namePlaceholder": "Ej: Yoga Vinyasa · Nivel 1",
|
||||||
"audience": "¿Para quién es?",
|
|
||||||
"audienceOption": {
|
|
||||||
"ADULTS": "Adultos",
|
|
||||||
"KIDS": "Chicos"
|
|
||||||
},
|
|
||||||
"audienceHint": {
|
|
||||||
"ADULTS": "Cada alumno es su propio contacto",
|
|
||||||
"KIDS": "Hablás con el adulto a cargo"
|
|
||||||
},
|
|
||||||
"days": "Días de clase",
|
"days": "Días de clase",
|
||||||
"time": "Horario",
|
"time": "Horario",
|
||||||
"capacity": "Cupo máximo",
|
"capacity": "Cupo máximo",
|
||||||
@@ -75,13 +66,5 @@
|
|||||||
"submitting": "Creando…",
|
"submitting": "Creando…",
|
||||||
"whenLegend": "Las clases",
|
"whenLegend": "Las clases",
|
||||||
"priceLegend": "El cobro"
|
"priceLegend": "El cobro"
|
||||||
},
|
|
||||||
"edit": {
|
|
||||||
"link": "Editar",
|
|
||||||
"heading": "Editar grupo",
|
|
||||||
"description": "Los cambios se aplican desde ahora; las cuotas ya generadas no cambian.",
|
|
||||||
"submit": "Guardar cambios",
|
|
||||||
"error": "No pudimos guardar los cambios. Revisá los datos e intentá de nuevo.",
|
|
||||||
"loadError": "No pudimos cargar el grupo."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,8 +63,5 @@
|
|||||||
},
|
},
|
||||||
"billing": {
|
"billing": {
|
||||||
"priceInvalid": "Ingresá un precio mayor a cero"
|
"priceInvalid": "Ingresá un precio mayor a cero"
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"nameRequired": "Ingresá el nombre del adulto a cargo"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,7 +105,6 @@
|
|||||||
"unlimitedFor": "{{label}} sem limite",
|
"unlimitedFor": "{{label}} sem limite",
|
||||||
"mpCharges": "Cobranças com Mercado Pago",
|
"mpCharges": "Cobranças com Mercado Pago",
|
||||||
"whatsappAutomations": "Mensagens automáticas por WhatsApp",
|
"whatsappAutomations": "Mensagens automáticas por WhatsApp",
|
||||||
"kidsGroups": "Turmas de crianças com responsável",
|
|
||||||
"impact_one": "{{count}} conta já passa desses limites e vai ficar em somente leitura ao salvar.",
|
"impact_one": "{{count}} conta já passa desses limites e vai ficar em somente leitura ao salvar.",
|
||||||
"impact_other": "{{count}} contas já passam desses limites e vão ficar em somente leitura ao salvar.",
|
"impact_other": "{{count}} contas já passam desses limites e vão ficar em somente leitura ao salvar.",
|
||||||
"saved": "Limites salvos."
|
"saved": "Limites salvos."
|
||||||
|
|||||||
@@ -58,7 +58,6 @@
|
|||||||
"title": "Convidar para o app",
|
"title": "Convidar para o app",
|
||||||
"descriptionReinvite": "Envie um novo link para {{name}}. O acesso anterior deixa de funcionar.",
|
"descriptionReinvite": "Envie um novo link para {{name}}. O acesso anterior deixa de funcionar.",
|
||||||
"description": "{{name}} vai poder avisar faltas, informar pagamentos e ver as próximas aulas. Sem senhas nem dados novos.",
|
"description": "{{name}} vai poder avisar faltas, informar pagamentos e ver as próximas aulas. Sem senhas nem dados novos.",
|
||||||
"descriptionGuardian": "{{guardian}} vai poder avisar faltas, informar pagamentos e ver as aulas de {{name}} e dos outros filhos. Sem senhas nem dados novos.",
|
|
||||||
"preview": "Prévia da mensagem",
|
"preview": "Prévia da mensagem",
|
||||||
"linkPlaceholder": "🔗 link pessoal",
|
"linkPlaceholder": "🔗 link pessoal",
|
||||||
"security": "O link é pessoal, vale uma única vez e vence em 72 horas. Fica conectado o primeiro celular que abrir.",
|
"security": "O link é pessoal, vale uma única vez e vence em 72 horas. Fica conectado o primeiro celular que abrir.",
|
||||||
@@ -66,8 +65,7 @@
|
|||||||
"sendWhatsapp": "Enviar pelo WhatsApp",
|
"sendWhatsapp": "Enviar pelo WhatsApp",
|
||||||
"copied": "Link copiado",
|
"copied": "Link copiado",
|
||||||
"copy": "Copiar link",
|
"copy": "Copiar link",
|
||||||
"message": "Olá, {{name}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{group}}. {{url}}",
|
"message": "Olá, {{name}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{group}}. {{url}}"
|
||||||
"messageGuardian": "Olá, {{guardian}}! Te convido para o gruperly para avisar faltas e informar pagamentos de {{name}} em {{group}}. {{url}}"
|
|
||||||
},
|
},
|
||||||
"payments": {
|
"payments": {
|
||||||
"title": "Cobranças",
|
"title": "Cobranças",
|
||||||
@@ -160,15 +158,5 @@
|
|||||||
"alreadyMember": "Esta pessoa já é membro desse grupo.",
|
"alreadyMember": "Esta pessoa já é membro desse grupo.",
|
||||||
"moveError": "Não foi possível mudar de grupo.",
|
"moveError": "Não foi possível mudar de grupo.",
|
||||||
"addError": "Não foi possível adicionar ao grupo."
|
"addError": "Não foi possível adicionar ao grupo."
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"title": "Responsável",
|
|
||||||
"add": "Adicionar",
|
|
||||||
"name": "Nome",
|
|
||||||
"namePlaceholder": "Nome e sobrenome",
|
|
||||||
"required": "Preencha o nome e um telefone válido do responsável.",
|
|
||||||
"shared": "A alteração aparece na ficha de todas as crianças dele.",
|
|
||||||
"siblings": "Irmãos",
|
|
||||||
"missing": "Esta criança ainda não tem um responsável cadastrado."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,7 @@
|
|||||||
"unlimitedStudents": "Alunos ilimitados",
|
"unlimitedStudents": "Alunos ilimitados",
|
||||||
"students": "Até {{count}} alunos ativos",
|
"students": "Até {{count}} alunos ativos",
|
||||||
"mpCharges": "Cobranças com Mercado Pago",
|
"mpCharges": "Cobranças com Mercado Pago",
|
||||||
"whatsapp": "Mensagens automáticas pelo WhatsApp",
|
"whatsapp": "Mensagens automáticas pelo WhatsApp"
|
||||||
"kidsGroups": "Turmas de crianças com responsável"
|
|
||||||
},
|
},
|
||||||
"subscriptionStatus": {
|
"subscriptionStatus": {
|
||||||
"AUTHORIZED": "Ativa",
|
"AUTHORIZED": "Ativa",
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
"group_capacity_reached": "O grupo atingiu o limite máximo de membros.",
|
"group_capacity_reached": "O grupo atingiu o limite máximo de membros.",
|
||||||
"group_capacity_reached_one": "O grupo atingiu o limite máximo de {{count}} membro.",
|
"group_capacity_reached_one": "O grupo atingiu o limite máximo de {{count}} membro.",
|
||||||
"group_capacity_reached_other": "O grupo atingiu o limite máximo de {{count}} membros.",
|
"group_capacity_reached_other": "O grupo atingiu o limite máximo de {{count}} membros.",
|
||||||
"group_owner_required": "Só quem criou a turma pode fazer essa alteração.",
|
"group_owner_required": "Só quem criou o grupo pode mudar as automações.",
|
||||||
"group_without_price": "Defina o preço do grupo antes de gerar as cobranças.",
|
"group_without_price": "Defina o preço do grupo antes de gerar as cobranças.",
|
||||||
"mp_account_in_use": "Essa conta do Mercado Pago já está vinculada a outro professor.",
|
"mp_account_in_use": "Essa conta do Mercado Pago já está vinculada a outro professor.",
|
||||||
"mp_not_configured": "A vinculação com o Mercado Pago não está disponível no momento.",
|
"mp_not_configured": "A vinculação com o Mercado Pago não está disponível no momento.",
|
||||||
@@ -41,7 +41,6 @@
|
|||||||
"plan_feature_required": "Este recurso está disponível no plano Pro.",
|
"plan_feature_required": "Este recurso está disponível no plano Pro.",
|
||||||
"plan_feature_required_mpCharges": "Cobrar pelo Mercado Pago está disponível no plano Pro.",
|
"plan_feature_required_mpCharges": "Cobrar pelo Mercado Pago está disponível no plano Pro.",
|
||||||
"plan_feature_required_whatsappAutomations": "As mensagens automáticas de WhatsApp estão disponíveis no plano Pro.",
|
"plan_feature_required_whatsappAutomations": "As mensagens automáticas de WhatsApp estão disponíveis no plano Pro.",
|
||||||
"plan_feature_required_kidsGroups": "Turmas de crianças com responsável estão disponíveis no plano Pro.",
|
|
||||||
"plan_limit_reached": "Você atingiu o limite do plano Free. Mude para o Pro para continuar crescendo.",
|
"plan_limit_reached": "Você atingiu o limite do plano Free. Mude para o Pro para continuar crescendo.",
|
||||||
"plan_limit_reached_groups_one": "O plano Free permite até {{count}} grupo. Mude para o Pro para criar mais.",
|
"plan_limit_reached_groups_one": "O plano Free permite até {{count}} grupo. Mude para o Pro para criar mais.",
|
||||||
"plan_limit_reached_groups_other": "O plano Free permite até {{count}} grupos. Mude para o Pro para criar mais.",
|
"plan_limit_reached_groups_other": "O plano Free permite até {{count}} grupos. Mude para o Pro para criar mais.",
|
||||||
@@ -63,9 +62,7 @@
|
|||||||
"whatsapp_number_in_use": "Esse número de WhatsApp já está vinculado a outro professor.",
|
"whatsapp_number_in_use": "Esse número de WhatsApp já está vinculado a outro professor.",
|
||||||
"whatsapp_pairing_not_ready": "O WhatsApp ainda está preparando a vinculação. Tente novamente em alguns segundos.",
|
"whatsapp_pairing_not_ready": "O WhatsApp ainda está preparando a vinculação. Tente novamente em alguns segundos.",
|
||||||
"whatsapp_pairing_unsupported": "Este provedor de WhatsApp não permite vincular pelo número de telefone.",
|
"whatsapp_pairing_unsupported": "Este provedor de WhatsApp não permite vincular pelo número de telefone.",
|
||||||
"whatsapp_provider_error": "Não conseguimos falar com o WhatsApp. Tente novamente em alguns minutos.",
|
"whatsapp_provider_error": "Não conseguimos falar com o WhatsApp. Tente novamente em alguns minutos."
|
||||||
"guardian_required": "Em uma turma de crianças você precisa cadastrar o responsável.",
|
|
||||||
"group_has_kids_without_phone": "Há crianças sem telefone próprio: cadastre um antes de mudar a turma para adultos."
|
|
||||||
},
|
},
|
||||||
"auth": {
|
"auth": {
|
||||||
"INVALID_EMAIL_OR_PASSWORD": "E-mail ou senha incorretos.",
|
"INVALID_EMAIL_OR_PASSWORD": "E-mail ou senha incorretos.",
|
||||||
|
|||||||
@@ -93,22 +93,5 @@
|
|||||||
"importedLinked": "{{count}} já estavam em outros grupos seus.",
|
"importedLinked": "{{count}} já estavam em outros grupos seus.",
|
||||||
"importedDuplicates_one": "{{count}} duplicado ignorado.",
|
"importedDuplicates_one": "{{count}} duplicado ignorado.",
|
||||||
"importedDuplicates_other": "{{count}} duplicados ignorados."
|
"importedDuplicates_other": "{{count}} duplicados ignorados."
|
||||||
},
|
|
||||||
"kid": {
|
|
||||||
"kidSection": "A criança",
|
|
||||||
"guardianSection": "Responsável",
|
|
||||||
"guardianName": "Nome e sobrenome",
|
|
||||||
"guardianNamePlaceholder": "Ex.: Ana Souza",
|
|
||||||
"guardianEmailPlaceholder": "responsavel@exemplo.com",
|
|
||||||
"guardianPhoneHint": "Recebe os avisos e lembretes da criança. Se já estiver cadastrado, reconhecemos pelo telefone.",
|
|
||||||
"notesPlaceholder": "Ex.: Alergias, quem busca",
|
|
||||||
"required": "Preencha o nome da criança e o nome e telefone do responsável.",
|
|
||||||
"existing": {
|
|
||||||
"found": "<strong>{{name}}</strong> já está cadastrado com esse telefone: fica como responsável.",
|
|
||||||
"foundWithKids": "<strong>{{name}}</strong> já é responsável por estas crianças. É alguma delas ou um irmão novo?",
|
|
||||||
"pickLabel": "Escolha a criança",
|
|
||||||
"kidInGroup": "{{name}} (já está na turma)",
|
|
||||||
"newSibling": "Outra criança"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,15 +55,6 @@
|
|||||||
"form": {
|
"form": {
|
||||||
"name": "Nome do grupo",
|
"name": "Nome do grupo",
|
||||||
"namePlaceholder": "Ex.: Yoga Vinyasa · Nível 1",
|
"namePlaceholder": "Ex.: Yoga Vinyasa · Nível 1",
|
||||||
"audience": "Para quem é?",
|
|
||||||
"audienceOption": {
|
|
||||||
"ADULTS": "Adultos",
|
|
||||||
"KIDS": "Crianças"
|
|
||||||
},
|
|
||||||
"audienceHint": {
|
|
||||||
"ADULTS": "Cada aluno é o próprio contato",
|
|
||||||
"KIDS": "Você fala com o responsável"
|
|
||||||
},
|
|
||||||
"days": "Dias de aula",
|
"days": "Dias de aula",
|
||||||
"time": "Horário",
|
"time": "Horário",
|
||||||
"capacity": "Vagas",
|
"capacity": "Vagas",
|
||||||
@@ -75,13 +66,5 @@
|
|||||||
"submitting": "Criando…",
|
"submitting": "Criando…",
|
||||||
"whenLegend": "As aulas",
|
"whenLegend": "As aulas",
|
||||||
"priceLegend": "A cobrança"
|
"priceLegend": "A cobrança"
|
||||||
},
|
|
||||||
"edit": {
|
|
||||||
"link": "Editar",
|
|
||||||
"heading": "Editar turma",
|
|
||||||
"description": "As alterações valem a partir de agora; as mensalidades já geradas não mudam.",
|
|
||||||
"submit": "Salvar alterações",
|
|
||||||
"error": "Não conseguimos salvar as alterações. Revise os dados e tente de novo.",
|
|
||||||
"loadError": "Não conseguimos carregar a turma."
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,8 +63,5 @@
|
|||||||
},
|
},
|
||||||
"billing": {
|
"billing": {
|
||||||
"priceInvalid": "Informe um preço maior que zero"
|
"priceInvalid": "Informe um preço maior que zero"
|
||||||
},
|
|
||||||
"guardian": {
|
|
||||||
"nameRequired": "Informe o nome do responsável"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,8 +35,6 @@ import type {
|
|||||||
CreatePaymentsBatchResult,
|
CreatePaymentsBatchResult,
|
||||||
GroupAnalytics,
|
GroupAnalytics,
|
||||||
GroupDto,
|
GroupDto,
|
||||||
GuardianInput,
|
|
||||||
UpdateGroup,
|
|
||||||
GroupInviteInfoDto,
|
GroupInviteInfoDto,
|
||||||
GroupList,
|
GroupList,
|
||||||
GroupPreRegistrationList,
|
GroupPreRegistrationList,
|
||||||
@@ -222,12 +220,6 @@ export const getWhatsappStatus = () => apiFetch<WhatsappStatusDto>('/api/v1/what
|
|||||||
export const disconnectWhatsapp = () =>
|
export const disconnectWhatsapp = () =>
|
||||||
apiFetch<WhatsappDisconnectResultDto>('/api/v1/whatsapp/connect', { method: 'DELETE' })
|
apiFetch<WhatsappDisconnectResultDto>('/api/v1/whatsapp/connect', { method: 'DELETE' })
|
||||||
|
|
||||||
export const updateGroup = (groupId: string, payload: UpdateGroup) =>
|
|
||||||
apiFetch<GroupDto>(`/api/v1/groups/${groupId}`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
})
|
|
||||||
|
|
||||||
export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) =>
|
export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) =>
|
||||||
apiFetch<GroupAutomationsDto>(`/api/v1/groups/${groupId}/automations`, {
|
apiFetch<GroupAutomationsDto>(`/api/v1/groups/${groupId}/automations`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
@@ -337,13 +329,6 @@ export const updateGroupAttendee = (
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
})
|
})
|
||||||
|
|
||||||
// El adulto a cargo de un chico: edita el que tiene o vincula uno (por teléfono).
|
|
||||||
export const updateAttendeeGuardian = (groupId: string, attendeeId: string, payload: GuardianInput) =>
|
|
||||||
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/guardian`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
})
|
|
||||||
|
|
||||||
// Mueve al miembro a otro grupo del profe; devuelve el attendee con su nuevo `groupId`.
|
// Mueve al miembro a otro grupo del profe; devuelve el attendee con su nuevo `groupId`.
|
||||||
export const moveGroupAttendee = (groupId: string, attendeeId: string, targetGroupId: string) =>
|
export const moveGroupAttendee = (groupId: string, attendeeId: string, targetGroupId: string) =>
|
||||||
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/move`, {
|
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/move`, {
|
||||||
|
|||||||
@@ -45,7 +45,6 @@ import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accou
|
|||||||
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
||||||
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
||||||
import { Route as AuthenticatedGroupsGroupIdEditRouteImport } from './routes/_authenticated/groups/$groupId/edit'
|
|
||||||
import { Route as AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport } from './routes/_authenticated/groups/$groupId/attendees/$attendeeId'
|
import { Route as AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport } from './routes/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAttendeesNewRouteImport } from './routes/_authenticated/groups/$groupId/attendees/new'
|
import { Route as AuthenticatedGroupsGroupIdAttendeesNewRouteImport } from './routes/_authenticated/groups/$groupId/attendees/new'
|
||||||
|
|
||||||
@@ -234,12 +233,6 @@ const AuthenticatedGroupsGroupIdAnalyticsRoute =
|
|||||||
path: '/groups/$groupId/analytics',
|
path: '/groups/$groupId/analytics',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
const AuthenticatedGroupsGroupIdEditRoute =
|
|
||||||
AuthenticatedGroupsGroupIdEditRouteImport.update({
|
|
||||||
id: '/groups/$groupId/edit',
|
|
||||||
path: '/groups/$groupId/edit',
|
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
|
||||||
} as any)
|
|
||||||
const AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute =
|
const AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute =
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport.update({
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport.update({
|
||||||
id: '/groups/$groupId/attendees/$attendeeId',
|
id: '/groups/$groupId/attendees/$attendeeId',
|
||||||
@@ -287,7 +280,6 @@ export interface FileRoutesByFullPath {
|
|||||||
'/student/': typeof StudentStudentIndexRoute
|
'/student/': typeof StudentStudentIndexRoute
|
||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute
|
|
||||||
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
@@ -325,7 +317,6 @@ export interface FileRoutesByTo {
|
|||||||
'/student': typeof StudentStudentIndexRoute
|
'/student': typeof StudentStudentIndexRoute
|
||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute
|
|
||||||
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
@@ -367,7 +358,6 @@ export interface FileRoutesById {
|
|||||||
'/_student/student/': typeof StudentStudentIndexRoute
|
'/_student/student/': typeof StudentStudentIndexRoute
|
||||||
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/_authenticated/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute
|
|
||||||
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
'/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
'/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
'/_authenticated/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
'/_authenticated/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
@@ -408,7 +398,6 @@ export interface FileRouteTypes {
|
|||||||
| '/student/'
|
| '/student/'
|
||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId/edit'
|
|
||||||
| '/groups/$groupId/'
|
| '/groups/$groupId/'
|
||||||
| '/groups/$groupId/attendees/$attendeeId'
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
| '/groups/$groupId/attendees/new'
|
| '/groups/$groupId/attendees/new'
|
||||||
@@ -446,7 +435,6 @@ export interface FileRouteTypes {
|
|||||||
| '/student'
|
| '/student'
|
||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId/edit'
|
|
||||||
| '/groups/$groupId'
|
| '/groups/$groupId'
|
||||||
| '/groups/$groupId/attendees/$attendeeId'
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
| '/groups/$groupId/attendees/new'
|
| '/groups/$groupId/attendees/new'
|
||||||
@@ -487,7 +475,6 @@ export interface FileRouteTypes {
|
|||||||
| '/_student/student/'
|
| '/_student/student/'
|
||||||
| '/_authenticated/class/$sessionId/attendance'
|
| '/_authenticated/class/$sessionId/attendance'
|
||||||
| '/_authenticated/groups/$groupId/analytics'
|
| '/_authenticated/groups/$groupId/analytics'
|
||||||
| '/_authenticated/groups/$groupId/edit'
|
|
||||||
| '/_authenticated/groups/$groupId/'
|
| '/_authenticated/groups/$groupId/'
|
||||||
| '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
| '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
| '/_authenticated/groups/$groupId/attendees/new'
|
| '/_authenticated/groups/$groupId/attendees/new'
|
||||||
@@ -764,13 +751,6 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport
|
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
parentRoute: typeof AuthenticatedRoute
|
||||||
}
|
}
|
||||||
'/_authenticated/groups/$groupId/edit': {
|
|
||||||
id: '/_authenticated/groups/$groupId/edit'
|
|
||||||
path: '/groups/$groupId/edit'
|
|
||||||
fullPath: '/groups/$groupId/edit'
|
|
||||||
preLoaderRoute: typeof AuthenticatedGroupsGroupIdEditRouteImport
|
|
||||||
parentRoute: typeof AuthenticatedRoute
|
|
||||||
}
|
|
||||||
'/_authenticated/groups/$groupId/attendees/$attendeeId': {
|
'/_authenticated/groups/$groupId/attendees/$attendeeId': {
|
||||||
id: '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
id: '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
path: '/groups/$groupId/attendees/$attendeeId'
|
path: '/groups/$groupId/attendees/$attendeeId'
|
||||||
@@ -800,7 +780,6 @@ interface AuthenticatedRouteChildren {
|
|||||||
AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute
|
AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute
|
||||||
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
AuthenticatedGroupsGroupIdEditRoute: typeof AuthenticatedGroupsGroupIdEditRoute
|
|
||||||
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
AuthenticatedGroupsGroupIdAttendeesNewRoute: typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
AuthenticatedGroupsGroupIdAttendeesNewRoute: typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
@@ -820,7 +799,6 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
|||||||
AuthenticatedClassSessionIdAttendanceRoute,
|
AuthenticatedClassSessionIdAttendanceRoute,
|
||||||
AuthenticatedGroupsGroupIdAnalyticsRoute:
|
AuthenticatedGroupsGroupIdAnalyticsRoute:
|
||||||
AuthenticatedGroupsGroupIdAnalyticsRoute,
|
AuthenticatedGroupsGroupIdAnalyticsRoute,
|
||||||
AuthenticatedGroupsGroupIdEditRoute: AuthenticatedGroupsGroupIdEditRoute,
|
|
||||||
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute:
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute:
|
||||||
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute,
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute,
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
import { createFileRoute, useParams } from '@tanstack/react-router'
|
|
||||||
import { EditGroupView } from '../../../../features/groups/EditGroupView'
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/groups/$groupId/edit')({
|
|
||||||
component: () => {
|
|
||||||
const { groupId } = useParams({ from: '/_authenticated/groups/$groupId/edit' })
|
|
||||||
return <EditGroupView groupId={groupId} />
|
|
||||||
},
|
|
||||||
})
|
|
||||||
@@ -39,7 +39,6 @@ describe('copy del plan', () => {
|
|||||||
{ label: 'Hasta 15 alumnos activos', included: true },
|
{ label: 'Hasta 15 alumnos activos', included: true },
|
||||||
{ label: 'Cobros con Mercado Pago', included: false },
|
{ label: 'Cobros con Mercado Pago', included: false },
|
||||||
{ label: 'Mensajes automáticos por WhatsApp', included: false },
|
{ label: 'Mensajes automáticos por WhatsApp', included: false },
|
||||||
{ label: 'Grupos de chicos con adulto a cargo', included: false },
|
|
||||||
])
|
])
|
||||||
expect(planFeatureList(PLAN_LIMITS.PRO).every((feature) => feature.included)).toBe(true)
|
expect(planFeatureList(PLAN_LIMITS.PRO).every((feature) => feature.included)).toBe(true)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -108,7 +108,6 @@ export const UpdatePlanLimitsInputSchema = z.strictObject({
|
|||||||
maxAttendees: limitValueSchema,
|
maxAttendees: limitValueSchema,
|
||||||
whatsappAutomations: z.boolean(),
|
whatsappAutomations: z.boolean(),
|
||||||
mpCharges: z.boolean(),
|
mpCharges: z.boolean(),
|
||||||
kidsGroups: z.boolean(),
|
|
||||||
});
|
});
|
||||||
export type UpdatePlanLimitsInput = z.output<typeof UpdatePlanLimitsInputSchema>;
|
export type UpdatePlanLimitsInput = z.output<typeof UpdatePlanLimitsInputSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -24,11 +24,8 @@ export const AttendeeDtoSchema = z.object({
|
|||||||
fullName: z.string(),
|
fullName: z.string(),
|
||||||
email: z.string().nullable(),
|
email: z.string().nullable(),
|
||||||
phone: z.string().nullable(),
|
phone: z.string().nullable(),
|
||||||
/** The adult in charge (kids groups): a person of their own, flattened here. */
|
|
||||||
guardianPersonId: z.string().nullable(),
|
|
||||||
guardianName: z.string().nullable(),
|
guardianName: z.string().nullable(),
|
||||||
guardianPhone: z.string().nullable(),
|
guardianPhone: z.string().nullable(),
|
||||||
guardianEmail: z.string().nullable(),
|
|
||||||
notes: z.string().nullable(),
|
notes: z.string().nullable(),
|
||||||
notifyToken: z.string().nullable().optional(),
|
notifyToken: z.string().nullable().optional(),
|
||||||
createdAt: isoDateTimeSchema,
|
createdAt: isoDateTimeSchema,
|
||||||
@@ -79,8 +76,6 @@ export const AttendeeDetailDtoSchema = AttendeeDtoSchema.extend({
|
|||||||
payment: AttendeePaymentSummarySchema.nullable(),
|
payment: AttendeePaymentSummarySchema.nullable(),
|
||||||
/** The person's memberships in the teacher's other groups. */
|
/** The person's memberships in the teacher's other groups. */
|
||||||
otherGroups: z.array(PersonMembershipSchema),
|
otherGroups: z.array(PersonMembershipSchema),
|
||||||
/** Other kids of the same adult in charge (kids groups). */
|
|
||||||
siblings: z.array(z.object({ personId: z.string(), fullName: z.string() })),
|
|
||||||
});
|
});
|
||||||
export type AttendeeDetailDto = z.output<typeof AttendeeDetailDtoSchema>;
|
export type AttendeeDetailDto = z.output<typeof AttendeeDetailDtoSchema>;
|
||||||
|
|
||||||
@@ -120,35 +115,16 @@ export const AttendeeListSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type AttendeeList = z.output<typeof AttendeeListSchema>;
|
export type AttendeeList = z.output<typeof AttendeeListSchema>;
|
||||||
|
|
||||||
/* The adult in charge of a kid (kids groups). Found by phone among the
|
export const CreateAttendeeSchema = z.object({
|
||||||
teacher's people, so siblings share the same adult. */
|
firstName: z.string().trim().min(1, 'name.required'),
|
||||||
export const GuardianInputSchema = z.object({
|
lastName: z.string().trim().optional().default(''),
|
||||||
fullName: z.string().trim().min(1, 'guardian.nameRequired'),
|
|
||||||
phone: z.string().trim().min(6, 'phone.invalid'),
|
phone: z.string().trim().min(6, 'phone.invalid'),
|
||||||
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
|
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
|
||||||
|
notes: z.string().trim().optional(),
|
||||||
|
/* Adds an existing person of the teacher (found by phone) instead of creating
|
||||||
|
a new one: the name/email fields are ignored then. */
|
||||||
|
personId: z.string().min(1).optional(),
|
||||||
});
|
});
|
||||||
export type GuardianInput = z.output<typeof GuardianInputSchema>;
|
|
||||||
|
|
||||||
export const CreateAttendeeSchema = z
|
|
||||||
.object({
|
|
||||||
firstName: z.string().trim().min(1, 'name.required'),
|
|
||||||
lastName: z.string().trim().optional().default(''),
|
|
||||||
/* Optional only for a kid with an adult in charge (`guardian`) or when
|
|
||||||
adding an existing person (`personId`). */
|
|
||||||
phone: z.string().trim().min(6, 'phone.invalid').optional().or(z.literal('')),
|
|
||||||
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
|
|
||||||
notes: z.string().trim().optional(),
|
|
||||||
/* Adds an existing person of the teacher (found by phone) instead of creating
|
|
||||||
a new one: the name/email fields are ignored then. */
|
|
||||||
personId: z.string().min(1).optional(),
|
|
||||||
/* Kids groups: the adult in charge of a new kid. */
|
|
||||||
guardian: GuardianInputSchema.optional(),
|
|
||||||
})
|
|
||||||
.superRefine((value, ctx) => {
|
|
||||||
if (!value.phone && !value.guardian && !value.personId) {
|
|
||||||
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['phone'], message: 'phone.invalid' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
export type CreateAttendee = z.output<typeof CreateAttendeeSchema>;
|
export type CreateAttendee = z.output<typeof CreateAttendeeSchema>;
|
||||||
|
|
||||||
export const CreateAttendeeResultSchema = z.discriminatedUnion('outcome', [
|
export const CreateAttendeeResultSchema = z.discriminatedUnion('outcome', [
|
||||||
@@ -240,10 +216,6 @@ export const PersonSummarySchema = z.object({
|
|||||||
email: z.string().nullable(),
|
email: z.string().nullable(),
|
||||||
phone: z.string().nullable(),
|
phone: z.string().nullable(),
|
||||||
groups: z.array(PersonMembershipSchema),
|
groups: z.array(PersonMembershipSchema),
|
||||||
/** When the phone is an adult in charge: their kids, to add one of them or a sibling. */
|
|
||||||
children: z.array(
|
|
||||||
z.object({ id: z.string(), fullName: z.string(), groups: z.array(PersonMembershipSchema) }),
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
export type PersonSummary = z.output<typeof PersonSummarySchema>;
|
export type PersonSummary = z.output<typeof PersonSummarySchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const isoDateTimeSchema = z.string().datetime();
|
|||||||
export const planSchema = z.enum(['FREE', 'PRO']);
|
export const planSchema = z.enum(['FREE', 'PRO']);
|
||||||
export type Plan = z.output<typeof planSchema>;
|
export type Plan = z.output<typeof planSchema>;
|
||||||
|
|
||||||
export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges', 'kidsGroups']);
|
export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges']);
|
||||||
export type PlanFeature = z.output<typeof planFeatureSchema>;
|
export type PlanFeature = z.output<typeof planFeatureSchema>;
|
||||||
|
|
||||||
export type PlanLimits = {
|
export type PlanLimits = {
|
||||||
@@ -18,16 +18,14 @@ export type PlanLimits = {
|
|||||||
maxAttendees: number | null;
|
maxAttendees: number | null;
|
||||||
whatsappAutomations: boolean;
|
whatsappAutomations: boolean;
|
||||||
mpCharges: boolean;
|
mpCharges: boolean;
|
||||||
/** Groups of kids whose contact is the adult in charge. */
|
|
||||||
kidsGroups: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Defaults only: the live limits and prices are edited from the backoffice and
|
// Defaults only: the live limits and prices are edited from the backoffice and
|
||||||
// live in `plan_configs` / `plan_prices` (seeded with these values). The backend
|
// live in `plan_configs` / `plan_prices` (seeded with these values). The backend
|
||||||
// falls back to them when a row is missing; the web asks `GET /billing/plans`.
|
// falls back to them when a row is missing; the web asks `GET /billing/plans`.
|
||||||
export const PLAN_LIMITS: Record<Plan, PlanLimits> = {
|
export const PLAN_LIMITS: Record<Plan, PlanLimits> = {
|
||||||
FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false, kidsGroups: false },
|
FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false },
|
||||||
PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true, kidsGroups: true },
|
PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true },
|
||||||
};
|
};
|
||||||
|
|
||||||
// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY),
|
// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY),
|
||||||
@@ -76,7 +74,6 @@ export const PlanLimitsSchema = z.object({
|
|||||||
maxAttendees: z.number().int().nullable(),
|
maxAttendees: z.number().int().nullable(),
|
||||||
whatsappAutomations: z.boolean(),
|
whatsappAutomations: z.boolean(),
|
||||||
mpCharges: z.boolean(),
|
mpCharges: z.boolean(),
|
||||||
kidsGroups: z.boolean(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/** What each plan allows and what Pro costs in each country, as configured now. */
|
/** What each plan allows and what Pro costs in each country, as configured now. */
|
||||||
|
|||||||
@@ -14,9 +14,4 @@ export type WeekDay = z.output<typeof weekdaySchema>;
|
|||||||
|
|
||||||
// Billing frequency of a group.
|
// Billing frequency of a group.
|
||||||
export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']);
|
export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']);
|
||||||
export type BillingType = z.output<typeof billingTypeSchema>;
|
export type BillingType = z.output<typeof billingTypeSchema>;
|
||||||
|
|
||||||
// Who attends a group. In a KIDS group each student is a kid and the contact
|
|
||||||
// (messages, student app) is the adult in charge.
|
|
||||||
export const groupAudienceSchema = z.enum(['ADULTS', 'KIDS']);
|
|
||||||
export type GroupAudience = z.output<typeof groupAudienceSchema>;
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user