feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con teléfono único (índice parcial `people_owner_phone_key`). `Attendee` pasa a ser la membresía (`group_id` + `person_id`, único por grupo). - La cuenta de la app de alumnos se vincula a la persona (`student_account_people`): una sola cuenta ve todos sus grupos. - Migración unifica attendees del mismo profe y teléfono, y fusiona sus cuentas de alumno (conserva la usada más recientemente). - `POST /groups/:gid/attendees/:aid/add-to-group` y `GET /people/lookup` para detectar personas existentes al cargar; el alta responde `409 person_exists` y acepta `personId`. Bulk, lista de espera y preinscripciones vinculan solas. - El límite del plan cuenta personas con al menos un grupo activo. - Web: "Agregar a otro grupo", sección "También está en" en la ficha y aviso "Ya tenés a esta persona" en el alta individual. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { peopleRoutes } from './modules/people';
|
||||
import { studentPortalRoutes } from './modules/student-portal';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
import { whatsappRoutes } from './modules/whatsapp';
|
||||
@@ -68,6 +69,7 @@ api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
api.route('/people', peopleRoutes);
|
||||
api.route('/student-portal', studentPortalRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
|
||||
export const HISTORY_SESSIONS_LIMIT = 20;
|
||||
@@ -33,8 +34,8 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true, createdAt: true },
|
||||
});
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((row) => row && flattenPerson(row));
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
URGENT_MEMBERS_LIMIT,
|
||||
} from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
@@ -76,8 +77,8 @@ export class GetGroupsRiskOverview {
|
||||
const [attendees, sessions, attendances] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true, fullName: true, createdAt: true },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
db.classSession.findMany({
|
||||
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
} from '@gruperly/shared';
|
||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||
@@ -73,8 +74,8 @@ export async function findStudentsAtRisk(
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { groupId, status: 'ACTIVE' },
|
||||
select: { id: true, fullName: true, phone: true, createdAt: true },
|
||||
}),
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
||||
}).then((rows) => rows.map(flattenPerson)),
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId } },
|
||||
select: {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
|
||||
import { AddAttendeeToGroupSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { AddAttendeeToGroup } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new AddAttendeeToGroup();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type AddAttendeeToGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
};
|
||||
|
||||
type AddAttendeeToGroupCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* "Agregar a otro grupo": the same person gets a membership in another group of
|
||||
the teacher and keeps this one. It does not take a new student slot of the
|
||||
plan (the person is already counted) but the target's capacity applies. A
|
||||
former membership there (DROPPED) is reactivated, history included. */
|
||||
export class AddAttendeeToGroup {
|
||||
constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
|
||||
|
||||
async execute(command: AddAttendeeToGroupCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, targetGroupId } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
if (targetGroupId === groupId) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'El miembro ya pertenece a este grupo.',
|
||||
code: 'attendee_same_group',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) return targetResult;
|
||||
const target = targetResult.value;
|
||||
|
||||
try {
|
||||
return await unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const former = await tx.attendee.findFirst({
|
||||
where: { groupId: targetGroupId, personId: attendee.personId },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
|
||||
|
||||
const canJoin = await checkCanJoinGroup(tx, target, null);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const membership = former
|
||||
? await tx.attendee.update({
|
||||
where: { id: former.id },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: attendeeWithPerson,
|
||||
})
|
||||
: await tx.attendee.create({
|
||||
data: { groupId: targetGroupId, personId: attendee.personId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(membership));
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
// Two clicks at once: the unique (group, person) lets only one through.
|
||||
if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { phoneVariants } from '@/modules/people/lib/people';
|
||||
import { normalizePhone } from '../../lib/helpers';
|
||||
|
||||
type AddToGroupWaitlistDeps = {
|
||||
@@ -72,10 +73,7 @@ export class AddToGroupWaitlist {
|
||||
const existingAttendee = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
person: { phone: { in: phoneVariants(payload.phone) } },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type BulkCreateAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
@@ -43,23 +43,29 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
/* The teacher's people by phone: a row whose phone is already someone they
|
||||
have is added to this group as that person (linked), unless that person
|
||||
is already in the group (duplicate). */
|
||||
const people = await db.person.findMany({
|
||||
where: { createdById: group.createdById, phone: { not: null } },
|
||||
select: {
|
||||
id: true,
|
||||
phone: true,
|
||||
attendees: { select: { groupId: true, status: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const existingPhones = new Set<string>();
|
||||
for (const a of existingAttendees) {
|
||||
if (a.phone) {
|
||||
existingPhones.add(normalizePhone(a.phone));
|
||||
}
|
||||
const peopleByPhone = new Map<string, (typeof people)[number]>();
|
||||
for (const person of people) {
|
||||
if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
|
||||
}
|
||||
|
||||
let duplicatesCount = 0;
|
||||
let invalidCount = 0;
|
||||
const toCreateData: Array<{
|
||||
groupId: string;
|
||||
// Only people not active in any group take a new slot of the plan.
|
||||
let newlyCounted = 0;
|
||||
const seenPhones = new Set<string>();
|
||||
const toLink: string[] = [];
|
||||
const toCreate: Array<{
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
@@ -75,14 +81,21 @@ export class BulkCreateAttendeesUseCase {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existingPhones.has(phone)) {
|
||||
const existing = peopleByPhone.get(phone);
|
||||
if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
|
||||
duplicatesCount++;
|
||||
continue;
|
||||
}
|
||||
seenPhones.add(phone);
|
||||
|
||||
existingPhones.add(phone);
|
||||
toCreateData.push({
|
||||
groupId,
|
||||
if (existing) {
|
||||
toLink.push(existing.id);
|
||||
if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
|
||||
continue;
|
||||
}
|
||||
|
||||
newlyCounted++;
|
||||
toCreate.push({
|
||||
fullName: rawFullName,
|
||||
phone,
|
||||
email: item.email?.trim() || null,
|
||||
@@ -94,26 +107,44 @@ export class BulkCreateAttendeesUseCase {
|
||||
// reason about than a clear "your plan allows N".
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
toCreateData.length,
|
||||
newlyCounted,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const createdRecords: AttendeeRecord[] = [];
|
||||
for (const data of toCreateData) {
|
||||
const record = await db.attendee.create({ data });
|
||||
createdRecords.push(record as unknown as AttendeeRecord);
|
||||
for (const personId of toLink) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: { groupId, personId },
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const data of toCreate) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: {
|
||||
group: { connect: { id: groupId } },
|
||||
person: { create: { ...data, createdById: group.createdById } },
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const createdCount = createdRecords.length;
|
||||
const linkedCount = toLink.length;
|
||||
const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
|
||||
const message = duplicatesCount > 0
|
||||
? `${createdCount} alumnos agregados con éxito, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito.`;
|
||||
? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito${linkedNote}.`;
|
||||
|
||||
return ok({
|
||||
totalProcessed: payload.attendees.length,
|
||||
createdCount,
|
||||
linkedCount,
|
||||
duplicatesCount,
|
||||
invalidCount,
|
||||
message,
|
||||
|
||||
@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
alreadyWaitlistedProblem,
|
||||
capacityReachedProblem,
|
||||
conflictProblem,
|
||||
noGroupAccessProblem,
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import {
|
||||
alreadyInGroupProblem,
|
||||
findPersonByPhone,
|
||||
isUniqueViolation,
|
||||
personExistsProblem,
|
||||
} from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type CreateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
|
||||
const phone = normalizePhone(payload.phone);
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
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',
|
||||
}),
|
||||
);
|
||||
/* 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;
|
||||
if (payload.personId) {
|
||||
person = await db.person.findFirst({
|
||||
where: { id: payload.personId, createdById: group.createdById },
|
||||
select: { id: true, fullName: true },
|
||||
});
|
||||
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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
// 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 ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
@@ -108,25 +125,51 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
// The owner's plan pays for the attendee, whoever adds it.
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
|
||||
// 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;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
notes: payload.notes?.trim() || null,
|
||||
},
|
||||
});
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'created',
|
||||
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord),
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
import { toAttendeeListItemDto } from '../../lib/helpers';
|
||||
import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
|
||||
|
||||
type ListAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee'>;
|
||||
@@ -28,6 +28,7 @@ export class ListAttendees {
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
...attendeeWithPerson,
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
|
||||
@@ -4,8 +4,8 @@ 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 { toAttendeeDetailDto } from '../../lib/helpers';
|
||||
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
|
||||
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
@@ -31,6 +31,7 @@ export class GetAttendee {
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
include: {
|
||||
person: { select: { ...personContactSelect, ...personMembershipsSelect } },
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
@@ -46,7 +47,14 @@ export class GetAttendee {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
return ok(toAttendeeDetailDto(attendee));
|
||||
const { attendees: memberships, ...person } = attendee.person;
|
||||
return ok(
|
||||
toAttendeeDetailDto({
|
||||
...attendee,
|
||||
person,
|
||||
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builder
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type MoveAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
@@ -54,7 +54,7 @@ export class MoveAttendee {
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.phone);
|
||||
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
|
||||
@@ -68,8 +68,9 @@ export class MoveAttendee {
|
||||
const moved = await tx.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: { groupId: targetGroupId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(moved as unknown as AttendeeRecord));
|
||||
return ok(toAttendeeDto(moved));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,10 @@ export class RemoveAttendee {
|
||||
}
|
||||
const group = groupResult.value;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
@@ -49,6 +52,10 @@ export class RemoveAttendee {
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
|
||||
await tx.attendee.delete({ where: { id: attendeeId } });
|
||||
// Their last group: the person goes too (with their student app link).
|
||||
await tx.person.deleteMany({
|
||||
where: { id: attendee.personId, attendees: { none: {} } },
|
||||
});
|
||||
|
||||
if (!options.promoteFromWaitlist) {
|
||||
return ok({ removedAttendeeId: attendeeId, promoted: null });
|
||||
|
||||
@@ -4,10 +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 { toAttendeeDto } from '../../lib/helpers';
|
||||
import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type UpdateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
};
|
||||
|
||||
type UpdateAttendeeCommand = {
|
||||
@@ -26,12 +27,26 @@ export class UpdateAttendeeDetails {
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const updated = await db.attendee.update({
|
||||
// Contact data is the person's: the change shows in every group they are in.
|
||||
try {
|
||||
await db.person.update({
|
||||
where: { id: attendee.personId },
|
||||
data: normalizeEditableFields(input),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.attendee.findUniqueOrThrow({
|
||||
where: { id: attendeeId },
|
||||
data: normalizeEditableFields(input),
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
@@ -39,6 +54,11 @@ export class UpdateAttendeeDetails {
|
||||
|
||||
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
|
||||
return Object.fromEntries(
|
||||
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
|
||||
Object.entries(input).map(([key, value]) => {
|
||||
if (value === '') return [key, null];
|
||||
// Same normalization as the add form, so the phone keeps matching.
|
||||
if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
|
||||
return [key, value];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
/* Contact data of the person behind an attendee (shared by all their groups). */
|
||||
export const personContactSelect = {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
guardianName: true,
|
||||
guardianPhone: true,
|
||||
notes: true,
|
||||
} as const;
|
||||
|
||||
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
||||
export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
|
||||
|
||||
export type PersonContactRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
guardianName: string | null;
|
||||
guardianPhone: string | null;
|
||||
notes: string | null;
|
||||
};
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
personId: string;
|
||||
notifyToken?: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
person: PersonContactRecord;
|
||||
};
|
||||
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
@@ -25,18 +45,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
|
||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||
payments: AttendeeListItemRecord['payments'];
|
||||
otherGroups: AttendeeDetailDto['otherGroups'];
|
||||
};
|
||||
|
||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
email: record.email,
|
||||
phone: record.phone,
|
||||
guardianName: record.guardianName,
|
||||
guardianPhone: record.guardianPhone,
|
||||
notes: record.notes,
|
||||
personId: record.personId,
|
||||
fullName: record.person.fullName,
|
||||
email: record.person.email,
|
||||
phone: record.person.phone,
|
||||
guardianName: record.person.guardianName,
|
||||
guardianPhone: record.person.guardianPhone,
|
||||
notes: record.person.notes,
|
||||
notifyToken: record.notifyToken ?? null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
@@ -68,6 +90,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
otherGroups: record.otherGroups,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -91,3 +114,13 @@ export function normalizePhone(rawPhone: string): string {
|
||||
const digitsOnly = trimmed.replace(/\D/g, '');
|
||||
return hasPlus ? `+${digitsOnly}` : digitsOnly;
|
||||
}
|
||||
|
||||
/* For queries that select a few person fields next to the attendee's: turns
|
||||
`{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
|
||||
flat rows stays as it was. */
|
||||
export function flattenPerson<TRow extends { person: object }>(
|
||||
row: TRow,
|
||||
): Omit<TRow, 'person'> & TRow['person'] {
|
||||
const { person, ...rest } = row;
|
||||
return { ...rest, ...person };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import type {
|
||||
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
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 { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||
|
||||
type GetAttentionOverviewDeps = {
|
||||
@@ -82,9 +84,14 @@ export class GetAttentionOverview {
|
||||
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
|
||||
select: {
|
||||
id: true,
|
||||
groupId: true,
|
||||
createdAt: true,
|
||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
// Past classes only, most recent first: `toMemberAttendance` keeps the
|
||||
// last 20 per attendee, more than the 6-class window needs.
|
||||
db.classSession.findMany({
|
||||
@@ -154,7 +161,7 @@ export class GetAttentionOverview {
|
||||
firma: row.signature,
|
||||
}));
|
||||
|
||||
const phone = attendee.phone ?? attendee.guardianPhone;
|
||||
const phone = contactPhone(attendee);
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
|
||||
@@ -86,7 +86,7 @@ export type Entitlements = PlanResolution & {
|
||||
};
|
||||
|
||||
type PlanGuardDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'person'>;
|
||||
enforced?: boolean;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
@@ -116,7 +116,10 @@ export class PlanGuard {
|
||||
select: { status: true, authorizedAt: true, paidThrough: true },
|
||||
}),
|
||||
db.group.count({ where: { createdById: ownerId } }),
|
||||
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
|
||||
// People, not memberships: someone in three groups is one student.
|
||||
db.person.count({
|
||||
where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
||||
|
||||
@@ -32,6 +32,7 @@ export class GetAbsenceDetails {
|
||||
where: { notifyToken: query.token },
|
||||
include: {
|
||||
group: { select: { id: true, name: true, days: true, time: true } },
|
||||
person: { select: { fullName: true } },
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
@@ -46,7 +47,7 @@ export class GetAbsenceDetails {
|
||||
if (candidates.length === 0) {
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
fullName: attendee.person.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: [],
|
||||
});
|
||||
@@ -75,7 +76,7 @@ export class GetAbsenceDetails {
|
||||
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
fullName: attendee.person.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: sessions.map((session) => {
|
||||
const attendanceStatus = attendanceBySession.get(session.id) ?? null;
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
type ClassesDb,
|
||||
@@ -60,8 +61,9 @@ export class GetSessionStudents {
|
||||
const [attendees, payments, attendances, releases] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
orderBy: { fullName: 'asc' },
|
||||
}),
|
||||
orderBy: { person: { fullName: 'asc' } },
|
||||
include: { person: { select: { fullName: true } } },
|
||||
}).then((rows) => rows.map(flattenPerson)),
|
||||
db.payment.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
select: { attendeeId: true, status: true, dueDate: true },
|
||||
|
||||
@@ -8,6 +8,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { countsAsNewStudent } from '@/modules/people/lib/people';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -17,7 +18,7 @@ import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote'
|
||||
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration' | 'person'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
@@ -53,7 +54,8 @@ export class ApproveGroupPreRegistration {
|
||||
);
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { countsAsNewStudent } from '@/modules/people/lib/people';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -11,7 +12,7 @@ import {
|
||||
import { promoteWaitlistEntryRecord } from '../../lib/promote';
|
||||
|
||||
type PromoteGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
@@ -51,7 +52,8 @@ export class PromoteGroupWaitlistEntry {
|
||||
targetGroup = targetResult.value;
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders';
|
||||
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { capacityReachedProblem } from '@/http/problem-builders';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people';
|
||||
import { type GroupWaitlistEntryRecord } from './helpers';
|
||||
|
||||
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>;
|
||||
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
|
||||
type PromoteGroup = {
|
||||
id: string;
|
||||
capacity: number | null;
|
||||
createdById: string;
|
||||
};
|
||||
|
||||
export async function findFirstPendingWaitlistEntry(
|
||||
@@ -23,13 +25,13 @@ export async function findFirstPendingWaitlistEntry(
|
||||
return record as GroupWaitlistEntryRecord | null;
|
||||
}
|
||||
|
||||
/* Whether someone can join `group`: free capacity (ACTIVE members) and no
|
||||
member there with the same phone. Shared by the waitlist promotion and the
|
||||
member move between groups. */
|
||||
/* Whether someone can join `group`: free capacity (ACTIVE members) and the
|
||||
person (when there already is one) not being a member there yet. Shared by
|
||||
the waitlist promotion, the member move and "Agregar a otro grupo". */
|
||||
export async function checkCanJoinGroup(
|
||||
db: Pick<PrismaClient, 'attendee'>,
|
||||
group: PromoteGroup,
|
||||
phone: string | null,
|
||||
group: Pick<PromoteGroup, 'id' | 'capacity'>,
|
||||
personId: string | null,
|
||||
): Promise<Result<void, ProblemDetails>> {
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
@@ -40,44 +42,44 @@ export async function checkCanJoinGroup(
|
||||
}
|
||||
}
|
||||
|
||||
if (phone) {
|
||||
if (personId) {
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, phone },
|
||||
where: { groupId: group.id, personId },
|
||||
select: { id: true },
|
||||
});
|
||||
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',
|
||||
}),
|
||||
);
|
||||
return err(alreadyInGroupProblem());
|
||||
}
|
||||
}
|
||||
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
/* The entry has its own contact data; if its phone is already one of the
|
||||
teacher's people, the new membership goes to that person. */
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const canJoin = await checkCanJoinGroup(db, group, entry.phone);
|
||||
const person = await findOrCreatePerson(db, group.createdById, {
|
||||
fullName: entry.fullName,
|
||||
phone: entry.phone,
|
||||
email: entry.email,
|
||||
notes: entry.notes,
|
||||
});
|
||||
|
||||
const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id);
|
||||
if (!canJoin.ok) {
|
||||
return canJoin;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName: entry.fullName,
|
||||
phone: entry.phone,
|
||||
email: entry.email,
|
||||
notes: entry.notes,
|
||||
},
|
||||
data: { groupId: group.id, personId: person.id },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
|
||||
return ok(toAttendeeDto(attendee as unknown as AttendeeRecord));
|
||||
return ok(toAttendeeDto(attendee));
|
||||
}
|
||||
|
||||
export type PromoteFirstResult = {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Hono } from 'hono';
|
||||
import analyticsRoutes from '../analytics/routes';
|
||||
import addAttendeeToGroupRoute from '../attendees/features/add-to-group/route';
|
||||
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
|
||||
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
||||
import createAttendeeRoute from '../attendees/features/create/route';
|
||||
@@ -39,6 +40,7 @@ routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
routes.route('/', moveAttendeeRoute);
|
||||
routes.route('/', addAttendeeToGroupRoute);
|
||||
routes.route('/', studentAccessRoutes);
|
||||
|
||||
export default routes;
|
||||
|
||||
@@ -74,7 +74,7 @@ export class GetHomeSummary {
|
||||
take: UPCOMING_PAYMENTS_LIMIT,
|
||||
include: {
|
||||
group: { select: { name: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
@@ -96,7 +96,7 @@ export class GetHomeSummary {
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
status: payment.status,
|
||||
groupName: payment.group.name,
|
||||
attendeeName: payment.attendee.fullName,
|
||||
attendeeName: payment.attendee.person.fullName,
|
||||
})),
|
||||
pendingPreRegistrations: groups
|
||||
.filter((group) => group._count.preRegistrations > 0)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
import { phoneVariants } from '@/modules/people/lib/people';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||
@@ -36,10 +37,7 @@ export class JoinViaInvite {
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
person: { phone: { in: phoneVariants(payload.phone) } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -58,10 +56,7 @@ export class JoinViaInvite {
|
||||
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
phone: { in: phoneVariants(payload.phone) },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ export class CreatePaymentBatch {
|
||||
status: 'ACTIVE',
|
||||
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
|
||||
},
|
||||
include: { person: { select: { fullName: true } } },
|
||||
});
|
||||
if (attendees.length === 0) {
|
||||
return err(noAttendeesToBillProblem());
|
||||
@@ -150,7 +151,7 @@ export class CreatePaymentBatch {
|
||||
items.push({
|
||||
paymentId: payment.id,
|
||||
attendeeId: attendee.id,
|
||||
attendeeName: attendee.fullName,
|
||||
attendeeName: attendee.person.fullName,
|
||||
amount: unitPrice,
|
||||
currency,
|
||||
checkoutUrl: link?.initPoint ?? null,
|
||||
|
||||
@@ -36,7 +36,7 @@ export class ListPayments {
|
||||
where,
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
},
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
|
||||
@@ -35,7 +35,7 @@ export class RenewPaymentLink {
|
||||
const payment = await db.payment.findUnique({
|
||||
where: { id: paymentId },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: {
|
||||
select: {
|
||||
name: true,
|
||||
@@ -106,7 +106,7 @@ export class RenewPaymentLink {
|
||||
where: { id: payment.id },
|
||||
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -31,7 +31,7 @@ const reportSelect = {
|
||||
receiptMime: true,
|
||||
receiptName: true,
|
||||
receiptSize: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
attendee: { select: { id: true, person: { select: { fullName: true } } } },
|
||||
group: { select: { id: true, name: true } },
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
|
||||
} satisfies Prisma.ReportedPaymentSelect;
|
||||
@@ -202,7 +202,7 @@ export class ReportedPayments {
|
||||
return {
|
||||
id: row.id,
|
||||
status: STATUS[row.status],
|
||||
attendee: row.attendee,
|
||||
attendee: { id: row.attendee.id, fullName: row.attendee.person.fullName },
|
||||
group: row.group,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
totalAmount: row.totalAmount.toNumber(),
|
||||
|
||||
@@ -18,7 +18,7 @@ export type PaymentRecord = {
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
group: { name: string; price: unknown };
|
||||
attendee: { fullName: string };
|
||||
attendee: { person: { fullName: string } };
|
||||
};
|
||||
|
||||
export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
@@ -27,7 +27,7 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
groupId: record.groupId,
|
||||
groupName: record.group.name,
|
||||
attendeeId: record.attendeeId,
|
||||
attendeeName: record.attendee.fullName,
|
||||
attendeeName: record.attendee.person.fullName,
|
||||
amount: Number(record.amount.toString()),
|
||||
currency: record.currency,
|
||||
status: record.status,
|
||||
|
||||
18
apps/backend/src/modules/people/features/lookup/route.ts
Normal file
18
apps/backend/src/modules/people/features/lookup/route.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { PersonLookupQuery } from '@gruperly/shared';
|
||||
import { PersonLookupQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { LookupPerson } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/lookup', validate.query(PersonLookupQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new LookupPerson().execute(c.req.valid('query') as PersonLookupQuery, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
24
apps/backend/src/modules/people/features/lookup/use-case.ts
Normal file
24
apps/backend/src/modules/people/features/lookup/use-case.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { PersonLookupQuery, PersonSummary, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { findPersonSummaryByPhone } from '../../lib/people';
|
||||
|
||||
type LookupPersonDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'person'>;
|
||||
};
|
||||
|
||||
/* While the teacher types a phone in the add form: is it someone they already
|
||||
have? `null` when not. */
|
||||
export class LookupPerson {
|
||||
constructor(private readonly deps: LookupPersonDeps = {}) {}
|
||||
|
||||
async execute(query: PersonLookupQuery, userId: string): Promise<Result<PersonSummary | null, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, query.groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
return ok(await findPersonSummaryByPhone(db, access.value.createdById, query.phone));
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/people/index.ts
Normal file
1
apps/backend/src/modules/people/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as peopleRoutes } from './routes';
|
||||
142
apps/backend/src/modules/people/lib/people.ts
Normal file
142
apps/backend/src/modules/people/lib/people.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
||||
import { conflictProblem } from '@/http/problem-builders';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
/* 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
|
||||
teacher (partial index `people_owner_phone_key`), so it is how a new row is
|
||||
recognized as someone the teacher already has. */
|
||||
|
||||
export type PeopleDb = Pick<PrismaClient, 'person'>;
|
||||
|
||||
/* Phones are stored normalized, but older rows may keep what was typed. */
|
||||
export function phoneVariants(rawPhone: string): string[] {
|
||||
const normalized = normalizePhone(rawPhone);
|
||||
const trimmed = rawPhone.trim();
|
||||
return normalized === trimmed ? [normalized] : [normalized, trimmed];
|
||||
}
|
||||
|
||||
export const personMembershipsSelect = {
|
||||
attendees: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { id: true, groupId: true, status: true, group: { select: { name: true } } },
|
||||
},
|
||||
} as const;
|
||||
|
||||
type MembershipRow = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
status: PersonMembership['status'];
|
||||
group: { name: string };
|
||||
};
|
||||
|
||||
export function toMemberships(rows: MembershipRow[]): PersonMembership[] {
|
||||
return rows.map((row) => ({
|
||||
attendeeId: row.id,
|
||||
groupId: row.groupId,
|
||||
groupName: row.group.name,
|
||||
status: row.status,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function findPersonByPhone(db: PeopleDb, ownerId: string, rawPhone: string) {
|
||||
return db.person.findFirst({
|
||||
where: { createdById: ownerId, phone: { in: phoneVariants(rawPhone) } },
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
...personMembershipsSelect,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function findPersonSummaryByPhone(
|
||||
db: PeopleDb,
|
||||
ownerId: string,
|
||||
rawPhone: string,
|
||||
): Promise<PersonSummary | null> {
|
||||
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
||||
if (!person) return null;
|
||||
return {
|
||||
id: person.id,
|
||||
fullName: person.fullName,
|
||||
email: person.email,
|
||||
phone: person.phone,
|
||||
groups: toMemberships(person.attendees),
|
||||
};
|
||||
}
|
||||
|
||||
export type NewPersonData = {
|
||||
fullName: string;
|
||||
phone: string | null;
|
||||
email?: string | null;
|
||||
notes?: string | null;
|
||||
};
|
||||
|
||||
/* Waitlist promotion, pre-registration approval and bulk import: the row has
|
||||
its own contact data, and if that phone is already one of the teacher's
|
||||
people the membership goes to that person (their data wins). */
|
||||
export async function findOrCreatePerson(
|
||||
db: PeopleDb,
|
||||
ownerId: string,
|
||||
data: NewPersonData,
|
||||
): Promise<{ id: string; created: boolean }> {
|
||||
if (data.phone) {
|
||||
const existing = await findPersonByPhone(db, ownerId, data.phone);
|
||||
if (existing) return { id: existing.id, created: false };
|
||||
}
|
||||
const person = await db.person.create({
|
||||
data: {
|
||||
createdById: ownerId,
|
||||
fullName: data.fullName,
|
||||
phone: data.phone,
|
||||
email: data.email ?? null,
|
||||
notes: data.notes ?? null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return { id: person.id, created: true };
|
||||
}
|
||||
|
||||
/* Whether adding someone with this phone takes a new student slot of the plan:
|
||||
no when they are already an active member of another group. */
|
||||
export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone: string | null): Promise<boolean> {
|
||||
if (!rawPhone) return true;
|
||||
const person = await findPersonByPhone(db, ownerId, 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;
|
||||
}
|
||||
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
|
||||
}
|
||||
|
||||
export function alreadyInGroupProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Esta persona ya es miembro de este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
});
|
||||
}
|
||||
|
||||
/* The phone belongs to someone the teacher already has: the web offers to add
|
||||
that person (`personId`) instead of creating a duplicate. */
|
||||
export function personExistsProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya tenés registrada a una persona con este número de teléfono.',
|
||||
code: 'person_exists',
|
||||
});
|
||||
}
|
||||
|
||||
export function personPhoneTakenProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
||||
code: 'person_phone_taken',
|
||||
});
|
||||
}
|
||||
8
apps/backend/src/modules/people/routes.ts
Normal file
8
apps/backend/src/modules/people/routes.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Hono } from 'hono';
|
||||
import lookupRoute from './features/lookup/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', lookupRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -7,7 +7,7 @@ import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type GetStudentAccessDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
@@ -23,9 +23,9 @@ export class GetStudentAccess {
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true } });
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date()));
|
||||
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,12 @@ 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 { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type InviteStudentDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
now?: Date;
|
||||
};
|
||||
@@ -36,9 +37,8 @@ export class InviteStudent {
|
||||
where: { id: attendeeId, groupId },
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
phone: true,
|
||||
guardianPhone: true,
|
||||
personId: true,
|
||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||
group: { select: { owner: { select: { country: true } } } },
|
||||
},
|
||||
});
|
||||
@@ -49,8 +49,9 @@ export class InviteStudent {
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
|
||||
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||
const link = await tx.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
// One account per person: inviting from any of their groups reuses it.
|
||||
const link = await tx.studentAccountPerson.findFirst({
|
||||
where: { personId: attendee.personId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { accountId: true },
|
||||
});
|
||||
@@ -58,7 +59,11 @@ export class InviteStudent {
|
||||
link?.accountId
|
||||
?? (
|
||||
await tx.studentAccount.create({
|
||||
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
|
||||
data: {
|
||||
name: attendee.person.fullName,
|
||||
createdById: userId,
|
||||
people: { create: { personId: attendee.personId } },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
).id;
|
||||
@@ -90,8 +95,8 @@ export class InviteStudent {
|
||||
return ok({
|
||||
url: studentLinkUrl(token),
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
|
||||
access: await computeStudentAccess(db, attendeeId, now),
|
||||
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
||||
access: await computeStudentAccess(db, attendee.personId, now),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class ListGroupAbsenceNotices {
|
||||
reason: true,
|
||||
message: true,
|
||||
createdAt: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
attendee: { select: { id: true, person: { select: { fullName: true } } } },
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
});
|
||||
@@ -47,7 +47,7 @@ export class ListGroupAbsenceNotices {
|
||||
return ok({
|
||||
data: notices.map((notice) => ({
|
||||
id: notice.id,
|
||||
attendee: notice.attendee,
|
||||
attendee: { id: notice.attendee.id, fullName: notice.attendee.person.fullName },
|
||||
startsAt: notice.classSession.startsAt.toISOString(),
|
||||
reason: notice.reason ? REASON[notice.reason] : null,
|
||||
message: notice.message,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { StudentAccessDto } from '@gruperly/shared';
|
||||
|
||||
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>;
|
||||
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountPerson'>;
|
||||
|
||||
/* Passive state for the attendee's card: active (a live session) > invited
|
||||
(a pending invitation) > expired (invited before, nothing alive) > not invited. */
|
||||
(a pending invitation) > expired (invited before, nothing alive) > not invited.
|
||||
It is the person's access, so every group of theirs shows the same state. */
|
||||
export async function computeStudentAccess(
|
||||
db: StudentAccessStatusDb,
|
||||
attendeeId: string,
|
||||
personId: string,
|
||||
now: Date,
|
||||
): Promise<StudentAccessDto> {
|
||||
const link = await db.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
const link = await db.studentAccountPerson.findFirst({
|
||||
where: { personId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
account: {
|
||||
|
||||
@@ -127,7 +127,7 @@ export class CancelStudentAbsence {
|
||||
where: {
|
||||
id: noticeId,
|
||||
cancelledAt: null,
|
||||
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
|
||||
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||
});
|
||||
|
||||
@@ -32,10 +32,20 @@ export class GetStudentLinkInfo {
|
||||
account: {
|
||||
select: {
|
||||
name: true,
|
||||
attendees: {
|
||||
people: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 1,
|
||||
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
|
||||
select: {
|
||||
person: {
|
||||
select: {
|
||||
attendees: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 1,
|
||||
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -52,7 +62,7 @@ export class GetStudentLinkInfo {
|
||||
return ok({ status: 'invalid' });
|
||||
}
|
||||
|
||||
const group = row.account.attendees[0]?.attendee.group ?? null;
|
||||
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
|
||||
return ok({
|
||||
status: 'valid',
|
||||
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||
|
||||
@@ -20,15 +20,21 @@ export class GetStudentMe {
|
||||
pendingRecoveryEmail: true,
|
||||
welcomedAt: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
attendees: {
|
||||
where: { attendee: { status: { not: 'DROPPED' } } },
|
||||
// Linked people, and every group each of them is in.
|
||||
people: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
attendee: {
|
||||
person: {
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||
attendees: {
|
||||
where: { status: { not: 'DROPPED' } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -46,13 +52,15 @@ export class GetStudentMe {
|
||||
hasPasskey: account._count.passkeys > 0,
|
||||
welcomed: account.welcomedAt !== null,
|
||||
},
|
||||
students: account.attendees.map(({ attendee }) => ({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
groupId: attendee.group.id,
|
||||
groupName: attendee.group.name,
|
||||
teacherName: attendee.group.owner.name,
|
||||
})),
|
||||
students: account.people.flatMap(({ person }) =>
|
||||
person.attendees.map((attendee) => ({
|
||||
attendeeId: attendee.id,
|
||||
fullName: person.fullName,
|
||||
groupId: attendee.group.id,
|
||||
groupName: attendee.group.name,
|
||||
teacherName: attendee.group.owner.name,
|
||||
})),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,21 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
|
||||
export type StudentAccessDb = {
|
||||
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
|
||||
};
|
||||
|
||||
/* The authorization rule of every student endpoint: only the attendees linked
|
||||
to the session's account. Anything else is a 404 (we don't confirm ids). */
|
||||
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
|
||||
const links = await db.studentAccountAttendee.findMany({
|
||||
// A DROPPED attendee loses access; a PAUSED one keeps it.
|
||||
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
|
||||
select: { attendeeId: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return links.map((link) => link.attendeeId);
|
||||
}
|
||||
|
||||
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||
|
||||
/* One attendee of the session, with what the student screens need from the
|
||||
group. null for an attendee not linked to the account (or DROPPED): routes
|
||||
answer 404, the same as for an id that doesn't exist. */
|
||||
/* The authorization rule of every student endpoint: an attendee (membership)
|
||||
of a person linked to the session's account, with what the student screens
|
||||
need from the group. The account is linked to the person, so every group
|
||||
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
||||
access): routes answer 404, the same as for an id that doesn't exist. */
|
||||
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||
return db.attendee.findFirst({
|
||||
where: {
|
||||
id: attendeeId,
|
||||
status: { not: 'DROPPED' },
|
||||
studentAccounts: { some: { accountId } },
|
||||
person: { studentAccounts: { some: { accountId } } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
groupId: true,
|
||||
group: {
|
||||
select: {
|
||||
|
||||
@@ -1,6 +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 {
|
||||
addTotals,
|
||||
type DispatchItem,
|
||||
@@ -69,7 +70,9 @@ export class SendPaymentReminders {
|
||||
currency: true,
|
||||
dueDate: true,
|
||||
checkoutUrl: true,
|
||||
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
|
||||
attendee: {
|
||||
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
|
||||
},
|
||||
},
|
||||
orderBy: { dueDate: 'asc' },
|
||||
});
|
||||
@@ -82,10 +85,10 @@ export class SendPaymentReminders {
|
||||
groupId: group.id,
|
||||
attendeeId: payment.attendee.id,
|
||||
paymentId: payment.id,
|
||||
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
|
||||
rawPhone: contactPhone(payment.attendee.person),
|
||||
message: {
|
||||
kind: 'PAYMENT_REMINDER',
|
||||
studentName: payment.attendee.fullName,
|
||||
studentName: payment.attendee.person.fullName,
|
||||
groupName: group.name,
|
||||
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
|
||||
dueDate: formatDueDate(payment.dueDate, country),
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
findStudentsAtRisk,
|
||||
type StudentsAtRiskDb,
|
||||
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import {
|
||||
addTotals,
|
||||
type DispatchItem,
|
||||
@@ -69,11 +70,11 @@ export class SendReengagementMessages {
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, phone: true, guardianPhone: true },
|
||||
select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
|
||||
}),
|
||||
]);
|
||||
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
||||
const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone]));
|
||||
const phones = new Map(contacts.map((row) => [row.id, contactPhone(row.person)]));
|
||||
|
||||
for (const student of atRisk) {
|
||||
if (coolingDown.has(student.attendeeId)) continue;
|
||||
|
||||
Reference in New Issue
Block a user