- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales de plataforma por país, webhook firmado y reconciliación por polling. - PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o activan automatizaciones (402 plan_limit_reached / plan_feature_required / plan_read_only), detrás de BILLING_ENFORCEMENT. - Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se saltean Cobros y WhatsApp. - Web: pantalla /billing, aviso de Pro desde el MutationCache. - Migración billing_subscriptions y docs/billing.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
386 lines
13 KiB
TypeScript
386 lines
13 KiB
TypeScript
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<string, unknown> | unknown[]
|
|
|
|
async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
|
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<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)
|
|
}
|
|
|
|
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}`)
|
|
|
|
export const promoteGroupWaitlistEntry = (groupId: string, entryId: string) =>
|
|
apiFetch<PromoteGroupWaitlistEntryResult>(`/api/v1/groups/${groupId}/waitlist/${entryId}/promote`, {
|
|
method: 'POST',
|
|
})
|
|
|
|
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 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 }),
|
|
})
|