feat: cambiar a un miembro de grupo
- `POST /groups/:gid/attendees/:aid/move` mueve al mismo attendee a otro grupo del profesor: conserva historial, cuotas (siguen del grupo anterior) y acceso a la app de alumnos. Cancela las faltas avisadas y libera lo reservado en clases futuras del grupo anterior. - Cupo y teléfono duplicado se validan con `checkCanJoinGroup`, compartido con el paso desde la lista de espera. - Ficha del miembro: "Cambiar de grupo" abre un diálogo con el selector de grupo destino y navega a la ficha en el grupo nuevo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
|
||||
import { MoveAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { MoveAttendee } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new MoveAttendee();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
76
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
76
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
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 { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type MoveAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
type MoveAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* Moves a member to another group of the same teacher. It is the same attendee
|
||||
with another `groupId`: past attendance, fees (they stay owed to the old
|
||||
group) and the student app access go with them. Only what was booked for
|
||||
the old group's future classes is undone: absence notices, the EXCUSED rows
|
||||
they left and the released slots. */
|
||||
export class MoveAttendee {
|
||||
constructor(private readonly deps: MoveAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: MoveAttendeeCommand): 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 now = this.deps.now?.() ?? new Date();
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
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;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.phone);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
|
||||
await tx.absenceNotice.updateMany({
|
||||
where: { attendeeId, cancelledAt: null, ...futureOldClasses },
|
||||
data: { cancelledAt: now },
|
||||
});
|
||||
await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
|
||||
await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
|
||||
|
||||
const moved = await tx.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: { groupId: targetGroupId },
|
||||
});
|
||||
return ok(toAttendeeDto(moved as unknown as AttendeeRecord));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,14 @@ export async function findFirstPendingWaitlistEntry(
|
||||
return record as GroupWaitlistEntryRecord | null;
|
||||
}
|
||||
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
/* 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. */
|
||||
export async function checkCanJoinGroup(
|
||||
db: Pick<PrismaClient, 'attendee'>,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
phone: string | null,
|
||||
): Promise<Result<void, ProblemDetails>> {
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
where: { groupId: group.id, status: 'ACTIVE' },
|
||||
@@ -37,16 +40,31 @@ export async function promoteWaitlistEntryRecord(
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, phone: entry.phone },
|
||||
});
|
||||
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',
|
||||
}),
|
||||
);
|
||||
if (phone) {
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, phone },
|
||||
});
|
||||
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 ok(undefined);
|
||||
}
|
||||
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const canJoin = await checkCanJoinGroup(db, group, entry.phone);
|
||||
if (!canJoin.ok) {
|
||||
return canJoin;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
|
||||
@@ -5,6 +5,7 @@ import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
||||
import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
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 groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
@@ -37,6 +38,7 @@ routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
routes.route('/', moveAttendeeRoute);
|
||||
routes.route('/', studentAccessRoutes);
|
||||
|
||||
export default routes;
|
||||
|
||||
Reference in New Issue
Block a user