development #14

Merged
jselesan merged 102 commits from development into main 2026-11-07 13:21:43 +00:00
792 changed files with 66639 additions and 1203 deletions
Showing only changes of commit fc12ec3ae0 - Show all commits

View File

@@ -1,19 +1,26 @@
import { type PromoteGroupWaitlistEntry as PromoteBody, PromoteGroupWaitlistEntrySchema } from '@gruperly/shared';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { PromoteGroupWaitlistEntry } from './use-case'; import { PromoteGroupWaitlistEntry } from './use-case';
const route = new Hono(); const route = new Hono();
route.post('/:groupId/waitlist/:entryId/promote', async (c) => { route.post(
const user = c.get('user'); '/:groupId/waitlist/:entryId/promote',
if (!user) { validate.json(PromoteGroupWaitlistEntrySchema),
return problemJson(c, unauthorizedProblem(c.req.path)); async (c) => {
} const user = c.get('user');
const groupId = c.req.param('groupId'); if (!user) {
const entryId = c.req.param('entryId'); return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new PromoteGroupWaitlistEntry(); }
const result = await useCase.execute(groupId, entryId, user.id); const groupId = c.req.param('groupId');
return resultJson(c, result); const entryId = c.req.param('entryId');
}); const body = c.req.valid('json') as PromoteBody;
const useCase = new PromoteGroupWaitlistEntry();
const result = await useCase.execute(groupId, entryId, user.id, body.targetGroupId);
return resultJson(c, result);
},
);
export default route; export default route;

View File

@@ -23,6 +23,7 @@ export class PromoteGroupWaitlistEntry {
groupId: string, groupId: string,
entryId: string, entryId: string,
userId: string, userId: string,
targetGroupId?: string,
): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> { ): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
@@ -39,6 +40,17 @@ export class PromoteGroupWaitlistEntry {
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
} }
// The entry leaves the waitlist of its own group but can land in another
// group of the same teacher (capacity and duplicates are checked there).
let targetGroup = groupResult.value;
if (targetGroupId && targetGroupId !== groupId) {
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) {
return targetResult;
}
targetGroup = targetResult.value;
}
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId); const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
@@ -48,7 +60,7 @@ export class PromoteGroupWaitlistEntry {
async (tx: Prisma.TransactionClient) => { async (tx: Prisma.TransactionClient) => {
const promoteResult = await promoteWaitlistEntryRecord( const promoteResult = await promoteWaitlistEntryRecord(
tx, tx,
groupResult.value, targetGroup,
entry as unknown as GroupWaitlistEntryRecord, entry as unknown as GroupWaitlistEntryRecord,
); );
if (!promoteResult.ok) { if (!promoteResult.ok) {

View File

@@ -204,6 +204,71 @@ describe('group waitlist management', () => {
expect(res.status).toBe(403); expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled(); expect(prisma.attendee.create).not.toHaveBeenCalled();
}); });
const promoteTo = (targetGroupId: string) =>
makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
it('places the entry in another group of the teacher and removes it from the origin waitlist', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', name: 'Taller de Cerámica' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(200);
expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } });
expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-2', fullName: 'Martín Gómez' }),
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', createdById: 'other-user' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
it('returns 404 when the target group does not exist', async () => {
prisma.group.findUnique.mockResolvedValueOnce(mockGroup as never).mockResolvedValueOnce(null);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-missing');
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', capacity: 5 } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
const res = await promoteTo('group-2');
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('group_capacity_reached');
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
}); });
describe('DELETE /groups/:groupId/waitlist/:entryId', () => { describe('DELETE /groups/:groupId/waitlist/:entryId', () => {

View File

@@ -6,6 +6,7 @@ import type {
UpdateGroupAutomations, UpdateGroupAutomations,
AttendeeListItem, AttendeeListItem,
GroupDto, GroupDto,
GroupListItem,
GroupPreRegistrationDto, GroupPreRegistrationDto,
GroupWaitlistEntryDto, GroupWaitlistEntryDto,
GroupRiskLevel, GroupRiskLevel,
@@ -17,6 +18,7 @@ import {
approveGroupPreRegistration, approveGroupPreRegistration,
getGroup, getGroup,
getGroupAttendees, getGroupAttendees,
getGroups,
getGroupPreRegistrations, getGroupPreRegistrations,
getGroupsRiskOverview, getGroupsRiskOverview,
getGroupWaitlist, getGroupWaitlist,
@@ -75,7 +77,10 @@ type GroupDetailContextValue = {
isSubmittingApproval: boolean isSubmittingApproval: boolean
isSubmittingRejection: boolean isSubmittingRejection: boolean
isRegeneratingInvite: boolean isRegeneratingInvite: boolean
promoteEntry: (entry: GroupWaitlistEntryDto) => void /** Grupos del profe: destino posible al pasar a alguien de la lista de espera. */
groups: GroupListItem[]
/** `targetGroupId` es este grupo por defecto, u otro grupo del profe. */
promoteEntry: (entry: GroupWaitlistEntryDto, targetGroupId: string) => void
removeEntry: (entry: GroupWaitlistEntryDto) => void removeEntry: (entry: GroupWaitlistEntryDto) => void
approvePreRegistration: (entry: GroupPreRegistrationDto) => void approvePreRegistration: (entry: GroupPreRegistrationDto) => void
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
@@ -157,6 +162,8 @@ export function GroupDetailProvider({
enabled: Boolean(groupId), enabled: Boolean(groupId),
}) })
const groupsQuery = useQuery({ queryKey: ['groups'], queryFn: getGroups })
const group = groupQuery.data const group = groupQuery.data
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data]) const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
@@ -208,10 +215,19 @@ export function GroupDetailProvider({
}) })
const promoteWaitlistMutation = useMutation({ const promoteWaitlistMutation = useMutation({
mutationFn: (entryId: string) => promoteGroupWaitlistEntry(groupId, entryId), mutationFn: ({ entryId, targetGroupId }: { entryId: string; targetGroupId: string }) =>
onSuccess: (result) => { promoteGroupWaitlistEntry(groupId, entryId, targetGroupId),
toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`) onSuccess: (result, { targetGroupId }) => {
if (targetGroupId === groupId) {
toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`)
} else {
const targetName = groupsQuery.data?.data.find((g) => g.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${result.attendee.fullName} pasó a ${targetName}.`)
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
}
invalidateGroupQueries() invalidateGroupQueries()
void queryClient.invalidateQueries({ queryKey: ['groups'] })
}, },
onError: (err: Error) => { onError: (err: Error) => {
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') { if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
@@ -377,9 +393,10 @@ export function GroupDetailProvider({
isSubmittingApproval: approvePreRegistrationMutation.isPending, isSubmittingApproval: approvePreRegistrationMutation.isPending,
isSubmittingRejection: rejectPreRegistrationMutation.isPending, isSubmittingRejection: rejectPreRegistrationMutation.isPending,
isRegeneratingInvite: regenerateTokenMutation.isPending, isRegeneratingInvite: regenerateTokenMutation.isPending,
promoteEntry: (entry) => { groups: groupsQuery.data?.data ?? [],
promoteEntry: (entry, targetGroupId) => {
setSelectedWaitlistEntry(null) setSelectedWaitlistEntry(null)
promoteWaitlistMutation.mutate(entry.id) promoteWaitlistMutation.mutate({ entryId: entry.id, targetGroupId })
}, },
removeEntry: (entry) => { removeEntry: (entry) => {
setSelectedWaitlistEntry(null) setSelectedWaitlistEntry(null)

View File

@@ -1,11 +1,19 @@
import type { GroupListItem } from '@gruperly/shared'
import { useEffect, useState } from 'react'
import { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react' import { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react'
import { Button, Modal } from '../../../components/ui' import { Button, Modal } from '../../../components/ui'
import { formatPhoneDisplay } from '../../../lib/format' import { formatPhoneDisplay } from '../../../lib/format'
import { DetailRow } from './DetailRow' import { DetailRow } from './DetailRow'
import { useGroupDetail } from './GroupDetailProvider' import { useGroupDetail } from './GroupDetailProvider'
function isFull(group: GroupListItem): boolean {
return group.capacity != null && group.attendeesCount >= group.capacity
}
export function WaitlistEntryDetailModal() { export function WaitlistEntryDetailModal() {
const { const {
groupId,
groups,
selectedWaitlistEntry, selectedWaitlistEntry,
setSelectedWaitlistEntry, setSelectedWaitlistEntry,
hasFreeCapacity, hasFreeCapacity,
@@ -15,6 +23,16 @@ export function WaitlistEntryDetailModal() {
isSubmittingWaitlistRemoval, isSubmittingWaitlistRemoval,
} = useGroupDetail() } = useGroupDetail()
// Por defecto pasa al grupo en el que se anotó; el profe puede elegir otro.
const [targetGroupId, setTargetGroupId] = useState(groupId)
useEffect(() => {
setTargetGroupId(groupId)
}, [groupId, selectedWaitlistEntry])
const isCurrentGroup = targetGroupId === groupId
const targetGroup = groups.find((group) => group.id === targetGroupId)
const targetHasFreeCapacity = isCurrentGroup ? hasFreeCapacity : !targetGroup || !isFull(targetGroup)
return ( return (
<Modal <Modal
isOpen={selectedWaitlistEntry !== null} isOpen={selectedWaitlistEntry !== null}
@@ -81,18 +99,42 @@ export function WaitlistEntryDetailModal() {
</DetailRow> </DetailRow>
</div> </div>
{!hasFreeCapacity ? ( {groups.length > 1 ? (
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Asignar a</span>
<select
value={targetGroupId}
onChange={(event) => setTargetGroupId(event.target.value)}
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
{groups.map((group) => {
const isOwnGroup = group.id === groupId
// El grupo actual queda elegible siempre: su cupo lo explica el aviso de abajo.
const full = !isOwnGroup && isFull(group)
return (
<option key={group.id} value={group.id} disabled={full}>
{group.name}
{isOwnGroup ? ' (en el que se anotó)' : full ? ' (sin cupo)' : ''}
</option>
)
})}
</select>
</label>
) : null}
{!targetHasFreeCapacity ? (
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-xs text-foreground/70"> <p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-xs text-foreground/70">
El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar a esta {isCurrentGroup
persona al grupo. ? 'El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar a esta persona al grupo.'
: 'Ese grupo alcanzó su cupo de miembros. Elige otro grupo o libera un lugar primero.'}
</p> </p>
) : null} ) : null}
<div className="grid grid-cols-1 gap-2.5 border-t border-border pt-2"> <div className="grid grid-cols-1 gap-2.5 border-t border-border pt-2">
<Button <Button
variant="primary" variant="primary"
onClick={() => promoteEntry(selectedWaitlistEntry)} onClick={() => promoteEntry(selectedWaitlistEntry, targetGroupId)}
disabled={isSubmittingPromotion || !hasFreeCapacity} disabled={isSubmittingPromotion || !targetHasFreeCapacity}
className="gap-2" className="gap-2"
> >
{isSubmittingPromotion ? ( {isSubmittingPromotion ? (
@@ -100,7 +142,9 @@ export function WaitlistEntryDetailModal() {
) : ( ) : (
<UserCheck className="size-4" /> <UserCheck className="size-4" />
)} )}
<span>Pasar al grupo</span> <span className="truncate">
{isCurrentGroup || !targetGroup ? 'Pasar al grupo' : `Pasar a ${targetGroup.name}`}
</span>
</Button> </Button>
<Button <Button
variant="ghost" variant="ghost"

View File

@@ -319,9 +319,12 @@ export const updateGroupAttendee = (
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) => export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`) apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)
export const promoteGroupWaitlistEntry = (groupId: string, entryId: string) => // Sin `targetGroupId` la persona pasa al grupo en el que se anotó. El body va
// siempre: `apiFetch` manda Content-Type JSON y un body vacío no se parsea.
export const promoteGroupWaitlistEntry = (groupId: string, entryId: string, targetGroupId?: string) =>
apiFetch<PromoteGroupWaitlistEntryResult>(`/api/v1/groups/${groupId}/waitlist/${entryId}/promote`, { apiFetch<PromoteGroupWaitlistEntryResult>(`/api/v1/groups/${groupId}/waitlist/${entryId}/promote`, {
method: 'POST', method: 'POST',
body: JSON.stringify({ targetGroupId }),
}) })
export const removeGroupWaitlistEntry = (groupId: string, entryId: string) => export const removeGroupWaitlistEntry = (groupId: string, entryId: string) =>

View File

@@ -161,6 +161,13 @@ export const BulkCreateAttendeesResultSchema = z.object({
}); });
export type BulkCreateAttendeesResult = z.output<typeof BulkCreateAttendeesResultSchema>; export type BulkCreateAttendeesResult = z.output<typeof BulkCreateAttendeesResultSchema>;
/* Accepting someone from the waitlist defaults to the group they signed up
for; `targetGroupId` lets the teacher place them in another of their groups. */
export const PromoteGroupWaitlistEntrySchema = z.object({
targetGroupId: z.string().min(1).optional(),
});
export type PromoteGroupWaitlistEntry = z.output<typeof PromoteGroupWaitlistEntrySchema>;
export const PromoteGroupWaitlistEntryResultSchema = z.object({ export const PromoteGroupWaitlistEntryResultSchema = z.object({
attendee: AttendeeDtoSchema, attendee: AttendeeDtoSchema,
}); });