Initial attendee management
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
};
|
||||
|
||||
export type JoinViaInviteResult = {
|
||||
attendee: AttendeeDto;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export class JoinViaInvite {
|
||||
constructor(private readonly deps: JoinViaInviteDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
token: string,
|
||||
payload: JoinGroupViaInvite,
|
||||
): Promise<Result<JoinViaInviteResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const group = await db.group.findUnique({
|
||||
where: { inviteToken: token },
|
||||
});
|
||||
|
||||
if (!group) {
|
||||
return err(notFoundResourceProblem('Invitación', token));
|
||||
}
|
||||
|
||||
const phone = normalizePhone(payload.phone);
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
const created = await db.attendee.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
||||
message: 'Inscripción realizada con éxito',
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user