feat(groups): kids groups with an adult in charge
- Add the `kidsGroups` plan feature (Pro) and `Group.audience` (ADULTS | KIDS); creating or switching a group to KIDS requires the feature, existing KIDS groups keep working after a downgrade. - Model the adult in charge as a Person linked through `person_guardians`; migrate the old guardian_name/guardian_phone columns and drop them. - Kids quick add: kid + guardian form, guardian lookup by phone to pick an existing kid or add a sibling; backend rejects KIDS adds without guardian. - Attendee page: "Adulto a cargo" section with siblings, editable via PATCH /groups/:gid/attendees/:aid/guardian. - Contact phone (WhatsApp jobs, attention, student access invite, students at risk, attendee actions) prefers the guardian's phone. - Edit group screen (PATCH /groups/:gid, owner only); switching back to ADULTS is blocked while kids have no phone of their own. - Hide bulk import in KIDS groups until it carries guardian data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<PlanFeature, string> = {
|
||||
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 },
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'personGuardian'>;
|
||||
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 })),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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<PrismaClient, 'group' | 'attendee' | 'person' | 'personGuardian'>;
|
||||
};
|
||||
|
||||
type UpdateGuardianCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
input: GuardianInput;
|
||||
};
|
||||
|
||||
/**
|
||||
* The adult in charge of a kid, from the kid's page. With an adult already
|
||||
* linked it edits that adult (a person of their own, so it shows on every
|
||||
* sibling); without one it links the adult with that phone, or a new one.
|
||||
*/
|
||||
export class UpdateAttendeeGuardian {
|
||||
constructor(private readonly deps: UpdateGuardianDeps = {}) {}
|
||||
|
||||
async execute(command: UpdateGuardianCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, input } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true, person: { select: { id: true, phone: true, ...guardianSelect } } },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const current = primaryGuardian(attendee.person);
|
||||
try {
|
||||
if (current) {
|
||||
await db.person.update({
|
||||
where: { id: current.id },
|
||||
data: {
|
||||
fullName: input.fullName.trim(),
|
||||
phone: normalizePhone(input.phone),
|
||||
email: input.email?.trim() || null,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const guardian = await findOrCreateGuardian(db, access.value.createdById, input);
|
||||
// The kid's own phone is not an adult in charge of themselves.
|
||||
if (guardian.id === attendee.personId) return err(personPhoneTakenProblem());
|
||||
await db.personGuardian.create({ data: { childId: attendee.personId, guardianId: guardian.id } });
|
||||
}
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.attendee.findUniqueOrThrow({
|
||||
where: { id: attendeeId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
}
|
||||
@@ -1,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 ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -58,6 +58,7 @@ export class PlanCatalog {
|
||||
maxAttendees: config.maxAttendees,
|
||||
whatsappAutomations: config.whatsappAutomations,
|
||||
mpCharges: config.mpCharges,
|
||||
kidsGroups: config.kidsGroups,
|
||||
};
|
||||
}
|
||||
for (const price of prices) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { type GroupRecord, toGroupDto } from '../../lib';
|
||||
|
||||
type CreateGroupDeps = {
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
||||
};
|
||||
|
||||
export class CreateGroup {
|
||||
@@ -25,10 +25,15 @@ export class CreateGroup {
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
20
apps/backend/src/modules/groups/features/update/route.ts
Normal file
20
apps/backend/src/modules/groups/features/update/route.ts
Normal file
@@ -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;
|
||||
66
apps/backend/src/modules/groups/features/update/use-case.ts
Normal file
66
apps/backend/src/modules/groups/features/update/use-case.ts
Normal file
@@ -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<PrismaClient, 'group' | 'attendee'>;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
/**
|
||||
* "Editar grupo": name, schedule, capacity, billing and who it is for. Only
|
||||
* the owner can. A lower capacity than the current members is allowed: it only
|
||||
* stops new additions.
|
||||
*
|
||||
* Who it is for: turning it into a kids group needs the `kidsGroups` plan
|
||||
* feature (a kids group that already exists keeps working after a downgrade);
|
||||
* going back to adults is blocked while a member has no phone of their own,
|
||||
* since without the adult in charge nobody could be reached.
|
||||
*/
|
||||
export class UpdateGroupUseCase {
|
||||
constructor(private readonly deps: UpdateGroupDeps = {}) {}
|
||||
|
||||
async execute(groupId: string, userId: string, input: UpdateGroup): Promise<Result<GroupDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const group = await db.group.findUnique({
|
||||
where: { id: groupId },
|
||||
select: { id: true, createdById: true, audience: true },
|
||||
});
|
||||
if (!group) return err(notFoundResourceProblem('Group', groupId));
|
||||
if (group.createdById !== userId) {
|
||||
return err(
|
||||
forbiddenProblem({
|
||||
detail: 'Solo quien creó el grupo puede editarlo.',
|
||||
code: 'group_owner_required',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (input.audience === 'KIDS' && group.audience !== 'KIDS') {
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(userId, 'kidsGroups');
|
||||
if (!allowed.ok) return allowed;
|
||||
}
|
||||
if (input.audience === 'ADULTS' && group.audience === 'KIDS') {
|
||||
const withoutPhone = await db.attendee.count({
|
||||
where: { groupId, status: { not: 'DROPPED' }, person: { phone: null } },
|
||||
});
|
||||
if (withoutPhone > 0) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Hay chicos sin teléfono propio: cargales uno antes de pasar el grupo a adultos.',
|
||||
code: 'group_has_kids_without_phone',
|
||||
params: { count: withoutPhone },
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await db.group.update({ where: { id: groupId }, data: input });
|
||||
return ok(toGroupDto(updated as GroupRecord));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
||||
import type { BillingType, GroupAudience, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
||||
|
||||
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -16,7 +16,7 @@ import { toOnboardingGroupDto } from '../../lib';
|
||||
type CreateFirstGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'user'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
||||
};
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
21
apps/backend/src/modules/people/lib/guardians.ts
Normal file
21
apps/backend/src/modules/people/lib/guardians.ts
Normal file
@@ -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<GuardianContact> & { phone: string | null } }[] };
|
||||
|
||||
export function primaryGuardian<T extends { phone: string | null }>(person: {
|
||||
guardians?: { guardian: T }[];
|
||||
}): T | null {
|
||||
return person.guardians?.[0]?.guardian ?? null;
|
||||
}
|
||||
@@ -1,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<PersonSummary | null> {
|
||||
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.',
|
||||
|
||||
@@ -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 } } } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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));
|
||||
|
||||
Reference in New Issue
Block a user