Files
gruperly/apps/web/src/lib/api.ts
Jose Selesan fc12ec3ae0 feat: pasar de la lista de espera a otro grupo del profesor
- `POST /groups/:gid/waitlist/:entryId/promote` acepta `targetGroupId`
  opcional (por defecto, el grupo en el que se anotó). El destino tiene que
  ser del mismo profesor; cupo y teléfono duplicado se validan ahí.
- Detalle de la lista de espera: selector "Asignar a" con los grupos llenos
  deshabilitados.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:39:55 -03:00

561 lines
19 KiB
TypeScript

import type {
AbsenceDetails,
AdminAccountDetail,
AdminAccountList,
AdminAccountQueryInput,
AdminMeDto,
ApproveGroupPreRegistrationResult,
AttendeeDetailDto,
AttendeeDto,
AttendeeHistory,
AttendeeList,
AttendeeStats,
AttendeeStatus,
BillingChargeList,
BillingStatusDto,
BulkCreateAttendees,
BulkCreateAttendeesResult,
ClassTodayList,
CreateAttendee,
CreateAttendeeResult,
CreateFirstGroup,
CreateFirstGroupResult,
CreateGroupResult,
CreateGroupWaitlistEntry,
CreatePaymentsBatch,
CreatePaymentsBatchResult,
GroupAnalytics,
GroupDto,
GroupInviteInfoDto,
GroupList,
GroupPreRegistrationList,
GroupRiskSummary,
GroupsRiskOverview,
AttentionOverview,
ResolveAlert,
GroupWaitlistEntryDto,
GroupWaitlistList,
HomeSummaryDto,
InviteTokenResult,
JoinGroupViaInvite,
JoinGroupViaInviteResult,
MarkAttendance,
MarkAttendanceResult,
MpAuthorizationUrlDto,
MpDisconnectResultDto,
MpReturnTo,
MpStatusDto,
NotifyAbsence,
NotifyAbsenceResult,
OnboardingStatusDto,
PaymentDto,
PaymentList,
PaymentQuery,
ProblemDetails,
StudentLinkInfo,
ConsumeStudentLinkResult,
StudentMe,
PasskeyOptionsResult,
PasskeyVerify,
StudentClassesDto,
CreateAbsenceNotices,
CreateAbsenceNoticesResult,
StudentFeesDto,
StudentAccessDto,
StudentInvitationDto,
ReportedPaymentList,
ReportedPaymentDto,
ReceiptUrlDto,
TransferDetailsDto,
UpdateTransferDetails,
TeacherAbsenceNoticeList,
PromoteGroupWaitlistEntryResult,
PublicNotifyAbsence,
RejectGroupPreRegistrationResult,
RemoveAttendeeResult,
RemoveGroupWaitlistEntryResult,
SelectPlanInput,
SelectPlanResultDto,
SessionStudents,
StudentsAtRisk,
SubscribeInput,
SubscribeResultDto,
UpdateAttendee,
UpdateStudentStatusResult,
GroupAutomationsDto,
UpdateGroupAutomations,
WhatsappConnectResultDto,
WhatsappDisconnectResultDto,
WhatsappReturnTo,
WhatsappPairingCodeDto,
WhatsappStatusDto,
} from '@gruperly/shared'
import { browserTimezone } from './region'
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000'
export class ApiError extends Error {
constructor(
readonly status: number,
readonly problem: ProblemDetails | null,
) {
super(problem?.detail ?? problem?.title ?? `Error ${status}`)
this.name = 'ApiError'
}
}
type JsonBody = Record<string, unknown> | unknown[]
async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers)
// A FormData body sets its own multipart Content-Type (with the boundary).
if (!(init?.body instanceof FormData)) headers.set('Content-Type', 'application/json')
const res = await fetch(`${API_URL}${path}`, {
...init,
headers,
credentials: 'include',
})
if (!res.ok) {
let problem: ProblemDetails | null = null
try {
const body = (await res.json()) as Partial<ProblemDetails>
if (body && typeof body === 'object' && typeof body.title === 'string') {
problem = body as ProblemDetails
}
} catch {
// No JSON body: we use the generic error.
}
throw new ApiError(res.status, problem)
}
if (res.status === 204) return undefined as T
return (await res.json()) as T
}
export const getOnboardingStatus = () => apiFetch<OnboardingStatusDto>('/api/v1/onboarding/status')
export const createFirstGroup = (payload: CreateFirstGroup) =>
apiFetch<CreateFirstGroupResult>('/api/v1/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(payload),
})
/* Paso obligatorio "Plan" del onboarding. Con Pro devuelve `checkoutUrl`: el
navegador navega a Mercado Pago y vuelve a `/onboarding?sub=return`. */
export const selectPlan = (payload: SelectPlanInput) =>
apiFetch<SelectPlanResultDto>('/api/v1/onboarding/plan', {
method: 'POST',
body: JSON.stringify(payload),
})
export const createGroup = (payload: CreateFirstGroup) =>
apiFetch<CreateGroupResult>('/api/v1/groups', {
method: 'POST',
body: JSON.stringify(payload),
})
// — Mercado Pago —
/* La vinculación es un OAuth: el backend devuelve la URL de autorización y el
navegador navega a Mercado Pago. `returnTo` le dice al callback a qué pantalla
volver (solo `onboarding` o `settings`: nunca una URL libre). */
export const startMpAuthorization = (returnTo: MpReturnTo) =>
apiFetch<MpAuthorizationUrlDto>(`/api/v1/mp/connect?returnTo=${returnTo}`)
export const getMpStatus = () => apiFetch<MpStatusDto>('/api/v1/mp/status')
export const disconnectMp = () =>
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
// — Plan de Gruperly (suscripción a Pro con Mercado Pago) —
export const getBillingStatus = () => apiFetch<BillingStatusDto>('/api/v1/billing/status')
/* Igual que la vinculación de MP: el backend devuelve a dónde navegar y Mercado
Pago devuelve el control a `/billing?sub=return`. */
export const subscribeToPro = (payload: SubscribeInput) =>
apiFetch<SubscribeResultDto>('/api/v1/billing/subscribe', {
method: 'POST',
body: JSON.stringify(payload),
})
export const cancelSubscription = () =>
apiFetch<{ status: string }>('/api/v1/billing/cancel', { method: 'POST' })
export const getBillingCharges = (page = 1) =>
apiFetch<BillingChargeList>(`/api/v1/billing/charges?page=${page}&pageSize=10`)
// --- WhatsApp (recordatorios y reenganche automáticos) ---
export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
apiFetch<WhatsappConnectResultDto>('/api/v1/whatsapp/connect', {
method: 'POST',
body: JSON.stringify({ returnTo }),
})
export const requestWhatsappPairingCode = (phoneNumber: string) =>
apiFetch<WhatsappPairingCodeDto>('/api/v1/whatsapp/connect/pairing-code', {
method: 'POST',
body: JSON.stringify({ phoneNumber }),
})
export const getWhatsappStatus = () => apiFetch<WhatsappStatusDto>('/api/v1/whatsapp/status')
export const disconnectWhatsapp = () =>
apiFetch<WhatsappDisconnectResultDto>('/api/v1/whatsapp/connect', { method: 'DELETE' })
export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) =>
apiFetch<GroupAutomationsDto>(`/api/v1/groups/${groupId}/automations`, {
method: 'PATCH',
body: JSON.stringify(payload),
})
// — Cobros —
export const getPayments = (params: PaymentQuery) => {
const query = new URLSearchParams({
page: String(params.page ?? 1),
pageSize: String(params.pageSize ?? 20),
})
if (params.groupId) query.set('groupId', params.groupId)
if (params.status) query.set('status', params.status)
return apiFetch<PaymentList>(`/api/v1/payments?${query.toString()}`)
}
export const createPaymentsBatch = (groupId: string, payload: CreatePaymentsBatch) =>
apiFetch<CreatePaymentsBatchResult>(`/api/v1/groups/${groupId}/payments/batch`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const renewPaymentLink = (paymentId: string) =>
apiFetch<PaymentDto>(`/api/v1/payments/${paymentId}/renew`, { method: 'POST' })
/* The groups screen has no pagination: we ask for the maximum allowed so no
group is left out of the listing, and for the browser time zone so the
backend sorts by the next class in the person's local time. */
const GROUPS_PAGE_SIZE = 100
export const getGroups = () => {
const params = new URLSearchParams({ pageSize: String(GROUPS_PAGE_SIZE) })
const timeZone = browserTimezone()
if (timeZone) {
params.set('timeZone', timeZone)
}
return apiFetch<GroupList>(`/api/v1/groups?${params.toString()}`)
}
function timeZoneParam(): string {
const timeZone = browserTimezone()
return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : ''
}
export const getHomeSummary = () =>
apiFetch<HomeSummaryDto>(`/api/v1/home${timeZoneParam()}`)
export const getGroup = (groupId: string) =>
apiFetch<GroupDto>(`/api/v1/groups/${groupId}`)
export const getInviteToken = (groupId: string, regenerate = false) =>
regenerate
? apiFetch<InviteTokenResult>(`/api/v1/groups/${groupId}/invite-token?regenerate=true`, {
method: 'POST',
})
: apiFetch<InviteTokenResult>(`/api/v1/groups/${groupId}/invite-token`)
export const getInviteInfo = (token: string) =>
apiFetch<GroupInviteInfoDto>(`/api/v1/invitations/${token}`)
export const joinViaInvite = (token: string, payload: JoinGroupViaInvite) =>
apiFetch<JoinGroupViaInviteResult>(`/api/v1/invitations/${token}/join`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const createAttendee = (
groupId: string,
payload: CreateAttendee,
options?: { allowOverflow?: boolean },
) =>
apiFetch<CreateAttendeeResult>(
`/api/v1/groups/${groupId}/attendees${options?.allowOverflow ? '?allowOverflow=true' : ''}`,
{
method: 'POST',
body: JSON.stringify(payload),
},
)
export const addToGroupWaitlist = (groupId: string, payload: CreateGroupWaitlistEntry) =>
apiFetch<GroupWaitlistEntryDto>(`/api/v1/groups/${groupId}/waitlist`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const bulkCreateAttendees = (groupId: string, payload: BulkCreateAttendees) =>
apiFetch<BulkCreateAttendeesResult>(`/api/v1/groups/${groupId}/attendees/bulk`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) =>
apiFetch<AttendeeList>(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`)
export const getGroupAttendee = (groupId: string, attendeeId: string) =>
apiFetch<AttendeeDetailDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`)
export const updateGroupAttendee = (
groupId: string,
attendeeId: string,
payload: UpdateAttendee,
) =>
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`, {
method: 'PATCH',
body: JSON.stringify(payload),
})
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)
// 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`, {
method: 'POST',
body: JSON.stringify({ targetGroupId }),
})
export const removeGroupWaitlistEntry = (groupId: string, entryId: string) =>
apiFetch<RemoveGroupWaitlistEntryResult>(`/api/v1/groups/${groupId}/waitlist/${entryId}`, {
method: 'DELETE',
})
export const getGroupPreRegistrations = (groupId: string, page = 1, pageSize = 100) =>
apiFetch<GroupPreRegistrationList>(
`/api/v1/groups/${groupId}/preregistrations?page=${page}&pageSize=${pageSize}`,
)
export const approveGroupPreRegistration = (groupId: string, entryId: string) =>
apiFetch<ApproveGroupPreRegistrationResult>(
`/api/v1/groups/${groupId}/preregistrations/${entryId}/approve`,
{ method: 'POST' },
)
export const rejectGroupPreRegistration = (groupId: string, entryId: string) =>
apiFetch<RejectGroupPreRegistrationResult>(
`/api/v1/groups/${groupId}/preregistrations/${entryId}/reject`,
{ method: 'POST' },
)
export const removeGroupAttendee = (
groupId: string,
attendeeId: string,
options?: { promoteFromWaitlist?: boolean },
) =>
apiFetch<RemoveAttendeeResult>(
`/api/v1/groups/${groupId}/attendees/${attendeeId}${options?.promoteFromWaitlist ? '?promoteFromWaitlist=true' : ''}`,
{
method: 'DELETE',
},
)
// — Day to day: classes and attendance —
export const getClassesToday = () =>
apiFetch<ClassTodayList>(`/api/v1/classes/today${timeZoneParam()}`)
export const getSessionStudents = (sessionId: string) =>
apiFetch<SessionStudents>(`/api/v1/classes/${sessionId}/students${timeZoneParam()}`)
export const markAttendance = (sessionId: string, payload: MarkAttendance) =>
apiFetch<MarkAttendanceResult>(`/api/v1/classes/${sessionId}/attendance`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const notifyAbsence = (sessionId: string, payload: NotifyAbsence) =>
apiFetch<NotifyAbsenceResult>(`/api/v1/classes/${sessionId}/notify-absence`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const getAbsenceDetails = (token: string) =>
apiFetch<AbsenceDetails>(`/api/v1/classes/absence?token=${encodeURIComponent(token)}`)
export const publicNotifyAbsence = (payload: PublicNotifyAbsence) =>
apiFetch<NotifyAbsenceResult>('/api/v1/classes/notify-absence', {
method: 'POST',
body: JSON.stringify(payload),
})
// — Analytics and risk management —
export const getGroupAnalytics = (groupId: string) =>
apiFetch<GroupAnalytics>(`/api/v1/groups/${groupId}/analytics`)
export const getStudentsAtRisk = (groupId: string) =>
apiFetch<StudentsAtRisk>(`/api/v1/groups/${groupId}/students-at-risk`)
export const getGroupsRiskOverview = () => apiFetch<GroupsRiskOverview>('/api/v1/groups-risk/overview')
export const getAttention = () => apiFetch<AttentionOverview>('/api/v1/attention')
export const resolveAlert = (attendeeId: string, body: ResolveAlert) =>
apiFetch<ResolveAlert & { attendeeId: string }>(`/api/v1/attention/${attendeeId}/resolve`, {
method: 'POST',
body: JSON.stringify(body),
})
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)
export const getAttendeeStats = (groupId: string, attendeeId: string) =>
apiFetch<AttendeeStats>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/stats`)
export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) =>
apiFetch<UpdateStudentStatusResult>(`/api/v1/students/${attendeeId}/status`, {
method: 'POST',
body: JSON.stringify({ status }),
})
// — Backoffice (equipo de Gruperly) —
export const getAdminMe = () => apiFetch<AdminMeDto>('/api/v1/admin/me')
export const getAdminAccounts = (params: AdminAccountQueryInput) => {
const query = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== '') query.set(key, String(value))
}
return apiFetch<AdminAccountList>(`/api/v1/admin/accounts?${query.toString()}`)
}
export const getAdminAccount = (accountId: string) =>
apiFetch<AdminAccountDetail>(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`)
// — App del alumno (sesión propia, nunca la del profe) —
const STUDENT_API = '/api/v1/student-portal'
export const getStudentLinkInfo = (token: string) =>
apiFetch<StudentLinkInfo>(`${STUDENT_API}/links/${encodeURIComponent(token)}`)
export const consumeStudentLink = (token: string) =>
apiFetch<ConsumeStudentLinkResult>(`${STUDENT_API}/links/${encodeURIComponent(token)}/consume`, {
method: 'POST',
})
export const getStudentMe = () => apiFetch<StudentMe>(`${STUDENT_API}/me`)
export const markStudentWelcomed = () => apiFetch<StudentMe>(`${STUDENT_API}/me/welcome`, { method: 'POST' })
export const logoutStudent = () => apiFetch<void>(`${STUDENT_API}/logout`, { method: 'POST' })
export const setStudentRecoveryEmail = (email: string) =>
apiFetch<StudentMe>(`${STUDENT_API}/me/recovery-email`, {
method: 'PUT',
body: JSON.stringify({ email }),
})
export const removeStudentRecoveryEmail = () =>
apiFetch<StudentMe>(`${STUDENT_API}/me/recovery-email`, { method: 'DELETE' })
export const confirmStudentRecoveryEmail = (token: string) =>
apiFetch<{ email: string }>(`${STUDENT_API}/recovery-email/confirm`, {
method: 'POST',
body: JSON.stringify({ token }),
})
export const requestStudentRecoveryLink = (email: string) =>
apiFetch<{ accepted: true }>(`${STUDENT_API}/recovery`, {
method: 'POST',
body: JSON.stringify({ email }),
})
export const getStudentPasskeyRegistrationOptions = () =>
apiFetch<PasskeyOptionsResult>(`${STUDENT_API}/passkeys/register/options`, { method: 'POST' })
export const verifyStudentPasskeyRegistration = (payload: PasskeyVerify) =>
apiFetch<StudentMe>(`${STUDENT_API}/passkeys/register/verify`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const removeStudentPasskeys = () =>
apiFetch<StudentMe>(`${STUDENT_API}/passkeys`, { method: 'DELETE' })
export const getStudentPasskeyLoginOptions = () =>
apiFetch<PasskeyOptionsResult>(`${STUDENT_API}/passkeys/login/options`, { method: 'POST' })
export const verifyStudentPasskeyLogin = (payload: PasskeyVerify) =>
apiFetch<ConsumeStudentLinkResult>(`${STUDENT_API}/passkeys/login/verify`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const getStudentClasses = (attendeeId: string) =>
apiFetch<StudentClassesDto>(`${STUDENT_API}/classes?attendeeId=${encodeURIComponent(attendeeId)}`)
export const notifyStudentAbsences = (payload: CreateAbsenceNotices) =>
apiFetch<CreateAbsenceNoticesResult>(`${STUDENT_API}/absences`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const cancelStudentAbsence = (noticeId: string) =>
apiFetch<{ id: string }>(`${STUDENT_API}/absences/${encodeURIComponent(noticeId)}`, { method: 'DELETE' })
export const getStudentFees = (attendeeId: string) =>
apiFetch<StudentFeesDto>(`${STUDENT_API}/fees?attendeeId=${encodeURIComponent(attendeeId)}`)
export const reportStudentPayment = (payload: { attendeeId: string; paymentIds: string[]; note?: string | null; file: File }) => {
const form = new FormData()
form.set('attendeeId', payload.attendeeId)
for (const id of payload.paymentIds) form.append('paymentIds', id)
if (payload.note) form.set('note', payload.note)
form.set('file', payload.file)
return apiFetch<{ id: string }>(`${STUDENT_API}/payment-reports`, { method: 'POST', body: form })
}
// — Acceso de alumnos a la app (lado profe) —
export const getStudentAccess = (groupId: string, attendeeId: string) =>
apiFetch<StudentAccessDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/student-access`)
/* Invitar o reinvitar: revoca el acceso anterior y devuelve el link nuevo (una
sola vez: el backend guarda solo su hash). */
export const inviteStudent = (groupId: string, attendeeId: string) =>
apiFetch<StudentInvitationDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/student-access/invite`, {
method: 'POST',
})
export const getGroupAbsenceNotices = (groupId: string) =>
apiFetch<TeacherAbsenceNoticeList>(`/api/v1/groups/${groupId}/absence-notices`)
export const getReportedPayments = () => apiFetch<ReportedPaymentList>('/api/v1/payments/reported')
export const getReceiptUrl = (reportId: string) =>
apiFetch<ReceiptUrlDto>(`/api/v1/payments/reported/${reportId}/receipt`)
export const confirmReportedPayment = (reportId: string) =>
apiFetch<ReportedPaymentDto>(`/api/v1/payments/reported/${reportId}/confirm`, { method: 'POST' })
export const rejectReportedPayment = (reportId: string, reason: string | null) =>
apiFetch<ReportedPaymentDto>(`/api/v1/payments/reported/${reportId}/reject`, {
method: 'POST',
body: JSON.stringify({ reason }),
})
export const undoPaymentReview = (reportId: string) =>
apiFetch<ReportedPaymentDto>(`/api/v1/payments/reported/${reportId}/undo`, { method: 'POST' })
export const getTransferDetails = () => apiFetch<TransferDetailsDto>('/api/v1/payments/transfer-details')
export const updateTransferDetails = (payload: UpdateTransferDetails) =>
apiFetch<TransferDetailsDto>('/api/v1/payments/transfer-details', {
method: 'PUT',
body: JSON.stringify(payload),
})