import type { AbsenceDetails, 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, GroupWaitlistEntryDto, GroupWaitlistList, HomeSummaryDto, InviteTokenResult, JoinGroupViaInvite, JoinGroupViaInviteResult, MarkAttendance, MarkAttendanceResult, MpAuthorizationUrlDto, MpDisconnectResultDto, MpReturnTo, MpStatusDto, NotifyAbsence, NotifyAbsenceResult, OnboardingStatusDto, PaymentDto, PaymentList, PaymentQuery, ProblemDetails, 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 | unknown[] async function apiFetch(path: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers) 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 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) } return (await res.json()) as T } export const getOnboardingStatus = () => apiFetch('/api/v1/onboarding/status') export const createFirstGroup = (payload: CreateFirstGroup) => apiFetch('/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('/api/v1/onboarding/plan', { method: 'POST', body: JSON.stringify(payload), }) export const createGroup = (payload: CreateFirstGroup) => apiFetch('/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(`/api/v1/mp/connect?returnTo=${returnTo}`) export const getMpStatus = () => apiFetch('/api/v1/mp/status') export const disconnectMp = () => apiFetch('/api/v1/mp/connect', { method: 'DELETE' }) // — Plan de Gruperly (suscripción a Pro con Mercado Pago) — export const getBillingStatus = () => apiFetch('/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('/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(`/api/v1/billing/charges?page=${page}&pageSize=10`) // --- WhatsApp (recordatorios y reenganche automáticos) --- export const startWhatsappConnection = (returnTo: WhatsappReturnTo) => apiFetch('/api/v1/whatsapp/connect', { method: 'POST', body: JSON.stringify({ returnTo }), }) export const requestWhatsappPairingCode = (phoneNumber: string) => apiFetch('/api/v1/whatsapp/connect/pairing-code', { method: 'POST', body: JSON.stringify({ phoneNumber }), }) export const getWhatsappStatus = () => apiFetch('/api/v1/whatsapp/status') export const disconnectWhatsapp = () => apiFetch('/api/v1/whatsapp/connect', { method: 'DELETE' }) export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) => apiFetch(`/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(`/api/v1/payments?${query.toString()}`) } export const createPaymentsBatch = (groupId: string, payload: CreatePaymentsBatch) => apiFetch(`/api/v1/groups/${groupId}/payments/batch`, { method: 'POST', body: JSON.stringify(payload), }) export const renewPaymentLink = (paymentId: string) => apiFetch(`/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(`/api/v1/groups?${params.toString()}`) } function timeZoneParam(): string { const timeZone = browserTimezone() return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : '' } export const getHomeSummary = () => apiFetch(`/api/v1/home${timeZoneParam()}`) export const getGroup = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}`) export const getInviteToken = (groupId: string, regenerate = false) => regenerate ? apiFetch(`/api/v1/groups/${groupId}/invite-token?regenerate=true`, { method: 'POST', }) : apiFetch(`/api/v1/groups/${groupId}/invite-token`) export const getInviteInfo = (token: string) => apiFetch(`/api/v1/invitations/${token}`) export const joinViaInvite = (token: string, payload: JoinGroupViaInvite) => apiFetch(`/api/v1/invitations/${token}/join`, { method: 'POST', body: JSON.stringify(payload), }) export const createAttendee = ( groupId: string, payload: CreateAttendee, options?: { allowOverflow?: boolean }, ) => apiFetch( `/api/v1/groups/${groupId}/attendees${options?.allowOverflow ? '?allowOverflow=true' : ''}`, { method: 'POST', body: JSON.stringify(payload), }, ) export const addToGroupWaitlist = (groupId: string, payload: CreateGroupWaitlistEntry) => apiFetch(`/api/v1/groups/${groupId}/waitlist`, { method: 'POST', body: JSON.stringify(payload), }) export const bulkCreateAttendees = (groupId: string, payload: BulkCreateAttendees) => apiFetch(`/api/v1/groups/${groupId}/attendees/bulk`, { method: 'POST', body: JSON.stringify(payload), }) export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) => apiFetch(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`) export const getGroupAttendee = (groupId: string, attendeeId: string) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}`) export const updateGroupAttendee = ( groupId: string, attendeeId: string, payload: UpdateAttendee, ) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}`, { method: 'PATCH', body: JSON.stringify(payload), }) export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) => apiFetch(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`) export const promoteGroupWaitlistEntry = (groupId: string, entryId: string) => apiFetch(`/api/v1/groups/${groupId}/waitlist/${entryId}/promote`, { method: 'POST', }) export const removeGroupWaitlistEntry = (groupId: string, entryId: string) => apiFetch(`/api/v1/groups/${groupId}/waitlist/${entryId}`, { method: 'DELETE', }) export const getGroupPreRegistrations = (groupId: string, page = 1, pageSize = 100) => apiFetch( `/api/v1/groups/${groupId}/preregistrations?page=${page}&pageSize=${pageSize}`, ) export const approveGroupPreRegistration = (groupId: string, entryId: string) => apiFetch( `/api/v1/groups/${groupId}/preregistrations/${entryId}/approve`, { method: 'POST' }, ) export const rejectGroupPreRegistration = (groupId: string, entryId: string) => apiFetch( `/api/v1/groups/${groupId}/preregistrations/${entryId}/reject`, { method: 'POST' }, ) export const removeGroupAttendee = ( groupId: string, attendeeId: string, options?: { promoteFromWaitlist?: boolean }, ) => apiFetch( `/api/v1/groups/${groupId}/attendees/${attendeeId}${options?.promoteFromWaitlist ? '?promoteFromWaitlist=true' : ''}`, { method: 'DELETE', }, ) // — Day to day: classes and attendance — export const getClassesToday = () => apiFetch(`/api/v1/classes/today${timeZoneParam()}`) export const getSessionStudents = (sessionId: string) => apiFetch(`/api/v1/classes/${sessionId}/students${timeZoneParam()}`) export const markAttendance = (sessionId: string, payload: MarkAttendance) => apiFetch(`/api/v1/classes/${sessionId}/attendance`, { method: 'POST', body: JSON.stringify(payload), }) export const notifyAbsence = (sessionId: string, payload: NotifyAbsence) => apiFetch(`/api/v1/classes/${sessionId}/notify-absence`, { method: 'POST', body: JSON.stringify(payload), }) export const getAbsenceDetails = (token: string) => apiFetch(`/api/v1/classes/absence?token=${encodeURIComponent(token)}`) export const publicNotifyAbsence = (payload: PublicNotifyAbsence) => apiFetch('/api/v1/classes/notify-absence', { method: 'POST', body: JSON.stringify(payload), }) // — Analytics and risk management — export const getGroupAnalytics = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}/analytics`) export const getStudentsAtRisk = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}/students-at-risk`) export const getGroupsRiskOverview = () => apiFetch('/api/v1/groups-risk/overview') export const getAttendeeHistory = (groupId: string, attendeeId: string) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`) export const getAttendeeStats = (groupId: string, attendeeId: string) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}/stats`) export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) => apiFetch(`/api/v1/students/${attendeeId}/status`, { method: 'POST', body: JSON.stringify({ status }), })