- 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>
231 lines
7.8 KiB
TypeScript
231 lines
7.8 KiB
TypeScript
import type { PrismaClient } from '@generated/prisma/client';
|
|
import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
|
|
import { err, ok } from '@gruperly/shared';
|
|
import {
|
|
alreadyWaitlistedProblem,
|
|
capacityReachedProblem,
|
|
noGroupAccessProblem,
|
|
notFoundResourceProblem,
|
|
} from '@/http/problem-builders';
|
|
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';
|
|
|
|
type CreateAttendeeDeps = {
|
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
|
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
|
};
|
|
|
|
type CreateAttendeeOptions = {
|
|
allowOverflow?: boolean;
|
|
};
|
|
|
|
export class CreateAttendeeUseCase {
|
|
constructor(private readonly deps: CreateAttendeeDeps = {}) {}
|
|
|
|
async execute(
|
|
groupId: string,
|
|
userId: string,
|
|
payload: CreateAttendee,
|
|
options: CreateAttendeeOptions = {},
|
|
): Promise<Result<CreateAttendeeResult, ProblemDetails>> {
|
|
const db = this.deps.db ?? prisma;
|
|
|
|
const group = await db.group.findUnique({
|
|
where: { id: groupId },
|
|
include: {
|
|
members: { where: { userId } },
|
|
},
|
|
});
|
|
|
|
if (!group) {
|
|
return err(notFoundResourceProblem('Group', groupId));
|
|
}
|
|
|
|
const isOwner = group.createdById === userId;
|
|
const isMember = group.members.length > 0;
|
|
if (!isOwner && !isMember) {
|
|
return err(noGroupAccessProblem());
|
|
}
|
|
|
|
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; 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, phone: true, ...guardianSelect },
|
|
});
|
|
if (!person) {
|
|
return err(notFoundResourceProblem('Person', payload.personId));
|
|
}
|
|
} else {
|
|
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 },
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// A former member (DROPPED) comes back on the same membership: history included.
|
|
const membership = person
|
|
? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
|
|
: null;
|
|
if (membership && membership.status !== 'DROPPED') {
|
|
return err(alreadyInGroupProblem());
|
|
}
|
|
|
|
const fullName = person?.fullName ?? 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({
|
|
where: { groupId, status: 'ACTIVE' },
|
|
});
|
|
|
|
if (currentCount >= group.capacity) {
|
|
if (isOwner && !options.allowOverflow) {
|
|
return err(capacityReachedProblem(group.capacity));
|
|
}
|
|
|
|
if (!isOwner) {
|
|
const existingWaitlistEntry = reachPhone
|
|
? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } })
|
|
: null;
|
|
|
|
if (existingWaitlistEntry) {
|
|
return err(alreadyWaitlistedProblem());
|
|
}
|
|
|
|
await db.groupWaitlistEntry.create({
|
|
data: {
|
|
groupId,
|
|
fullName,
|
|
phone: reachPhone ?? '',
|
|
email: payload.email?.trim() || null,
|
|
notes: payload.notes?.trim() || null,
|
|
},
|
|
});
|
|
|
|
return ok({
|
|
outcome: 'waitlisted',
|
|
message: `${fullName} fue agregado a la lista de espera del grupo.`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// The owner's plan pays for the attendee, whoever adds it. It counts people:
|
|
// someone already active in another group does not take a new slot.
|
|
const alreadyCounted = person
|
|
? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
|
|
: false;
|
|
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
|
group.createdById,
|
|
alreadyCounted ? 0 : 1,
|
|
);
|
|
if (!allowed.ok) {
|
|
return allowed;
|
|
}
|
|
|
|
try {
|
|
const attendee = membership
|
|
? await db.attendee.update({
|
|
where: { id: membership.id },
|
|
data: { status: 'ACTIVE' },
|
|
include: attendeeWithPerson,
|
|
})
|
|
: await db.attendee.create({
|
|
data: {
|
|
group: { connect: { id: groupId } },
|
|
person: person
|
|
? { connect: { id: person.id } }
|
|
: {
|
|
create: {
|
|
createdById: group.createdById,
|
|
fullName,
|
|
phone,
|
|
email: payload.email?.trim() || null,
|
|
notes: payload.notes?.trim() || null,
|
|
...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}),
|
|
},
|
|
},
|
|
},
|
|
include: attendeeWithPerson,
|
|
});
|
|
|
|
return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
|
|
} catch (error) {
|
|
// Lost a race: someone created that person or membership meanwhile.
|
|
if (isUniqueViolation(error)) {
|
|
return err(person ? alreadyInGroupProblem() : personExistsProblem());
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
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,
|
|
},
|
|
},
|
|
};
|
|
}
|