diff --git a/apps/backend/prisma/migrations/20261111120000_kids_groups/migration.sql b/apps/backend/prisma/migrations/20261111120000_kids_groups/migration.sql new file mode 100644 index 0000000..999047f --- /dev/null +++ b/apps/backend/prisma/migrations/20261111120000_kids_groups/migration.sql @@ -0,0 +1,11 @@ +-- 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'; diff --git a/apps/backend/prisma/migrations/20261111150000_person_guardians/migration.sql b/apps/backend/prisma/migrations/20261111150000_person_guardians/migration.sql new file mode 100644 index 0000000..8e43a2a --- /dev/null +++ b/apps/backend/prisma/migrations/20261111150000_person_guardians/migration.sql @@ -0,0 +1,52 @@ +-- 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"; diff --git a/apps/backend/prisma/models/billing.prisma b/apps/backend/prisma/models/billing.prisma index 9fa3298..d38c88e 100644 --- a/apps/backend/prisma/models/billing.prisma +++ b/apps/backend/prisma/models/billing.prisma @@ -102,6 +102,7 @@ model PlanConfig { maxAttendees Int? @map("max_attendees") whatsappAutomations Boolean @map("whatsapp_automations") mpCharges Boolean @map("mp_charges") + kidsGroups Boolean @default(false) @map("kids_groups") updatedById String? @map("updated_by_id") updatedAt DateTime @updatedAt @map("updated_at") diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index 3dacdf2..bed0a6b 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -13,6 +13,8 @@ model Group { // Weekly WhatsApp automations, off until the teacher turns them on. autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") autoReengagement Boolean @default(false) @map("auto_reengagement") + // 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") createdById String @map("created_by_id") createdAt DateTime @default(now()) @map("created_at") @@ -31,6 +33,11 @@ model Group { @@map("groups") } +enum GroupAudience { + ADULTS + KIDS +} + enum WeekDay { MONDAY TUESDAY @@ -83,8 +90,6 @@ model Person { fullName String @map("full_name") email String? phone String? - guardianName String? @map("guardian_name") - guardianPhone String? @map("guardian_phone") notes String? createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -92,11 +97,31 @@ model Person { owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade) attendees Attendee[] 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]) @@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 // link (`notifyToken`) are per group. model Attendee { diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts index 6db2820..297d0b0 100644 --- a/apps/backend/src/http/problem-builders.ts +++ b/apps/backend/src/http/problem-builders.ts @@ -1,4 +1,4 @@ -import type { ProblemDetails } from '@gruperly/shared'; +import type { PlanFeature, ProblemDetails } from '@gruperly/shared'; import { notFoundProblem } from './problem-details'; import { PROBLEM_DOMAIN } from './problem-domain'; @@ -248,13 +248,16 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob }); } -/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */ -export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails { +const PLAN_FEATURE_DETAIL: Record = { + mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.', + 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({ - 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.', + detail: PLAN_FEATURE_DETAIL[feature], code: 'plan_feature_required', params: { feature }, }); diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts index d3ea984..1399a5c 100644 --- a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts @@ -9,6 +9,7 @@ import type { import { ok, summarizeMemberAttendance } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { flattenPerson } from '@/modules/attendees/lib/helpers'; +import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk'; @@ -74,7 +75,7 @@ export async function findStudentsAtRisk( }), db.attendee.findMany({ where: { groupId, status: 'ACTIVE' }, - select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } }, + select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } }, }).then((rows) => rows.map(flattenPerson)), db.attendance.findMany({ where: { attendee: { groupId } }, @@ -111,7 +112,8 @@ export async function findStudentsAtRisk( atRisk.push({ attendeeId: attendee.id, fullName: attendee.fullName, - phone: attendee.phone, + // The number to reach them on: the adult in charge for a kid. + phone: contactPhone(attendee), riskLevel, consecutiveAbsences, lastAttendedAt: attendedAt ? attendedAt.toISOString() : null, diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts index 814600d..7ea3e1f 100644 --- a/apps/backend/src/modules/attendees/features/create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/create/use-case.ts @@ -1,5 +1,5 @@ import type { PrismaClient } from '@generated/prisma/client'; -import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared'; +import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { alreadyWaitlistedProblem, @@ -11,9 +11,13 @@ import prisma from '@/lib/prisma'; import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { alreadyInGroupProblem, + contactPhone, findPersonByPhone, + guardianRequiredProblem, + guardianSelect, isUniqueViolation, personExistsProblem, + type WithGuardians, } from '@/modules/people/lib/people'; import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; @@ -54,27 +58,51 @@ export class CreateAttendeeUseCase { return err(noGroupAccessProblem()); } - const phone = normalizePhone(payload.phone); + const isKidsGroup = group.audience === 'KIDS'; + 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" hint) or a new one. A phone the teacher already has is never duplicated. */ - let person: { id: string; fullName: string } | null = null; + let person: ({ id: string; fullName: string; phone: string | null } & WithGuardians) | 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) { person = await db.person.findFirst({ where: { id: payload.personId, createdById: group.createdById }, - select: { id: true, fullName: true }, + select: { id: true, fullName: true, phone: true, ...guardianSelect }, }); if (!person) { return err(notFoundResourceProblem('Person', payload.personId)); } } else { - const samePhone = await findPersonByPhone(db, group.createdById, payload.phone); - if (samePhone) { - return err( - samePhone.attendees.some((membership) => membership.groupId === groupId) - ? alreadyInGroupProblem() - : personExistsProblem(), - ); + if (payload.phone) { + // The raw phone: its variants also match older rows stored as typed. + const samePhone = await findPersonByPhone(db, group.createdById, payload.phone); + if (samePhone) { + return err( + samePhone.attendees.some((membership) => membership.groupId === groupId) + ? 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 }, + }); + } } } @@ -86,7 +114,12 @@ export class CreateAttendeeUseCase { return err(alreadyInGroupProblem()); } - const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); + const fullName = person?.fullName ?? kidFullName(payload); + // 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) { const currentCount = await db.attendee.count({ @@ -99,9 +132,9 @@ export class CreateAttendeeUseCase { } if (!isOwner) { - const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({ - where: { groupId, phone }, - }); + const existingWaitlistEntry = reachPhone + ? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } }) + : null; if (existingWaitlistEntry) { return err(alreadyWaitlistedProblem()); @@ -111,7 +144,7 @@ export class CreateAttendeeUseCase { data: { groupId, fullName, - phone, + phone: reachPhone ?? '', email: payload.email?.trim() || null, notes: payload.notes?.trim() || null, }, @@ -157,6 +190,7 @@ export class CreateAttendeeUseCase { phone, email: payload.email?.trim() || null, notes: payload.notes?.trim() || null, + ...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}), }, }, }, @@ -173,3 +207,24 @@ 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, + }, + }, + }; +} diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts index 60b220e..2bbbd44 100644 --- a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts @@ -4,11 +4,11 @@ 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 { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people'; +import { personMembershipsSelect, primaryGuardian, toMemberships } from '@/modules/people/lib/people'; import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers'; type GetAttendeeDeps = { - db?: Pick; + db?: Pick; now?: () => Date; }; @@ -48,11 +48,21 @@ export class GetAttendee { } 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( toAttendeeDetailDto({ ...attendee, person, otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)), + siblings: siblings.map(({ child }) => ({ personId: child.id, fullName: child.fullName })), }), ); } diff --git a/apps/backend/src/modules/attendees/features/update-guardian/route.ts b/apps/backend/src/modules/attendees/features/update-guardian/route.ts new file mode 100644 index 0000000..0ae7782 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update-guardian/route.ts @@ -0,0 +1,24 @@ +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; diff --git a/apps/backend/src/modules/attendees/features/update-guardian/use-case.ts b/apps/backend/src/modules/attendees/features/update-guardian/use-case.ts new file mode 100644 index 0000000..3503e3a --- /dev/null +++ b/apps/backend/src/modules/attendees/features/update-guardian/use-case.ts @@ -0,0 +1,75 @@ +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; +}; + +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> { + 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)); + } +} diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 066bd00..4fa8664 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -1,4 +1,5 @@ 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). */ export const personContactSelect = { @@ -6,9 +7,8 @@ export const personContactSelect = { fullName: true, email: true, phone: true, - guardianName: true, - guardianPhone: true, notes: true, + ...guardianSelect, } as const; /* `include` for any attendee query that ends up in `toAttendeeDto`. */ @@ -19,9 +19,8 @@ export type PersonContactRecord = { fullName: string; email: string | null; phone: string | null; - guardianName: string | null; - guardianPhone: string | null; notes: string | null; + guardians?: { guardian: GuardianContact }[]; }; export type AttendeeRecord = { @@ -46,8 +45,20 @@ export type AttendeeListItemRecord = AttendeeRecord & { export type AttendeeDetailRecord = AttendeeRecord & { payments: AttendeeListItemRecord['payments']; 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 { return { id: record.id, @@ -56,8 +67,7 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { fullName: record.person.fullName, email: record.person.email, phone: record.person.phone, - guardianName: record.person.guardianName, - guardianPhone: record.person.guardianPhone, + ...guardianFields(record.person), notes: record.person.notes, notifyToken: record.notifyToken ?? null, createdAt: record.createdAt.toISOString(), @@ -91,6 +101,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai ...toAttendeeDto(record), payment: pickRelevantPayment(record.payments), otherGroups: record.otherGroups, + siblings: record.siblings ?? [], }; } diff --git a/apps/backend/src/modules/attention/features/get-overview/use-case.ts b/apps/backend/src/modules/attention/features/get-overview/use-case.ts index aeec72e..663cf6a 100644 --- a/apps/backend/src/modules/attention/features/get-overview/use-case.ts +++ b/apps/backend/src/modules/attention/features/get-overview/use-case.ts @@ -13,7 +13,7 @@ import prisma from '@/lib/prisma'; import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; import { flattenPerson } from '@/modules/attendees/lib/helpers'; import { buildGroupWhereForUser } from '@/modules/groups/lib'; -import { contactPhone } from '@/modules/people/lib/people'; +import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; type GetAttentionOverviewDeps = { @@ -35,7 +35,7 @@ type AttendeeRow = { groupId: string; fullName: string; phone: string | null; - guardianPhone: string | null; + guardians?: { guardian: { phone: string | null } }[]; createdAt: Date; }; type SessionRow = { id: string; groupId: string; startsAt: Date }; @@ -88,7 +88,7 @@ export class GetAttentionOverview { id: true, groupId: true, createdAt: true, - person: { select: { fullName: true, phone: true, guardianPhone: true } }, + person: { select: { fullName: true, phone: true, ...guardianSelect } }, }, orderBy: { createdAt: 'asc' }, }).then((rows): AttendeeRow[] => rows.map(flattenPerson)), diff --git a/apps/backend/src/modules/billing/lib/catalog.ts b/apps/backend/src/modules/billing/lib/catalog.ts index 9159d51..a0741ff 100644 --- a/apps/backend/src/modules/billing/lib/catalog.ts +++ b/apps/backend/src/modules/billing/lib/catalog.ts @@ -58,6 +58,7 @@ export class PlanCatalog { maxAttendees: config.maxAttendees, whatsappAutomations: config.whatsappAutomations, mpCharges: config.mpCharges, + kidsGroups: config.kidsGroups, }; } for (const price of prices) { diff --git a/apps/backend/src/modules/groups/features/create/use-case.ts b/apps/backend/src/modules/groups/features/create/use-case.ts index 4e1eb8d..0ce904c 100644 --- a/apps/backend/src/modules/groups/features/create/use-case.ts +++ b/apps/backend/src/modules/groups/features/create/use-case.ts @@ -13,7 +13,7 @@ import { type GroupRecord, toGroupDto } from '../../lib'; type CreateGroupDeps = { unitOfWork?: UnitOfWork; - planGuard?: Pick; + planGuard?: Pick; }; export class CreateGroup { @@ -25,10 +25,15 @@ export class CreateGroup { ): Promise> { const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); - const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + const planGuard = this.deps.planGuard ?? new PlanGuard(); + const allowed = await planGuard.canCreateGroup(userId); if (!allowed.ok) { return allowed; } + if (data.audience === 'KIDS') { + const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups'); + if (!kidsAllowed.ok) return kidsAllowed; + } const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { @@ -42,6 +47,7 @@ export class CreateGroup { price: data.price, billingType: data.billingType, dueDay: data.dueDay, + audience: data.audience, }, }); diff --git a/apps/backend/src/modules/groups/features/update/route.ts b/apps/backend/src/modules/groups/features/update/route.ts new file mode 100644 index 0000000..cf6aa08 --- /dev/null +++ b/apps/backend/src/modules/groups/features/update/route.ts @@ -0,0 +1,20 @@ +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; diff --git a/apps/backend/src/modules/groups/features/update/use-case.ts b/apps/backend/src/modules/groups/features/update/use-case.ts new file mode 100644 index 0000000..e2474f1 --- /dev/null +++ b/apps/backend/src/modules/groups/features/update/use-case.ts @@ -0,0 +1,66 @@ +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; + planGuard?: Pick; +}; + +/** + * "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> { + 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)); + } +} diff --git a/apps/backend/src/modules/groups/lib/helpers.ts b/apps/backend/src/modules/groups/lib/helpers.ts index c6f6dd8..6e9436b 100644 --- a/apps/backend/src/modules/groups/lib/helpers.ts +++ b/apps/backend/src/modules/groups/lib/helpers.ts @@ -1,5 +1,5 @@ import type { PrismaClient } from '@generated/prisma/client'; -import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared'; +import type { BillingType, GroupAudience, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared'; export type GroupDb = Pick; @@ -21,6 +21,7 @@ export type GroupRecord = { inviteToken?: string | null; autoPaymentReminders?: boolean; autoReengagement?: boolean; + audience?: GroupAudience; }; /* The listing adds the occupancy counters to each group so the card can show @@ -49,6 +50,7 @@ export function toGroupDto(record: GroupRecord): GroupDto { inviteToken: record.inviteToken ?? null, autoPaymentReminders: record.autoPaymentReminders ?? false, autoReengagement: record.autoReengagement ?? false, + audience: record.audience ?? 'ADULTS', }; } diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index b1848bf..7193dc6 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -9,6 +9,7 @@ import getAttendeeStatsRoute from '../attendees/features/get-stats/route'; import moveAttendeeRoute from '../attendees/features/move/route'; import removeAttendeeRoute from '../attendees/features/remove/route'; import updateAttendeeRoute from '../attendees/features/update/route'; +import updateAttendeeGuardianRoute from '../attendees/features/update-guardian/route'; import groupPreRegistrationRoutes from '../group-preregistrations/routes'; import groupWaitlistRoutes from '../group-waitlist/routes'; import createPaymentsBatchRoute from '../payments/features/create-batch/route'; @@ -19,6 +20,7 @@ import getAllRoute from './features/get-all/route'; import getByIdRoute from './features/get-by-id/route'; import inviteTokenRoute from './features/invite-token/route'; import listAttendeesRoute from './features/list-attendees/route'; +import updateGroupRoute from './features/update/route'; const routes = new Hono(); @@ -31,12 +33,14 @@ routes.route('/', bulkCreateAttendeesRoute); routes.route('/', getByIdRoute); routes.route('/', createPaymentsBatchRoute); routes.route('/', updateGroupAutomationsRoute); +routes.route('/', updateGroupRoute); routes.route('/', addToGroupWaitlistRoute); routes.route('/', groupWaitlistRoutes); routes.route('/', groupPreRegistrationRoutes); routes.route('/', analyticsRoutes); routes.route('/', getAttendeeRoute); routes.route('/', updateAttendeeRoute); +routes.route('/', updateAttendeeGuardianRoute); routes.route('/', getAttendeeStatsRoute); routes.route('/', removeAttendeeRoute); routes.route('/', moveAttendeeRoute); diff --git a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts index 1714e08..6a31024 100644 --- a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts +++ b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts @@ -16,7 +16,7 @@ import { toOnboardingGroupDto } from '../../lib'; type CreateFirstGroupDeps = { db?: Pick; unitOfWork?: UnitOfWork; - planGuard?: Pick; + planGuard?: Pick; }; export class CreateFirstGroup { @@ -41,10 +41,15 @@ export class CreateFirstGroup { return err(planNotSelectedProblem()); } - const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); + const planGuard = this.deps.planGuard ?? new PlanGuard(); + const allowed = await planGuard.canCreateGroup(userId); if (!allowed.ok) { return allowed; } + if (data.audience === 'KIDS') { + const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups'); + if (!kidsAllowed.ok) return kidsAllowed; + } const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { @@ -58,6 +63,7 @@ export class CreateFirstGroup { price: data.price, billingType: data.billingType, dueDay: data.dueDay, + audience: data.audience, }, }); diff --git a/apps/backend/src/modules/onboarding/lib/helpers.ts b/apps/backend/src/modules/onboarding/lib/helpers.ts index 72a2ffb..ea09855 100644 --- a/apps/backend/src/modules/onboarding/lib/helpers.ts +++ b/apps/backend/src/modules/onboarding/lib/helpers.ts @@ -1,4 +1,4 @@ -import type { BillingType, OnboardingGroupDto, WeekDay } from '@gruperly/shared'; +import type { BillingType, GroupAudience, OnboardingGroupDto, WeekDay } from '@gruperly/shared'; type PriceLike = { toString(): string }; @@ -17,6 +17,7 @@ export type OnboardingGroupRecord = { dueDay: number | null; autoPaymentReminders?: boolean; autoReengagement?: boolean; + audience?: GroupAudience; }; export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto { @@ -35,5 +36,6 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG dueDay: record.dueDay, autoPaymentReminders: record.autoPaymentReminders ?? false, autoReengagement: record.autoReengagement ?? false, + audience: record.audience ?? 'ADULTS', }; } \ No newline at end of file diff --git a/apps/backend/src/modules/people/lib/guardians.ts b/apps/backend/src/modules/people/lib/guardians.ts new file mode 100644 index 0000000..314ae4f --- /dev/null +++ b/apps/backend/src/modules/people/lib/guardians.ts @@ -0,0 +1,21 @@ +/* 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 & { phone: string | null } }[] }; + +export function primaryGuardian(person: { + guardians?: { guardian: T }[]; +}): T | null { + return person.guardians?.[0]?.guardian ?? null; +} diff --git a/apps/backend/src/modules/people/lib/people.ts b/apps/backend/src/modules/people/lib/people.ts index 1baa790..ae88389 100644 --- a/apps/backend/src/modules/people/lib/people.ts +++ b/apps/backend/src/modules/people/lib/people.ts @@ -1,7 +1,11 @@ import { Prisma, type PrismaClient } from '@generated/prisma/client'; import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared'; import { conflictProblem } from '@/http/problem-builders'; +import { problemDetails } from '@/http/problem-details'; 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 `attendees` are the memberships in each group. The phone is unique per @@ -60,12 +64,27 @@ export async function findPersonSummaryByPhone( ): Promise { const person = await findPersonByPhone(db, ownerId, rawPhone); 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 { id: person.id, fullName: person.fullName, email: person.email, phone: person.phone, groups: toMemberships(person.attendees), + children: (links?.children ?? []).map(({ child }) => ({ + id: child.id, + fullName: child.fullName, + groups: toMemberships(child.attendees), + })), }; } @@ -109,9 +128,24 @@ export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone return !person?.attendees.some((membership) => membership.status === 'ACTIVE'); } -/* The number the teacher reaches the person on: theirs, or the guardian's. */ -export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null { - return person.phone ?? person.guardianPhone; +/* The number the teacher reaches the person on: the adult in charge when there + is one (a kid's own phone, if any, is not who answers for them), else theirs. */ +export function contactPhone(person: { phone: string | null } & WithGuardians): string | null { + 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 { @@ -134,6 +168,16 @@ 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 { return conflictProblem({ detail: 'Otra persona que tenés registrada ya usa este número de teléfono.', diff --git a/apps/backend/src/modules/student-access/features/invite/use-case.ts b/apps/backend/src/modules/student-access/features/invite/use-case.ts index b85b99d..285a8dc 100644 --- a/apps/backend/src/modules/student-access/features/invite/use-case.ts +++ b/apps/backend/src/modules/student-access/features/invite/use-case.ts @@ -4,7 +4,7 @@ import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from import { notFoundResourceProblem } from '@/http/problem-builders'; import prisma, { UnitOfWork } from '@/lib/prisma'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; -import { contactPhone } from '@/modules/people/lib/people'; +import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; import { computeStudentAccess } from '../../lib/status'; @@ -38,7 +38,7 @@ export class InviteStudent { select: { id: true, personId: true, - person: { select: { fullName: true, phone: true, guardianPhone: true } }, + person: { select: { fullName: true, phone: true, ...guardianSelect } }, group: { select: { owner: { select: { country: true } } } }, }, }); diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts index bcb61c5..42c916b 100644 --- a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts +++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts @@ -1,7 +1,7 @@ import type { PrismaClient } from '@generated/prisma/client'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; -import { contactPhone } from '@/modules/people/lib/people'; +import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { addTotals, type DispatchItem, @@ -71,7 +71,7 @@ export class SendPaymentReminders { dueDate: true, checkoutUrl: true, attendee: { - select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } }, + select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } }, }, }, orderBy: { dueDate: 'asc' }, diff --git a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts index a02d7a1..6774575 100644 --- a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts +++ b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts @@ -5,7 +5,7 @@ import { findStudentsAtRisk, type StudentsAtRiskDb, } from '@/modules/analytics/features/get-students-at-risk/use-case'; -import { contactPhone } from '@/modules/people/lib/people'; +import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { addTotals, type DispatchItem, @@ -70,7 +70,7 @@ export class SendReengagementMessages { }), db.attendee.findMany({ where: { id: { in: ids } }, - select: { id: true, person: { select: { phone: true, guardianPhone: true } } }, + select: { id: true, person: { select: { phone: true, ...guardianSelect } } }, }), ]); const coolingDown = new Set(recent.map((row) => row.attendeeId)); diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts index 0dd69af..ec90df7 100644 --- a/apps/backend/test/attendee-get-by-id.test.ts +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -8,6 +8,9 @@ const db = { attendee: { findFirst: mock(), }, + personGuardian: { + findMany: mock(), + }, }; mock.module('@/lib/prisma', () => ({ @@ -44,9 +47,9 @@ const attendee = { fullName: 'Ana Pérez', email: 'ana@example.com', phone: '5512345678', - guardianName: 'Luis Pérez', - guardianPhone: 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. attendees: [ { id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } }, @@ -69,6 +72,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => { it('devuelve el participante del grupo', async () => { prisma.group.findUnique.mockResolvedValue(makeGroup()); 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'); @@ -80,15 +84,21 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => { fullName: 'Ana Pérez', email: 'ana@example.com', phone: '5512345678', + guardianPersonId: 'person-9', guardianName: 'Luis Pérez', - guardianPhone: null, + guardianPhone: '5598765432', + guardianEmail: null, notes: null, notifyToken: 'token-1', createdAt: '2026-08-01T10:00:00.000Z', updatedAt: '2026-08-01T10:00:00.000Z', payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' }, 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({ where: { id: 'a-1', groupId: 'group-1' }, include: { diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts index daf6052..6ba4afe 100644 --- a/apps/backend/test/attendees-incorporation.test.ts +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -218,7 +218,7 @@ describe('attendee incorporation & invite-token in groups', () => { expect(res.status).toBe(201); expect(prisma.person.findFirst).toHaveBeenCalledWith({ where: { id: 'person-1', createdById: teacherId }, - select: { id: true, fullName: true }, + select: expect.objectContaining({ id: true, fullName: true }), }); expect(prisma.attendee.create).toHaveBeenCalledWith({ data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } }, diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index 428229b..b244ac7 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -24,9 +24,12 @@ const personSelect = { fullName: true, email: true, phone: true, - guardianName: true, - guardianPhone: true, notes: true, + guardians: { + take: 1, + orderBy: { createdAt: 'asc' }, + select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } }, + }, }; const person = { @@ -34,9 +37,8 @@ const person = { fullName: 'Ana Pérez', email: 'ana@example.com', phone: null, - guardianName: 'Luis Pérez', - guardianPhone: null, notes: null, + guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '1199990000', email: null } }], }; const attendeeRow = { @@ -75,8 +77,10 @@ describe('attendees routes', () => { fullName: person.fullName, email: person.email, phone: person.phone, - guardianName: person.guardianName, - guardianPhone: person.guardianPhone, + guardianPersonId: 'person-9', + guardianName: 'Luis Pérez', + guardianPhone: '1199990000', + guardianEmail: null, notes: person.notes, createdAt: attendeeRow.createdAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(), diff --git a/apps/backend/test/attention.test.ts b/apps/backend/test/attention.test.ts index db289fb..faf0817 100644 --- a/apps/backend/test/attention.test.ts +++ b/apps/backend/test/attention.test.ts @@ -39,9 +39,9 @@ describe('GetAttentionOverview', () => { db.user.findUnique.mockResolvedValue({ country: 'AR' }); db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]); db.attendee.findMany.mockResolvedValue([ - { id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) }, - { id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) }, - { id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) }, + { id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', createdAt: at(90) }, + { id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardians: [{ guardian: { phone: '1166660000' } }], createdAt: at(90) }, + { id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, createdAt: at(90) }, ]); db.classSession.findMany.mockResolvedValue([ { id: 's1', groupId: 'g1', startsAt: at(1) }, diff --git a/apps/backend/test/billing-plan-guards.test.ts b/apps/backend/test/billing-plan-guards.test.ts index 77cc2bd..a175de5 100644 --- a/apps/backend/test/billing-plan-guards.test.ts +++ b/apps/backend/test/billing-plan-guards.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, mock } from 'bun:test'; -import { err } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; import { planFeatureRequiredProblem, planLimitReachedProblem, } from '@/http/problem-builders'; import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-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 { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case'; @@ -14,7 +15,10 @@ const ownerId = 'owner-1'; describe('plan guards in the use cases', () => { it('does not create a group past the Free limit', async () => { const unitOfWork = { executeResult: mock() }; - const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) }; + const planGuard = { + canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))), + requireFeature: mock(async () => ok(undefined)), + }; const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute( {} as never, @@ -92,4 +96,100 @@ describe('plan guards in the use cases', () => { expect(off.ok).toBe(true); 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 = {}) { + 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, + }; +} diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts index af70646..f89982d 100644 --- a/apps/backend/test/groups.test.ts +++ b/apps/backend/test/groups.test.ts @@ -42,6 +42,7 @@ const group = { inviteToken: null, autoPaymentReminders: false, autoReengagement: false, + audience: 'ADULTS', }; function makeApp(userValue: unknown) { @@ -223,6 +224,7 @@ describe('groups routes', () => { price: 500, billingType: 'MONTHLY', dueDay: 5, + audience: 'ADULTS', }, }); expect(prisma.groupMember.create).toHaveBeenCalledWith({ diff --git a/apps/backend/test/kids-groups.test.ts b/apps/backend/test/kids-groups.test.ts new file mode 100644 index 0000000..bec2a81 --- /dev/null +++ b/apps/backend/test/kids-groups.test.ts @@ -0,0 +1,219 @@ +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 = {}) { + 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) { + 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' } }); + }); +}); diff --git a/apps/backend/test/onboarding.test.ts b/apps/backend/test/onboarding.test.ts index 80f5684..ca8a707 100644 --- a/apps/backend/test/onboarding.test.ts +++ b/apps/backend/test/onboarding.test.ts @@ -207,6 +207,7 @@ describe('onboarding routes', () => { dueDay: 5, autoPaymentReminders: false, autoReengagement: false, + audience: 'ADULTS', }, onboardingCompleted: true, }); @@ -220,6 +221,7 @@ describe('onboarding routes', () => { price: 150.5, billingType: 'MONTHLY', dueDay: 5, + audience: 'ADULTS', }, }); expect(prisma.groupMember.create).toHaveBeenCalledWith({ diff --git a/apps/backend/test/whatsapp-jobs.test.ts b/apps/backend/test/whatsapp-jobs.test.ts index 9b43f2e..b477f33 100644 --- a/apps/backend/test/whatsapp-jobs.test.ts +++ b/apps/backend/test/whatsapp-jobs.test.ts @@ -37,7 +37,7 @@ function payment(id: string, attendee: Record, overrides: Recor currency: 'ARS', dueDate: new Date('2026-10-20T15:00:00.000Z'), checkoutUrl: `https://mpago.la/${id}`, - attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } }, + attendee: { id: attendee.id, person: { phone: null, ...attendee } }, ...overrides, }; } @@ -174,7 +174,7 @@ describe('payment reminders', () => { it('falls back to the guardian phone and skips members without a usable one', async () => { db.payment.findMany.mockResolvedValue([ - payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }), + payment('pay-1', { id: 'att-1', fullName: 'Nene', guardians: [{ guardian: { phone: '1123456789' } }] }), payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }), ]); diff --git a/apps/web/src/features/admin/PlanLimitsCard.tsx b/apps/web/src/features/admin/PlanLimitsCard.tsx index 6af29ca..d153384 100644 --- a/apps/web/src/features/admin/PlanLimitsCard.tsx +++ b/apps/web/src/features/admin/PlanLimitsCard.tsx @@ -62,6 +62,11 @@ export function PlanLimitsCard({ plan, limits }: { plan: Plan; limits: PlanLimit checked={draft.whatsappAutomations} onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })} /> + setDraft({ ...draft, kidsGroups })} + /> diff --git a/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx index 4b9c803..d7f9765 100644 --- a/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx +++ b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx @@ -2,6 +2,7 @@ import { useId, useState } from 'react' import { Check, Copy, MessageCircle } from 'lucide-react' import { cn } from '../../lib/utils' import { useAttendeeDetail } from './AttendeeDetailProvider' +import { reachPhone } from './detail' import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton' import { Section } from './Section' import { useCopyToClipboard } from './useCopyToClipboard' @@ -18,7 +19,7 @@ export function AbsenceLinkSection() { const url = token ? `${window.location.origin}/report-absence/${token}` : null if (!attendee || !url) return null - const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? '' + const phoneDigits = reachPhone(attendee)?.replace(/\D/g, '') ?? '' const shareUrl = phoneDigits ? `https://wa.me/${phoneDigits}?text=${encodeURIComponent( t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }), diff --git a/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx index 05ea410..2ceebc7 100644 --- a/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx @@ -3,15 +3,16 @@ import { formatPhoneDisplay } from '../../lib/format' import { cn } from '../../lib/utils' import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton' import { useAttendeeDetail } from './AttendeeDetailProvider' +import { reachPhone } from './detail' import { useTranslation } from 'react-i18next' export function AttendeeContactActions() { const { attendee } = useAttendeeDetail() const { t } = useTranslation(['attendeeDetail', 'common']) - const phone = attendee?.phone + const phone = attendee ? reachPhone(attendee) : null const digits = phone?.replace(/\D/g, '') ?? '' - const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember') + const label = attendee?.guardianName ?? formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember') return (
diff --git a/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx index 924f729..b842406 100644 --- a/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx @@ -123,7 +123,7 @@ type ContactRowProps = { placeholder: boolean } -function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) { +export function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) { const content = ( <>
) : null} diff --git a/apps/web/src/i18n/locales/en/admin.json b/apps/web/src/i18n/locales/en/admin.json index 924b001..51b2aac 100644 --- a/apps/web/src/i18n/locales/en/admin.json +++ b/apps/web/src/i18n/locales/en/admin.json @@ -105,6 +105,7 @@ "unlimitedFor": "{{label}} with no limit", "mpCharges": "Mercado Pago charges", "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_other": "{{count}} accounts already exceed these limits and will become read only when you save.", "saved": "Limits saved." diff --git a/apps/web/src/i18n/locales/en/attendeeDetail.json b/apps/web/src/i18n/locales/en/attendeeDetail.json index e03a588..6f66233 100644 --- a/apps/web/src/i18n/locales/en/attendeeDetail.json +++ b/apps/web/src/i18n/locales/en/attendeeDetail.json @@ -158,5 +158,15 @@ "alreadyMember": "This person is already a member of that group.", "moveError": "We couldn't change 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." } } diff --git a/apps/web/src/i18n/locales/en/billing.json b/apps/web/src/i18n/locales/en/billing.json index 06edbf0..1fde5f2 100644 --- a/apps/web/src/i18n/locales/en/billing.json +++ b/apps/web/src/i18n/locales/en/billing.json @@ -11,7 +11,8 @@ "unlimitedStudents": "Unlimited students", "students": "Up to {{count}} active students", "mpCharges": "Payments with Mercado Pago", - "whatsapp": "Automatic WhatsApp messages" + "whatsapp": "Automatic WhatsApp messages", + "kidsGroups": "Kids groups with an adult in charge" }, "subscriptionStatus": { "AUTHORIZED": "Active", diff --git a/apps/web/src/i18n/locales/en/errors.json b/apps/web/src/i18n/locales/en/errors.json index 5557d83..44d072a 100644 --- a/apps/web/src/i18n/locales/en/errors.json +++ b/apps/web/src/i18n/locales/en/errors.json @@ -23,7 +23,7 @@ "group_capacity_reached": "The group is full.", "group_capacity_reached_one": "The group is full ({{count}} member max).", "group_capacity_reached_other": "The group is full ({{count}} members max).", - "group_owner_required": "Only the group's creator can change its automations.", + "group_owner_required": "Only the group's creator can make this change.", "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_not_configured": "Linking with Mercado Pago isn't available right now.", @@ -41,6 +41,7 @@ "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_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_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.", @@ -62,7 +63,9 @@ "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_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": { "INVALID_EMAIL_OR_PASSWORD": "The email or password is incorrect.", diff --git a/apps/web/src/i18n/locales/en/groupAdd.json b/apps/web/src/i18n/locales/en/groupAdd.json index 48321c8..9f15e62 100644 --- a/apps/web/src/i18n/locales/en/groupAdd.json +++ b/apps/web/src/i18n/locales/en/groupAdd.json @@ -93,5 +93,22 @@ "importedLinked": "{{count}} were already in your other groups.", "importedDuplicates_one": "{{count}} duplicate 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": "{{name}} is already saved with that phone: they will be the adult in charge.", + "foundWithKids": "{{name}} 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" + } } } diff --git a/apps/web/src/i18n/locales/en/groups.json b/apps/web/src/i18n/locales/en/groups.json index 6af5dce..9ed8ede 100644 --- a/apps/web/src/i18n/locales/en/groups.json +++ b/apps/web/src/i18n/locales/en/groups.json @@ -55,6 +55,15 @@ "form": { "name": "Group name", "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", "time": "Time", "capacity": "Capacity", @@ -66,5 +75,13 @@ "submitting": "Creating…", "whenLegend": "Classes", "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." } } diff --git a/apps/web/src/i18n/locales/en/validation.json b/apps/web/src/i18n/locales/en/validation.json index 6c417e9..5909d6a 100644 --- a/apps/web/src/i18n/locales/en/validation.json +++ b/apps/web/src/i18n/locales/en/validation.json @@ -63,5 +63,8 @@ }, "billing": { "priceInvalid": "Enter a price greater than zero" + }, + "guardian": { + "nameRequired": "Enter the name of the adult in charge" } } diff --git a/apps/web/src/i18n/locales/es-419/admin.json b/apps/web/src/i18n/locales/es-419/admin.json index 28a77c9..851b321 100644 --- a/apps/web/src/i18n/locales/es-419/admin.json +++ b/apps/web/src/i18n/locales/es-419/admin.json @@ -105,6 +105,7 @@ "unlimitedFor": "{{label}} sin límite", "mpCharges": "Cobros con Mercado Pago", "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_other": "{{count}} cuentas ya superan estos límites y quedarán en solo lectura al guardar.", "saved": "Límites guardados." diff --git a/apps/web/src/i18n/locales/es-419/attendeeDetail.json b/apps/web/src/i18n/locales/es-419/attendeeDetail.json index 2eebed3..7a0c42c 100644 --- a/apps/web/src/i18n/locales/es-419/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-419/attendeeDetail.json @@ -158,5 +158,15 @@ "alreadyMember": "Esta persona ya es miembro de ese grupo.", "moveError": "No se pudo cambiar de 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." } } diff --git a/apps/web/src/i18n/locales/es-419/billing.json b/apps/web/src/i18n/locales/es-419/billing.json index 667b2bf..283a4f7 100644 --- a/apps/web/src/i18n/locales/es-419/billing.json +++ b/apps/web/src/i18n/locales/es-419/billing.json @@ -11,7 +11,8 @@ "unlimitedStudents": "Alumnos ilimitados", "students": "Hasta {{count}} alumnos activos", "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": { "AUTHORIZED": "Activa", diff --git a/apps/web/src/i18n/locales/es-419/errors.json b/apps/web/src/i18n/locales/es-419/errors.json index b828e1f..b37cbe4 100644 --- a/apps/web/src/i18n/locales/es-419/errors.json +++ b/apps/web/src/i18n/locales/es-419/errors.json @@ -23,7 +23,7 @@ "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_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.", - "group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.", + "group_owner_required": "Solo quien creó el grupo puede hacer este cambio.", "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_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.", @@ -41,6 +41,7 @@ "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_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_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.", @@ -62,7 +63,9 @@ "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_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": { "INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.", diff --git a/apps/web/src/i18n/locales/es-419/groupAdd.json b/apps/web/src/i18n/locales/es-419/groupAdd.json index 4bdfa4c..1d41613 100644 --- a/apps/web/src/i18n/locales/es-419/groupAdd.json +++ b/apps/web/src/i18n/locales/es-419/groupAdd.json @@ -93,5 +93,22 @@ "importedLinked": "{{count}} ya estaban en otros de tus grupos.", "importedDuplicates_one": "{{count}} duplicado omitido.", "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": "{{name}} ya está registrado con ese teléfono: queda como adulto a cargo.", + "foundWithKids": "{{name}} 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" + } } } diff --git a/apps/web/src/i18n/locales/es-419/groups.json b/apps/web/src/i18n/locales/es-419/groups.json index bb76d43..ba13cdc 100644 --- a/apps/web/src/i18n/locales/es-419/groups.json +++ b/apps/web/src/i18n/locales/es-419/groups.json @@ -55,6 +55,15 @@ "form": { "name": "Nombre del grupo", "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", "time": "Horario", "capacity": "Cupo máximo", @@ -66,5 +75,13 @@ "submitting": "Creando…", "whenLegend": "Las clases", "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." } } diff --git a/apps/web/src/i18n/locales/es-419/validation.json b/apps/web/src/i18n/locales/es-419/validation.json index f93dc85..ce2114f 100644 --- a/apps/web/src/i18n/locales/es-419/validation.json +++ b/apps/web/src/i18n/locales/es-419/validation.json @@ -63,5 +63,8 @@ }, "billing": { "priceInvalid": "Ingresa un precio mayor a cero" + }, + "guardian": { + "nameRequired": "Ingresa el nombre del adulto a cargo" } } diff --git a/apps/web/src/i18n/locales/es-AR/admin.json b/apps/web/src/i18n/locales/es-AR/admin.json index 97619af..45fc772 100644 --- a/apps/web/src/i18n/locales/es-AR/admin.json +++ b/apps/web/src/i18n/locales/es-AR/admin.json @@ -105,6 +105,7 @@ "unlimitedFor": "{{label}} sin límite", "mpCharges": "Cobros con Mercado Pago", "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_other": "{{count}} cuentas ya superan estos límites y van a quedar en solo lectura al guardar.", "saved": "Límites guardados." diff --git a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json index d542155..1007b39 100644 --- a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json @@ -158,5 +158,15 @@ "alreadyMember": "Esta persona ya es miembro de ese grupo.", "moveError": "No se pudo cambiar de 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." } } diff --git a/apps/web/src/i18n/locales/es-AR/billing.json b/apps/web/src/i18n/locales/es-AR/billing.json index 7d443f4..e5df191 100644 --- a/apps/web/src/i18n/locales/es-AR/billing.json +++ b/apps/web/src/i18n/locales/es-AR/billing.json @@ -11,7 +11,8 @@ "unlimitedStudents": "Alumnos ilimitados", "students": "Hasta {{count}} alumnos activos", "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": { "AUTHORIZED": "Activa", diff --git a/apps/web/src/i18n/locales/es-AR/errors.json b/apps/web/src/i18n/locales/es-AR/errors.json index a6c87ae..501b134 100644 --- a/apps/web/src/i18n/locales/es-AR/errors.json +++ b/apps/web/src/i18n/locales/es-AR/errors.json @@ -23,7 +23,7 @@ "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_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.", - "group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.", + "group_owner_required": "Solo quien creó el grupo puede hacer este cambio.", "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_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.", @@ -41,6 +41,7 @@ "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_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_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.", @@ -62,7 +63,9 @@ "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_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": { "INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.", diff --git a/apps/web/src/i18n/locales/es-AR/groupAdd.json b/apps/web/src/i18n/locales/es-AR/groupAdd.json index 3ce3510..3c0c242 100644 --- a/apps/web/src/i18n/locales/es-AR/groupAdd.json +++ b/apps/web/src/i18n/locales/es-AR/groupAdd.json @@ -93,5 +93,22 @@ "importedLinked": "{{count}} ya estaban en otros de tus grupos.", "importedDuplicates_one": "{{count}} duplicado omitido.", "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": "{{name}} ya está registrado con ese teléfono: queda como adulto a cargo.", + "foundWithKids": "{{name}} 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" + } } } diff --git a/apps/web/src/i18n/locales/es-AR/groups.json b/apps/web/src/i18n/locales/es-AR/groups.json index 87ca252..3d2dfe2 100644 --- a/apps/web/src/i18n/locales/es-AR/groups.json +++ b/apps/web/src/i18n/locales/es-AR/groups.json @@ -55,6 +55,15 @@ "form": { "name": "Nombre del grupo", "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", "time": "Horario", "capacity": "Cupo máximo", @@ -66,5 +75,13 @@ "submitting": "Creando…", "whenLegend": "Las clases", "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." } } diff --git a/apps/web/src/i18n/locales/es-AR/validation.json b/apps/web/src/i18n/locales/es-AR/validation.json index 86aea06..7239b0e 100644 --- a/apps/web/src/i18n/locales/es-AR/validation.json +++ b/apps/web/src/i18n/locales/es-AR/validation.json @@ -63,5 +63,8 @@ }, "billing": { "priceInvalid": "Ingresá un precio mayor a cero" + }, + "guardian": { + "nameRequired": "Ingresá el nombre del adulto a cargo" } } diff --git a/apps/web/src/i18n/locales/pt-BR/admin.json b/apps/web/src/i18n/locales/pt-BR/admin.json index 86bd9f3..e3d096b 100644 --- a/apps/web/src/i18n/locales/pt-BR/admin.json +++ b/apps/web/src/i18n/locales/pt-BR/admin.json @@ -105,6 +105,7 @@ "unlimitedFor": "{{label}} sem limite", "mpCharges": "Cobranças com Mercado Pago", "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_other": "{{count}} contas já passam desses limites e vão ficar em somente leitura ao salvar.", "saved": "Limites salvos." diff --git a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json index 018fc4a..0f7abbf 100644 --- a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json @@ -158,5 +158,15 @@ "alreadyMember": "Esta pessoa já é membro desse grupo.", "moveError": "Não foi possível mudar de 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." } } diff --git a/apps/web/src/i18n/locales/pt-BR/billing.json b/apps/web/src/i18n/locales/pt-BR/billing.json index 4a91a34..b277db1 100644 --- a/apps/web/src/i18n/locales/pt-BR/billing.json +++ b/apps/web/src/i18n/locales/pt-BR/billing.json @@ -11,7 +11,8 @@ "unlimitedStudents": "Alunos ilimitados", "students": "Até {{count}} alunos ativos", "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": { "AUTHORIZED": "Ativa", diff --git a/apps/web/src/i18n/locales/pt-BR/errors.json b/apps/web/src/i18n/locales/pt-BR/errors.json index d6598d9..d3bd41b 100644 --- a/apps/web/src/i18n/locales/pt-BR/errors.json +++ b/apps/web/src/i18n/locales/pt-BR/errors.json @@ -23,7 +23,7 @@ "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_other": "O grupo atingiu o limite máximo de {{count}} membros.", - "group_owner_required": "Só quem criou o grupo pode mudar as automações.", + "group_owner_required": "Só quem criou a turma pode fazer essa alteração.", "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_not_configured": "A vinculação com o Mercado Pago não está disponível no momento.", @@ -41,6 +41,7 @@ "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_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_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.", @@ -62,7 +63,9 @@ "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_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": { "INVALID_EMAIL_OR_PASSWORD": "E-mail ou senha incorretos.", diff --git a/apps/web/src/i18n/locales/pt-BR/groupAdd.json b/apps/web/src/i18n/locales/pt-BR/groupAdd.json index 3f9dfd7..76f2cff 100644 --- a/apps/web/src/i18n/locales/pt-BR/groupAdd.json +++ b/apps/web/src/i18n/locales/pt-BR/groupAdd.json @@ -93,5 +93,22 @@ "importedLinked": "{{count}} já estavam em outros grupos seus.", "importedDuplicates_one": "{{count}} duplicado ignorado.", "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": "{{name}} já está cadastrado com esse telefone: fica como responsável.", + "foundWithKids": "{{name}} 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" + } } } diff --git a/apps/web/src/i18n/locales/pt-BR/groups.json b/apps/web/src/i18n/locales/pt-BR/groups.json index 189a728..ed7645a 100644 --- a/apps/web/src/i18n/locales/pt-BR/groups.json +++ b/apps/web/src/i18n/locales/pt-BR/groups.json @@ -55,6 +55,15 @@ "form": { "name": "Nome do grupo", "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", "time": "Horário", "capacity": "Vagas", @@ -66,5 +75,13 @@ "submitting": "Criando…", "whenLegend": "As aulas", "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." } } diff --git a/apps/web/src/i18n/locales/pt-BR/validation.json b/apps/web/src/i18n/locales/pt-BR/validation.json index 2878744..fa69565 100644 --- a/apps/web/src/i18n/locales/pt-BR/validation.json +++ b/apps/web/src/i18n/locales/pt-BR/validation.json @@ -63,5 +63,8 @@ }, "billing": { "priceInvalid": "Informe um preço maior que zero" + }, + "guardian": { + "nameRequired": "Informe o nome do responsável" } } diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index ea09a41..cd62e8d 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -35,6 +35,8 @@ import type { CreatePaymentsBatchResult, GroupAnalytics, GroupDto, + GuardianInput, + UpdateGroup, GroupInviteInfoDto, GroupList, GroupPreRegistrationList, @@ -220,6 +222,12 @@ export const getWhatsappStatus = () => apiFetch('/api/v1/what export const disconnectWhatsapp = () => apiFetch('/api/v1/whatsapp/connect', { method: 'DELETE' }) +export const updateGroup = (groupId: string, payload: UpdateGroup) => + apiFetch(`/api/v1/groups/${groupId}`, { + method: 'PATCH', + body: JSON.stringify(payload), + }) + export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) => apiFetch(`/api/v1/groups/${groupId}/automations`, { method: 'PATCH', @@ -329,6 +337,13 @@ export const updateGroupAttendee = ( 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(`/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`. export const moveGroupAttendee = (groupId: string, attendeeId: string, targetGroupId: string) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}/move`, { diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index e1d11ea..2d05549 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -45,6 +45,7 @@ import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accou import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance' import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index' 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 AuthenticatedGroupsGroupIdAttendeesNewRouteImport } from './routes/_authenticated/groups/$groupId/attendees/new' @@ -233,6 +234,12 @@ const AuthenticatedGroupsGroupIdAnalyticsRoute = path: '/groups/$groupId/analytics', getParentRoute: () => AuthenticatedRoute, } as any) +const AuthenticatedGroupsGroupIdEditRoute = + AuthenticatedGroupsGroupIdEditRouteImport.update({ + id: '/groups/$groupId/edit', + path: '/groups/$groupId/edit', + getParentRoute: () => AuthenticatedRoute, + } as any) const AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute = AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport.update({ id: '/groups/$groupId/attendees/$attendeeId', @@ -280,6 +287,7 @@ export interface FileRoutesByFullPath { '/student/': typeof StudentStudentIndexRoute '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute '/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute '/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute '/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute @@ -317,6 +325,7 @@ export interface FileRoutesByTo { '/student': typeof StudentStudentIndexRoute '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute '/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute '/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute '/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute @@ -358,6 +367,7 @@ export interface FileRoutesById { '/_student/student/': typeof StudentStudentIndexRoute '/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/_authenticated/groups/$groupId/edit': typeof AuthenticatedGroupsGroupIdEditRoute '/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute '/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute '/_authenticated/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute @@ -398,6 +408,7 @@ export interface FileRouteTypes { | '/student/' | '/class/$sessionId/attendance' | '/groups/$groupId/analytics' + | '/groups/$groupId/edit' | '/groups/$groupId/' | '/groups/$groupId/attendees/$attendeeId' | '/groups/$groupId/attendees/new' @@ -435,6 +446,7 @@ export interface FileRouteTypes { | '/student' | '/class/$sessionId/attendance' | '/groups/$groupId/analytics' + | '/groups/$groupId/edit' | '/groups/$groupId' | '/groups/$groupId/attendees/$attendeeId' | '/groups/$groupId/attendees/new' @@ -475,6 +487,7 @@ export interface FileRouteTypes { | '/_student/student/' | '/_authenticated/class/$sessionId/attendance' | '/_authenticated/groups/$groupId/analytics' + | '/_authenticated/groups/$groupId/edit' | '/_authenticated/groups/$groupId/' | '/_authenticated/groups/$groupId/attendees/$attendeeId' | '/_authenticated/groups/$groupId/attendees/new' @@ -751,6 +764,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport 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': { id: '/_authenticated/groups/$groupId/attendees/$attendeeId' path: '/groups/$groupId/attendees/$attendeeId' @@ -780,6 +800,7 @@ interface AuthenticatedRouteChildren { AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute + AuthenticatedGroupsGroupIdEditRoute: typeof AuthenticatedGroupsGroupIdEditRoute AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute AuthenticatedGroupsGroupIdAttendeesNewRoute: typeof AuthenticatedGroupsGroupIdAttendeesNewRoute @@ -799,6 +820,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = { AuthenticatedClassSessionIdAttendanceRoute, AuthenticatedGroupsGroupIdAnalyticsRoute: AuthenticatedGroupsGroupIdAnalyticsRoute, + AuthenticatedGroupsGroupIdEditRoute: AuthenticatedGroupsGroupIdEditRoute, AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute, AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute, diff --git a/apps/web/src/routes/_authenticated/groups/$groupId/edit.tsx b/apps/web/src/routes/_authenticated/groups/$groupId/edit.tsx new file mode 100644 index 0000000..f159db4 --- /dev/null +++ b/apps/web/src/routes/_authenticated/groups/$groupId/edit.tsx @@ -0,0 +1,9 @@ +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 + }, +}) diff --git a/apps/web/test/billing-copy.test.ts b/apps/web/test/billing-copy.test.ts index 24d1e45..5059f0f 100644 --- a/apps/web/test/billing-copy.test.ts +++ b/apps/web/test/billing-copy.test.ts @@ -39,6 +39,7 @@ describe('copy del plan', () => { { label: 'Hasta 15 alumnos activos', included: true }, { label: 'Cobros con Mercado Pago', 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) }) diff --git a/packages/shared/src/schemas/admin.ts b/packages/shared/src/schemas/admin.ts index 1c4fe48..b58c403 100644 --- a/packages/shared/src/schemas/admin.ts +++ b/packages/shared/src/schemas/admin.ts @@ -108,6 +108,7 @@ export const UpdatePlanLimitsInputSchema = z.strictObject({ maxAttendees: limitValueSchema, whatsappAutomations: z.boolean(), mpCharges: z.boolean(), + kidsGroups: z.boolean(), }); export type UpdatePlanLimitsInput = z.output; diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index df1dc18..81f47be 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -24,8 +24,11 @@ export const AttendeeDtoSchema = z.object({ fullName: z.string(), email: 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(), guardianPhone: z.string().nullable(), + guardianEmail: z.string().nullable(), notes: z.string().nullable(), notifyToken: z.string().nullable().optional(), createdAt: isoDateTimeSchema, @@ -76,6 +79,8 @@ export const AttendeeDetailDtoSchema = AttendeeDtoSchema.extend({ payment: AttendeePaymentSummarySchema.nullable(), /** The person's memberships in the teacher's other groups. */ 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; @@ -115,16 +120,35 @@ export const AttendeeListSchema = z.object({ }); export type AttendeeList = z.output; -export const CreateAttendeeSchema = z.object({ - firstName: z.string().trim().min(1, 'name.required'), - lastName: z.string().trim().optional().default(''), +/* The adult in charge of a kid (kids groups). Found by phone among the + teacher's people, so siblings share the same adult. */ +export const GuardianInputSchema = z.object({ + fullName: z.string().trim().min(1, 'guardian.nameRequired'), phone: z.string().trim().min(6, 'phone.invalid'), 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; + +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; export const CreateAttendeeResultSchema = z.discriminatedUnion('outcome', [ @@ -216,6 +240,10 @@ export const PersonSummarySchema = z.object({ email: z.string().nullable(), phone: z.string().nullable(), 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; diff --git a/packages/shared/src/schemas/billing.ts b/packages/shared/src/schemas/billing.ts index 3afe657..34acbf3 100644 --- a/packages/shared/src/schemas/billing.ts +++ b/packages/shared/src/schemas/billing.ts @@ -8,7 +8,7 @@ const isoDateTimeSchema = z.string().datetime(); export const planSchema = z.enum(['FREE', 'PRO']); export type Plan = z.output; -export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges']); +export const planFeatureSchema = z.enum(['whatsappAutomations', 'mpCharges', 'kidsGroups']); export type PlanFeature = z.output; export type PlanLimits = { @@ -18,14 +18,16 @@ export type PlanLimits = { maxAttendees: number | null; whatsappAutomations: 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 // 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`. export const PLAN_LIMITS: Record = { - FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false }, - PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true }, + FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false, kidsGroups: false }, + PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true, kidsGroups: true }, }; // Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY), @@ -74,6 +76,7 @@ export const PlanLimitsSchema = z.object({ maxAttendees: z.number().int().nullable(), whatsappAutomations: z.boolean(), mpCharges: z.boolean(), + kidsGroups: z.boolean(), }); /** What each plan allows and what Pro costs in each country, as configured now. */ diff --git a/packages/shared/src/schemas/enums.ts b/packages/shared/src/schemas/enums.ts index 2aa0a81..00f3772 100644 --- a/packages/shared/src/schemas/enums.ts +++ b/packages/shared/src/schemas/enums.ts @@ -14,4 +14,9 @@ export type WeekDay = z.output; // Billing frequency of a group. export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']); -export type BillingType = z.output; \ No newline at end of file +export type BillingType = z.output; + +// 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; diff --git a/packages/shared/src/schemas/groups.ts b/packages/shared/src/schemas/groups.ts index 4e8acc2..4473862 100644 --- a/packages/shared/src/schemas/groups.ts +++ b/packages/shared/src/schemas/groups.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { billingTypeSchema, weekdaySchema } from './enums.js'; +import { billingTypeSchema, groupAudienceSchema, weekdaySchema } from './enums.js'; import { timeZoneSchema } from './home.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; @@ -26,6 +26,7 @@ export const GroupDtoSchema = z.object({ // Weekly WhatsApp automations (payment reminder and re-engagement). autoPaymentReminders: z.boolean(), autoReengagement: z.boolean(), + audience: groupAudienceSchema, }); export type GroupDto = z.output; @@ -79,4 +80,4 @@ export type GroupList = z.output; export const CreateGroupResultSchema = z.object({ group: GroupDtoSchema, }); -export type CreateGroupResult = z.output; \ No newline at end of file +export type CreateGroupResult = z.output; diff --git a/packages/shared/src/schemas/onboarding.ts b/packages/shared/src/schemas/onboarding.ts index c414ca7..b5e5a4f 100644 --- a/packages/shared/src/schemas/onboarding.ts +++ b/packages/shared/src/schemas/onboarding.ts @@ -1,12 +1,12 @@ import { z } from 'zod'; import { planSchema, subscriptionStatusSchema } from './billing.js'; import { countryCodeSchema, DEFAULT_COUNTRY } from './country.js'; -import { billingTypeSchema, weekdaySchema } from './enums.js'; +import { billingTypeSchema, groupAudienceSchema, weekdaySchema } from './enums.js'; import { GroupDtoSchema } from './groups.js'; export { countryCodeSchema } from './country.js'; -export type { BillingType, WeekDay } from './enums.js'; -export { billingTypeSchema, weekdaySchema } from './enums.js'; +export type { BillingType, GroupAudience, WeekDay } from './enums.js'; +export { billingTypeSchema, groupAudienceSchema, weekdaySchema } from './enums.js'; // Step 4: create the teacher's first group. Linking Mercado Pago is step 2 and // is skippable, so nothing here may require a linked account. The country is @@ -37,9 +37,21 @@ export const CreateFirstGroupSchema = z.strictObject({ .min(1, 'group.dueDayRange') .max(28, 'group.dueDayRange'), country: countryCodeSchema.default(DEFAULT_COUNTRY), + // A KIDS group needs the `kidsGroups` plan feature. + audience: groupAudienceSchema.default('ADULTS'), }); export type CreateFirstGroup = z.output; +// "Editar grupo" (`PATCH /groups/:id`): the same fields as the group form, any +// subset. The country lives on the user, not on the group. Turning the group +// into KIDS needs the `kidsGroups` plan feature; going back to ADULTS is blocked +// while it has kids with no phone of their own. +export const UpdateGroupSchema = CreateFirstGroupSchema.omit({ country: true, audience: true }) + .extend({ audience: groupAudienceSchema }) + .partial() + .refine((value) => Object.keys(value).length > 0, 'update.empty'); +export type UpdateGroup = z.output; + export const OnboardingGroupDtoSchema = GroupDtoSchema.extend({ days: z.array(weekdaySchema).nullable(), time: z.string().nullable(),