diff --git a/AGENTS.md b/AGENTS.md index c973d2e..090ea4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/logger.ts` — pino + pino-pretty. - - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). + - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 54eff8d..c6a55e1 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -43,6 +43,9 @@ BILLING_ENFORCEMENT="off" # Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. BILLING_GRACE_DAYS="7" +# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie. +ADMIN_EMAILS="" + # WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md). # Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta). WHATSAPP_PROVIDER="openwa" diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 1adc52c..ad11aed 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -10,6 +10,7 @@ import { requestLoggerMiddleware } from '@/http/request-logger'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { sessionAuthMiddleware } from '@/http/session-auth'; import { logger } from '@/logger'; +import { adminRoutes } from './modules/admin'; import { groupsRiskOverviewRoute, studentStatusRoutes, @@ -48,6 +49,7 @@ for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/studen api.use(`${prefix}/*`, planReadOnly); } +api.route('/admin', adminRoutes); api.route('/auth', authRoutes); api.route('/health', healthCheckRoutes); api.route('/invitations', invitationsRoutes); diff --git a/apps/backend/src/modules/admin/features/get-account/route.ts b/apps/backend/src/modules/admin/features/get-account/route.ts new file mode 100644 index 0000000..5ec9959 --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-account/route.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { GetAccount } from './use-case'; + +const route = new Hono(); + +route.get('/accounts/:accountId', async (c) => { + const result = await new GetAccount().execute(c.req.param('accountId')); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/features/get-account/use-case.ts b/apps/backend/src/modules/admin/features/get-account/use-case.ts new file mode 100644 index 0000000..fab9353 --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-account/use-case.ts @@ -0,0 +1,95 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib'; +import { accountPlan, toAccountListItem } from '../../lib'; + +const RECENT_CHARGES = 12; + +type GetAccountDeps = { + db?: Pick; + enforced?: boolean; + graceDays?: number; + now?: () => Date; +}; + +/** One professor's account: plan, links, groups and the latest Pro charges. */ +export class GetAccount { + constructor(private readonly deps: GetAccountDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const context = { + now: this.deps.now?.() ?? new Date(), + graceDays: this.deps.graceDays ?? getGraceDays(), + }; + + const user = await db.user.findUnique({ + where: { id: userId }, + include: { + subscription: true, + mpAccount: { select: { status: true } }, + whatsappAccount: { select: { status: true } }, + groupsOwner: { + select: { + id: true, + name: true, + createdAt: true, + _count: { select: { attendees: { where: { status: 'ACTIVE' } } } }, + }, + orderBy: { createdAt: 'desc' }, + }, + }, + }); + if (!user) return err(notFoundResourceProblem('User', userId)); + + const charges = await db.billingCharge.findMany({ + where: { subscription: { userId } }, + orderBy: { createdAt: 'desc' }, + take: RECENT_CHARGES, + }); + + const groups = user.groupsOwner.map((group) => ({ + id: group.id, + name: group.name, + createdAt: group.createdAt.toISOString(), + attendeesCount: group._count.attendees, + })); + const usage = { + groupsCount: groups.length, + attendeesCount: groups.reduce((sum, group) => sum + group.attendeesCount, 0), + }; + const summary = toAccountListItem(user, usage, context); + const { graceUntil } = accountPlan(user, context); + const enforced = this.deps.enforced ?? isBillingEnforced(); + const subscription = user.subscription; + + return ok({ + ...summary, + planSelectedAt: user.planSelectedAt?.toISOString() ?? null, + graceUntil: graceUntil?.toISOString() ?? null, + // Same rule as the PlanGuard: an account without a plan is held to Free. + readOnly: + enforced + && exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], { + groups: usage.groupsCount, + attendees: usage.attendeesCount, + }), + subscription: + summary.subscription && subscription + ? { + ...summary.subscription, + payerEmail: subscription.payerEmail, + authorizedAt: subscription.authorizedAt?.toISOString() ?? null, + requestedAt: subscription.requestedAt.toISOString(), + } + : null, + mpStatus: user.mpAccount?.status ?? null, + whatsappStatus: user.whatsappAccount?.status ?? null, + groups, + charges: charges.map(toBillingChargeDto), + }); + } +} diff --git a/apps/backend/src/modules/admin/features/list-accounts/route.ts b/apps/backend/src/modules/admin/features/list-accounts/route.ts new file mode 100644 index 0000000..f6cb10e --- /dev/null +++ b/apps/backend/src/modules/admin/features/list-accounts/route.ts @@ -0,0 +1,16 @@ +import type { AdminAccountQuery } from '@gruperly/shared'; +import { AdminAccountQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { ListAccounts } from './use-case'; + +const route = new Hono(); + +route.get('/accounts', validate.query(AdminAccountQuerySchema), async (c) => { + const query = c.req.valid('query') as AdminAccountQuery; + const result = await new ListAccounts().execute(query); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/features/list-accounts/use-case.ts b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts new file mode 100644 index 0000000..0343d35 --- /dev/null +++ b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts @@ -0,0 +1,65 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { AdminAccountList, AdminAccountQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; +import prisma from '@/lib/prisma'; +import { getGraceDays } from '@/modules/billing/lib'; +import { type AccountUsage, buildAccountWhere, toAccountListItem } from '../../lib'; + +type ListAccountsDeps = { + db?: Pick; + graceDays?: number; + now?: () => Date; +}; + +/** Every professor's account, newest first, with plan and usage. */ +export class ListAccounts { + constructor(private readonly deps: ListAccountsDeps = {}) {} + + async execute(query: AdminAccountQuery): Promise> { + const db = this.deps.db ?? prisma; + const context = { + now: this.deps.now?.() ?? new Date(), + graceDays: this.deps.graceDays ?? getGraceDays(), + }; + const where = buildAccountWhere(query, context); + + const [users, total] = await Promise.all([ + db.user.findMany({ + where, + include: { subscription: true }, + skip: getPaginationOffset(query), + take: query.pageSize, + orderBy: { createdAt: 'desc' }, + }), + db.user.count({ where }), + ]); + + // Usage of the whole page in one query, same rule as the plan limits: + // groups the professor owns and their ACTIVE attendees. + const groups = users.length + ? await db.group.findMany({ + where: { createdById: { in: users.map((user) => user.id) } }, + select: { + createdById: true, + _count: { select: { attendees: { where: { status: 'ACTIVE' } } } }, + }, + }) + : []; + const usage = new Map(); + for (const group of groups) { + const current = usage.get(group.createdById) ?? { groupsCount: 0, attendeesCount: 0 }; + usage.set(group.createdById, { + groupsCount: current.groupsCount + 1, + attendeesCount: current.attendeesCount + group._count.attendees, + }); + } + + return ok({ + data: users.map((user) => + toAccountListItem(user, usage.get(user.id) ?? { groupsCount: 0, attendeesCount: 0 }, context), + ), + pagination: getPaginationMetadata(query, total), + }); + } +} diff --git a/apps/backend/src/modules/admin/features/me/route.ts b/apps/backend/src/modules/admin/features/me/route.ts new file mode 100644 index 0000000..f36974c --- /dev/null +++ b/apps/backend/src/modules/admin/features/me/route.ts @@ -0,0 +1,16 @@ +import type { AdminMeDto } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; +import { isAdminEmail } from '../../lib'; + +const route = new Hono(); + +// Open to every signed-in user: the web asks it to decide whether to show the backoffice. +route.get('/me', (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + return c.json({ isAdmin: isAdminEmail(user.email) } satisfies AdminMeDto); +}); + +export default route; diff --git a/apps/backend/src/modules/admin/index.ts b/apps/backend/src/modules/admin/index.ts new file mode 100644 index 0000000..bd2b614 --- /dev/null +++ b/apps/backend/src/modules/admin/index.ts @@ -0,0 +1 @@ +export { default as adminRoutes } from './routes'; diff --git a/apps/backend/src/modules/admin/lib/access.ts b/apps/backend/src/modules/admin/lib/access.ts new file mode 100644 index 0000000..0534bda --- /dev/null +++ b/apps/backend/src/modules/admin/lib/access.ts @@ -0,0 +1,39 @@ +import type { MiddlewareHandler } from 'hono'; +import type { BackendEnv } from '@/http/env'; +import { forbiddenProblem } from '@/http/problem-builders'; +import { problemJson, unauthorizedProblem } from '@/http/problem-details'; + +/** + * The backoffice is for Gruperly's own staff, listed by email in `ADMIN_EMAILS` + * (comma separated, case-insensitive). An empty or missing list means nobody. + */ +export function isAdminEmail( + email: string | null | undefined, + env: Record = process.env, +): boolean { + if (!email) return false; + const allowed = (env.ADMIN_EMAILS ?? '') + .split(',') + .map((entry) => entry.trim().toLowerCase()) + .filter(Boolean); + return allowed.includes(email.trim().toLowerCase()); +} + +export function adminOnlyMiddleware( + env: Record = process.env, +): MiddlewareHandler { + return async (c, next) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + if (!isAdminEmail(user.email, env)) { + return problemJson( + c, + forbiddenProblem({ + detail: 'Solo el equipo de Gruperly puede entrar al backoffice.', + code: 'admin_required', + }), + ); + } + await next(); + }; +} diff --git a/apps/backend/src/modules/admin/lib/account-summary.ts b/apps/backend/src/modules/admin/lib/account-summary.ts new file mode 100644 index 0000000..0f0bd32 --- /dev/null +++ b/apps/backend/src/modules/admin/lib/account-summary.ts @@ -0,0 +1,93 @@ +import type { BillingSubscription, Prisma } from '@generated/prisma/client'; +import type { AdminAccountListItem, AdminAccountQuery, Plan } from '@gruperly/shared'; +import { countryCodeSchema } from '@gruperly/shared'; +import { proSubscriptionWhere, resolvePlan } from '@/modules/billing/lib'; + +export type AccountRecord = { + id: string; + name: string; + email: string; + country: string | null; + createdAt: Date; + onboardingCompleted: boolean; + planSelectedAt: Date | null; + subscription: BillingSubscription | null; +}; + +export type AccountUsage = { groupsCount: number; attendeesCount: number }; + +export type PlanContext = { now: Date; graceDays: number }; + +/** Pro by its subscription; otherwise Free once chosen, `null` while not chosen. */ +export function accountPlan( + account: Pick, + { now, graceDays }: PlanContext, +): { plan: Plan | null; graceUntil: Date | null } { + const resolution = resolvePlan(account.subscription, now, graceDays); + if (resolution.plan === 'PRO') return resolution; + return { plan: account.planSelectedAt ? 'FREE' : null, graceUntil: null }; +} + +export function toAccountListItem( + account: AccountRecord, + usage: AccountUsage, + context: PlanContext, +): AdminAccountListItem { + const country = countryCodeSchema.safeParse(account.country); + const subscription = account.subscription; + return { + id: account.id, + name: account.name, + email: account.email, + country: country.success ? country.data : null, + createdAt: account.createdAt.toISOString(), + onboardingCompleted: account.onboardingCompleted, + plan: accountPlan(account, context).plan, + subscription: subscription + ? { + status: subscription.status, + amount: Number(subscription.amount.toString()), + currency: subscription.currency, + paidThrough: subscription.paidThrough?.toISOString() ?? null, + nextPaymentDate: + subscription.status === 'AUTHORIZED' + ? (subscription.nextPaymentDate?.toISOString() ?? null) + : null, + } + : null, + ...usage, + }; +} + +/** The list filters as a `user` query. The plan follows `accountPlan`. */ +export function buildAccountWhere( + query: Pick, + { now, graceDays }: PlanContext, +): Prisma.UserWhereInput { + const and: Prisma.UserWhereInput[] = []; + + if (query.search) { + and.push({ + OR: [ + { name: { contains: query.search, mode: 'insensitive' } }, + { email: { contains: query.search, mode: 'insensitive' } }, + ], + }); + } + if (query.country) and.push({ country: query.country }); + + if (query.subscriptionStatus === 'NONE') { + and.push({ subscription: { is: null } }); + } else if (query.subscriptionStatus) { + and.push({ subscription: { is: { status: query.subscriptionStatus } } }); + } + + if (query.plan) { + const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } }; + if (query.plan === 'PRO') and.push(isPro); + if (query.plan === 'FREE') and.push({ planSelectedAt: { not: null }, NOT: isPro }); + if (query.plan === 'NOT_SELECTED') and.push({ planSelectedAt: null, NOT: isPro }); + } + + return and.length > 0 ? { AND: and } : {}; +} diff --git a/apps/backend/src/modules/admin/lib/index.ts b/apps/backend/src/modules/admin/lib/index.ts new file mode 100644 index 0000000..08efd7f --- /dev/null +++ b/apps/backend/src/modules/admin/lib/index.ts @@ -0,0 +1,9 @@ +export { adminOnlyMiddleware, isAdminEmail } from './access'; +export { + type AccountRecord, + type AccountUsage, + accountPlan, + buildAccountWhere, + type PlanContext, + toAccountListItem, +} from './account-summary'; diff --git a/apps/backend/src/modules/admin/routes.ts b/apps/backend/src/modules/admin/routes.ts new file mode 100644 index 0000000..1abc5a9 --- /dev/null +++ b/apps/backend/src/modules/admin/routes.ts @@ -0,0 +1,17 @@ +import { Hono } from 'hono'; +import getAccountRoute from './features/get-account/route'; +import listAccountsRoute from './features/list-accounts/route'; +import meRoute from './features/me/route'; +import { adminOnlyMiddleware } from './lib'; + +const routes = new Hono(); + +routes.route('/', meRoute); + +// Everything below `/me` is the backoffice itself. +routes.use('/accounts', adminOnlyMiddleware()); +routes.use('/accounts/*', adminOnlyMiddleware()); +routes.route('/', listAccountsRoute); +routes.route('/', getAccountRoute); + +export default routes; diff --git a/apps/backend/src/modules/auth/auth.ts b/apps/backend/src/modules/auth/auth.ts index cb1d572..a9dc07a 100644 --- a/apps/backend/src/modules/auth/auth.ts +++ b/apps/backend/src/modules/auth/auth.ts @@ -14,6 +14,7 @@ export const auth = betterAuth({ emailAndPassword: { enabled: true, minPasswordLength: 8, + revokeSessionsOnPasswordReset: true, sendResetPassword: async ({ user, url }) => { await emailProvider.sendPasswordResetEmail({ email: user.email, diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts index dad8d30..1193ff2 100644 --- a/apps/backend/src/modules/billing/lib/entitlements.ts +++ b/apps/backend/src/modules/billing/lib/entitlements.ts @@ -1,4 +1,4 @@ -import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; +import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; import { @@ -53,6 +53,21 @@ export function resolvePlan( return { plan: 'FREE', graceUntil: null }; } +/** + * `resolvePlan` written as a query, for listing accounts by plan: a + * subscription is Pro when its paid period (or, before the first charge, its + * authorization) is younger than the grace period. Keep both in step. + */ +export function proSubscriptionWhere(now: Date, graceDays: number): Prisma.BillingSubscriptionWhereInput { + const cutoff = new Date(now.getTime() - graceDays * DAY_MS); + return { + OR: [ + { paidThrough: { gt: cutoff } }, + { paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } }, + ], + }; +} + export type PlanUsage = { groups: number; attendees: number }; export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean { diff --git a/apps/backend/src/modules/billing/lib/index.ts b/apps/backend/src/modules/billing/lib/index.ts index 2db0fa8..f0d9e7e 100644 --- a/apps/backend/src/modules/billing/lib/index.ts +++ b/apps/backend/src/modules/billing/lib/index.ts @@ -5,6 +5,7 @@ export { PlanGuard, type PlanResolution, type PlanUsage, + proSubscriptionWhere, resolvePlan, type SubscriptionSnapshot, } from './entitlements'; diff --git a/apps/backend/test/admin.test.ts b/apps/backend/test/admin.test.ts new file mode 100644 index 0000000..ab27bd9 --- /dev/null +++ b/apps/backend/test/admin.test.ts @@ -0,0 +1,315 @@ +import { afterAll, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + user: { findMany: mock(), count: mock(), findUnique: mock() }, + group: { findMany: mock() }, + billingCharge: { findMany: mock() }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class {}, +})); + +import { adminRoutes } from '@/modules/admin'; +import { GetAccount } from '@/modules/admin/features/get-account/use-case'; +import { ListAccounts } from '@/modules/admin/features/list-accounts/use-case'; +import { buildAccountWhere, isAdminEmail } from '@/modules/admin/lib'; + +const now = new Date('2026-10-22T12:00:00.000Z'); +const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000); +const context = { now, graceDays: 7 }; + +function subscription(overrides: Record = {}) { + return { + id: 'sub-1', + userId: 'u1', + country: 'AR', + currency: 'ARS', + amount: { toString: () => '15000' }, + payerEmail: 'pagos@ana.com', + mpPreapprovalId: 'pre-1', + status: 'AUTHORIZED', + requestedAt: days(-40), + authorizedAt: days(-40), + nextPaymentDate: days(20), + paidThrough: days(10), + lastSyncedAt: null, + createdAt: days(-40), + updatedAt: days(-1), + ...overrides, + }; +} + +function user(id: string, overrides: Record = {}) { + return { + id, + name: `Profe ${id}`, + email: `${id}@gruperly.test`, + country: 'AR', + createdAt: days(-60), + onboardingCompleted: true, + planSelectedAt: days(-60), + subscription: null, + ...overrides, + }; +} + +function makeApp(email: string | null) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', email ? ({ id: 'staff-1', email } as never) : null); + await next(); + }); + app.route('/admin', adminRoutes); + return app; +} + +const previousAdminEmails = process.env.ADMIN_EMAILS; + +beforeEach(() => { + process.env.ADMIN_EMAILS = 'staff@gruperly.com, Otra@Gruperly.com'; + db.user.findMany.mockReset(); + db.user.count.mockReset(); + db.user.findUnique.mockReset(); + db.group.findMany.mockReset(); + db.billingCharge.findMany.mockReset(); +}); + +afterAll(() => { + process.env.ADMIN_EMAILS = previousAdminEmails; +}); + +describe('admin access', () => { + it('matches the allowlist ignoring case and spaces', () => { + const env = { ADMIN_EMAILS: ' staff@gruperly.com ,Otra@Gruperly.com' }; + expect(isAdminEmail('STAFF@gruperly.com', env)).toBe(true); + expect(isAdminEmail('otra@gruperly.com', env)).toBe(true); + expect(isAdminEmail('profe@gmail.com', env)).toBe(false); + }); + + it('lets nobody in with an empty allowlist', () => { + expect(isAdminEmail('staff@gruperly.com', {})).toBe(false); + expect(isAdminEmail('', { ADMIN_EMAILS: ',' })).toBe(false); + }); + + it('tells any signed-in user whether they are an admin', async () => { + const admin = await makeApp('staff@gruperly.com').request('/admin/me'); + expect(await admin.json()).toEqual({ isAdmin: true }); + + const professor = await makeApp('profe@gmail.com').request('/admin/me'); + expect(professor.status).toBe(200); + expect(await professor.json()).toEqual({ isAdmin: false }); + }); + + it('forbids the accounts to anyone outside the allowlist', async () => { + const list = await makeApp('profe@gmail.com').request('/admin/accounts'); + expect(list.status).toBe(403); + expect(await list.json()).toMatchObject({ code: 'admin_required' }); + + const detail = await makeApp('profe@gmail.com').request('/admin/accounts/u1'); + expect(detail.status).toBe(403); + expect(db.user.findUnique).not.toHaveBeenCalled(); + }); + + it('asks for a session without a user', async () => { + const response = await makeApp(null).request('/admin/accounts'); + expect(response.status).toBe(401); + }); + + it('serves the list to an admin', async () => { + db.user.findMany.mockResolvedValue([]); + db.user.count.mockResolvedValue(0); + + const response = await makeApp('staff@gruperly.com').request('/admin/accounts?plan=PRO'); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ data: [], pagination: { total: 0 } }); + }); + + it('rejects an unknown filter', async () => { + const response = await makeApp('staff@gruperly.com').request('/admin/accounts?plan=GOLD'); + expect(response.status).toBe(400); + }); +}); + +describe('ListAccounts', () => { + it('adds up groups and ACTIVE attendees per owner and resolves the plan', async () => { + db.user.findMany.mockResolvedValue([ + user('pro', { subscription: subscription() }), + user('grace', { subscription: subscription({ paidThrough: days(-2), status: 'CANCELLED' }) }), + user('free'), + user('new', { planSelectedAt: null, country: null, onboardingCompleted: false }), + ]); + db.user.count.mockResolvedValue(4); + db.group.findMany.mockResolvedValue([ + { createdById: 'pro', _count: { attendees: 12 } }, + { createdById: 'pro', _count: { attendees: 8 } }, + { createdById: 'free', _count: { attendees: 5 } }, + ]); + + const result = await new ListAccounts({ db: db as never, graceDays: 7, now: () => now }).execute({ + page: 1, + pageSize: 20, + }); + + expect(result.ok).toBe(true); + if (!result.ok) return; + const [pro, grace, free, fresh] = result.value.data; + expect(pro).toMatchObject({ + plan: 'PRO', + groupsCount: 2, + attendeesCount: 20, + subscription: { status: 'AUTHORIZED', amount: 15000, currency: 'ARS' }, + }); + expect(grace).toMatchObject({ plan: 'PRO', subscription: { status: 'CANCELLED', nextPaymentDate: null } }); + expect(free).toMatchObject({ plan: 'FREE', subscription: null, groupsCount: 1, attendeesCount: 5 }); + expect(fresh).toMatchObject({ plan: null, country: null, groupsCount: 0, attendeesCount: 0 }); + expect(result.value.pagination).toEqual({ page: 1, pageSize: 20, total: 4, totalPages: 1 }); + + const groupQuery = db.group.findMany.mock.calls[0]?.[0]; + expect(groupQuery.where).toEqual({ createdById: { in: ['pro', 'grace', 'free', 'new'] } }); + }); + + it('skips the usage query on an empty page', async () => { + db.user.findMany.mockResolvedValue([]); + db.user.count.mockResolvedValue(0); + + await new ListAccounts({ db: db as never, graceDays: 7, now: () => now }).execute({ page: 3, pageSize: 20 }); + + expect(db.group.findMany).not.toHaveBeenCalled(); + expect(db.user.findMany.mock.calls[0]?.[0]).toMatchObject({ skip: 40, take: 20 }); + }); +}); + +describe('buildAccountWhere', () => { + const cutoff = days(-7); + const isPro = { + subscription: { + is: { + OR: [ + { paidThrough: { gt: cutoff } }, + { paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } }, + ], + }, + }, + }; + + it('is empty without filters', () => { + expect(buildAccountWhere({}, context)).toEqual({}); + }); + + it('searches name and email and filters by country', () => { + expect(buildAccountWhere({ search: 'ana', country: 'UY' }, context)).toEqual({ + AND: [ + { + OR: [ + { name: { contains: 'ana', mode: 'insensitive' } }, + { email: { contains: 'ana', mode: 'insensitive' } }, + ], + }, + { country: 'UY' }, + ], + }); + }); + + it('filters by subscription status, NONE meaning never subscribed', () => { + expect(buildAccountWhere({ subscriptionStatus: 'NONE' }, context)).toEqual({ + AND: [{ subscription: { is: null } }], + }); + expect(buildAccountWhere({ subscriptionStatus: 'PAUSED' }, context)).toEqual({ + AND: [{ subscription: { is: { status: 'PAUSED' } } }], + }); + }); + + it('writes the plan with the same grace period as resolvePlan', () => { + expect(buildAccountWhere({ plan: 'PRO' }, context)).toEqual({ AND: [isPro] }); + expect(buildAccountWhere({ plan: 'FREE' }, context)).toEqual({ + AND: [{ planSelectedAt: { not: null }, NOT: isPro }], + }); + expect(buildAccountWhere({ plan: 'NOT_SELECTED' }, context)).toEqual({ + AND: [{ planSelectedAt: null, NOT: isPro }], + }); + }); +}); + +describe('GetAccount', () => { + it('returns the account with its groups, links and charges', async () => { + db.user.findUnique.mockResolvedValue({ + ...user('u1', { subscription: subscription() }), + mpAccount: { status: 'ACTIVE' }, + whatsappAccount: null, + groupsOwner: [ + { id: 'g1', name: 'Yoga', createdAt: days(-30), _count: { attendees: 9 } }, + { id: 'g2', name: 'Pilates', createdAt: days(-50), _count: { attendees: 4 } }, + ], + }); + db.billingCharge.findMany.mockResolvedValue([ + { + id: 'c1', + subscriptionId: 'sub-1', + mpAuthorizedPaymentId: 'ap-1', + amount: { toString: () => '15000' }, + currency: 'ARS', + status: 'approved', + paidAt: days(-20), + createdAt: days(-20), + updatedAt: days(-20), + }, + ]); + + const result = await new GetAccount({ db: db as never, enforced: true, graceDays: 7, now: () => now }).execute( + 'u1', + ); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.value).toMatchObject({ + plan: 'PRO', + readOnly: false, + graceUntil: null, + groupsCount: 2, + attendeesCount: 13, + mpStatus: 'ACTIVE', + whatsappStatus: null, + subscription: { payerEmail: 'pagos@ana.com', status: 'AUTHORIZED' }, + groups: [{ id: 'g1', attendeesCount: 9 }, { id: 'g2', attendeesCount: 4 }], + charges: [{ id: 'c1', amount: 15000, status: 'approved' }], + }); + expect(db.billingCharge.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { subscription: { userId: 'u1' } } }); + }); + + it('flags a Free account over its limits as read-only when enforced', async () => { + db.user.findUnique.mockResolvedValue({ + ...user('u1'), + mpAccount: null, + whatsappAccount: null, + groupsOwner: [ + { id: 'g1', name: 'A', createdAt: days(-3), _count: { attendees: 1 } }, + { id: 'g2', name: 'B', createdAt: days(-2), _count: { attendees: 1 } }, + ], + }); + db.billingCharge.findMany.mockResolvedValue([]); + + const enforced = await new GetAccount({ db: db as never, enforced: true, graceDays: 7, now: () => now }).execute( + 'u1', + ); + expect(enforced.ok && enforced.value.readOnly).toBe(true); + + const notEnforced = await new GetAccount({ db: db as never, enforced: false, graceDays: 7, now: () => now }).execute( + 'u1', + ); + expect(notEnforced.ok && notEnforced.value.readOnly).toBe(false); + }); + + it('is 404 for an unknown account', async () => { + db.user.findUnique.mockResolvedValue(null); + + const result = await new GetAccount({ db: db as never }).execute('missing'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.status).toBe(404); + expect(db.billingCharge.findMany).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/layout/UserMenu.tsx b/apps/web/src/components/layout/UserMenu.tsx index adb7e41..ba6711b 100644 --- a/apps/web/src/components/layout/UserMenu.tsx +++ b/apps/web/src/components/layout/UserMenu.tsx @@ -1,11 +1,12 @@ import { useEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { Link, useNavigate } from '@tanstack/react-router' -import { ChevronDown, LogOut, Settings, UserRound, X } from 'lucide-react' +import { ChevronDown, LogOut, Settings, ShieldCheck, UserRound, X } from 'lucide-react' import { cn } from '../../lib/utils' import { signOut } from '../../lib/auth-client' import { useAuth } from '../../context/AuthProvider' import { useIsMobile } from '../../hooks/useIsMobile' +import { useAdminAccess } from '../../features/admin/useAdminAccess' import { Avatar } from '../ui' const itemClass = @@ -17,6 +18,8 @@ export function UserMenu() { const [open, setOpen] = useState(false) const ref = useRef(null) const navigate = useNavigate() + // Solo el equipo de Gruperly ve el acceso al backoffice. + const isAdmin = useAdminAccess(!!user).data?.isAdmin ?? false useEffect(() => { if (!open || isMobile) return @@ -124,6 +127,17 @@ export function UserMenu() { Ajustes + {isAdmin ? ( + setOpen(false)} + className={cn(itemClass, 'py-3.5')} + > + + Backoffice + + ) : null} + )} + + ) : null} + + {account ? : null} + + ) +} + +function AccountDetail({ account }: { account: AdminAccountDetail }) { + const subscription = account.subscription + const limits = PLAN_LIMITS[account.plan ?? 'FREE'] + + return ( +
+ + {countryLabel(account.country)} + {formatBillingDate(account.createdAt)} + {account.onboardingCompleted ? 'Completo' : 'Sin terminar'} + {MP_STATUS_LABELS[account.mpStatus ?? 'NONE']} + {WHATSAPP_STATUS_LABELS[account.whatsappStatus ?? 'NONE']} + + + + + + {planLabel(account.plan)} + {account.readOnly ? Solo lectura : null} + + + {formatBillingDate(account.planSelectedAt) ?? '—'} + + + {subscriptionStatusLabel(subscription?.status ?? null)} + + + {subscription ? ( + <> + {formatPrice(subscription.amount, subscription.currency)} / mes + {formatBillingDate(subscription.paidThrough) ?? '—'} + {formatBillingDate(subscription.nextPaymentDate) ?? '—'} + {subscription.payerEmail} + + ) : null} + {account.graceUntil ? ( + {formatBillingDate(account.graceUntil)} + ) : null} + + + + {formatUsage(account.groupsCount, limits.maxGroups)} + {formatUsage(account.attendeesCount, limits.maxAttendees)} + {account.groups.length > 0 ? ( +
    + {account.groups.map((group) => ( +
  • + {group.name} + + {group.attendeesCount} {group.attendeesCount === 1 ? 'alumno' : 'alumnos'} · desde{' '} + {formatBillingDate(group.createdAt)} + +
  • + ))} +
+ ) : ( +

Todavía no creó grupos.

+ )} +
+ + + {account.charges.length > 0 ? ( +
    + {account.charges.map((charge) => ( +
  • + + {formatBillingDate(charge.paidAt ?? charge.createdAt)} + + + + {formatPrice(charge.amount, charge.currency)} + + {charge.status} + +
  • + ))} +
+ ) : ( +

Sin cobros registrados.

+ )} +
+
+ ) +} + +function Card({ title, children }: { title: string; children: ReactNode }) { + return ( +
+

{title}

+
{children}
+
+ ) +} + +function Field({ label, children }: { label: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ) +} diff --git a/apps/web/src/features/admin/AdminAccountRow.tsx b/apps/web/src/features/admin/AdminAccountRow.tsx new file mode 100644 index 0000000..a02b64b --- /dev/null +++ b/apps/web/src/features/admin/AdminAccountRow.tsx @@ -0,0 +1,72 @@ +import type { AdminAccountListItem } from '@gruperly/shared' +import { Link } from '@tanstack/react-router' +import { ChevronRight } from 'lucide-react' +import { Badge } from '../../components/ui' +import { formatPrice } from '../../lib/format' +import { formatBillingDate, subscriptionStatusLabel } from '../billing' +import { countryLabel, planLabel, planVariant, subscriptionVariant } from './copy' + +/** Columnas de la grilla en `lg+`; el encabezado de `AdminAccountsView` usa las mismas. */ +export const ACCOUNT_GRID_COLUMNS = + 'lg:grid-cols-[minmax(0,2.2fr)_minmax(0,1fr)_minmax(0,0.8fr)_minmax(0,1.6fr)_4.5rem_4.5rem_1rem]' + +/* Una cuenta de la lista: tarjeta en móvil, fila de la grilla en escritorio. */ +export function AdminAccountRow({ account }: { account: AdminAccountListItem }) { + const subscription = account.subscription + const status = subscription?.status ?? null + const paidThrough = formatBillingDate(subscription?.paidThrough ?? null) + const planBadge = {planLabel(account.plan)} + const statusBadge = {subscriptionStatusLabel(status)} + + return ( +
  • + + {/* Móvil */} +
    +
    +
    +

    {account.name}

    +

    {account.email}

    +
    +
    +
    + {planBadge} + {statusBadge} +
    +

    + {countryLabel(account.country)} · {account.groupsCount}{' '} + {account.groupsCount === 1 ? 'grupo' : 'grupos'} · {account.attendeesCount}{' '} + {account.attendeesCount === 1 ? 'alumno' : 'alumnos'} +

    +
    + + {/* Escritorio */} +
    +
    +

    {account.name}

    +

    {account.email}

    +
    +

    {countryLabel(account.country)}

    +
    {planBadge}
    +
    + {statusBadge} + {subscription ? ( +

    + {formatPrice(subscription.amount, subscription.currency)} + {paidThrough ? ` · hasta ${paidThrough}` : ''} +

    + ) : null} +
    +

    {account.groupsCount}

    +

    {account.attendeesCount}

    +
    + +
  • + ) +} diff --git a/apps/web/src/features/admin/AdminAccountsProvider.tsx b/apps/web/src/features/admin/AdminAccountsProvider.tsx new file mode 100644 index 0000000..0e62b93 --- /dev/null +++ b/apps/web/src/features/admin/AdminAccountsProvider.tsx @@ -0,0 +1,123 @@ +import type { + AdminAccountListItem, + AdminAccountQueryInput, + AdminPlanFilter, + AdminSubscriptionFilter, + CountryCode, +} from '@gruperly/shared' +import { useQuery } from '@tanstack/react-query' +import type { ReactNode } from 'react' +import { createContext, useContext, useEffect, useMemo, useState } from 'react' +import { ApiError, getAdminAccounts } from '../../lib/api' + +const PAGE_SIZE = 20 +const SEARCH_DEBOUNCE_MS = 300 + +type AdminAccountsContextValue = { + accounts: AdminAccountListItem[] + total: number + page: number + totalPages: number + isPending: boolean + isFetching: boolean + isError: boolean + errorMessage: string | null + search: string + setSearch: (search: string) => void + country: CountryCode | null + setCountry: (country: CountryCode | null) => void + plan: AdminPlanFilter | null + setPlan: (plan: AdminPlanFilter | null) => void + subscriptionStatus: AdminSubscriptionFilter | null + setSubscriptionStatus: (status: AdminSubscriptionFilter | null) => void + setPage: (page: number) => void + retry: () => void +} + +const AdminAccountsContext = createContext(null) + +export function AdminAccountsProvider({ children }: { children: ReactNode }) { + const [page, setPage] = useState(1) + const [search, setSearch] = useState('') + const [debouncedSearch, setDebouncedSearch] = useState('') + const [country, setCountry] = useState(null) + const [plan, setPlan] = useState(null) + const [subscriptionStatus, setSubscriptionStatus] = useState(null) + + // La búsqueda espera a que se deje de tipear para no pedir una página por tecla. + useEffect(() => { + const timeout = setTimeout(() => { + setDebouncedSearch(search.trim()) + setPage(1) + }, SEARCH_DEBOUNCE_MS) + return () => clearTimeout(timeout) + }, [search]) + + const params = useMemo( + () => ({ + page, + pageSize: PAGE_SIZE, + search: debouncedSearch || undefined, + country: country ?? undefined, + plan: plan ?? undefined, + subscriptionStatus: subscriptionStatus ?? undefined, + }), + [page, debouncedSearch, country, plan, subscriptionStatus], + ) + + const accountsQuery = useQuery({ + queryKey: ['admin', 'accounts', params], + queryFn: () => getAdminAccounts(params), + placeholderData: (previous) => previous, + }) + + const data = accountsQuery.data + const errorMessage = accountsQuery.isError + ? accountsQuery.error instanceof ApiError + ? (accountsQuery.error.problem?.detail ?? 'No pudimos cargar las cuentas.') + : 'No pudimos cargar las cuentas.' + : null + + // Cambiar un filtro vuelve a la primera página. + const withFirstPage = + (setter: (value: T) => void) => + (value: T) => { + setter(value) + setPage(1) + } + + return ( + void accountsQuery.refetch(), + }} + > + {children} + + ) +} + +export function useAdminAccounts() { + const context = useContext(AdminAccountsContext) + if (!context) { + throw new Error('useAdminAccounts debe usarse dentro de ') + } + return context +} diff --git a/apps/web/src/features/admin/AdminAccountsView.tsx b/apps/web/src/features/admin/AdminAccountsView.tsx new file mode 100644 index 0000000..34479cb --- /dev/null +++ b/apps/web/src/features/admin/AdminAccountsView.tsx @@ -0,0 +1,198 @@ +import type { AdminPlanFilter, AdminSubscriptionFilter, CountryCode } from '@gruperly/shared' +import { ChevronLeft, ChevronRight, Loader2, Search, Users } from 'lucide-react' +import { Button, Input } from '../../components/ui' +import { cn } from '../../lib/utils' +import { ACCOUNT_GRID_COLUMNS, AdminAccountRow } from './AdminAccountRow' +import { useAdminAccounts } from './AdminAccountsProvider' +import { COUNTRY_OPTIONS, PLAN_FILTER_OPTIONS, SUBSCRIPTION_FILTER_OPTIONS } from './copy' + +const selectClass = + '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' + +export function AdminAccountsView() { + const { + accounts, + total, + page, + totalPages, + isPending, + isFetching, + isError, + errorMessage, + search, + setSearch, + country, + setCountry, + plan, + setPlan, + subscriptionStatus, + setSubscriptionStatus, + setPage, + retry, + } = useAdminAccounts() + + const hasFilters = !!search.trim() || !!country || !!plan || !!subscriptionStatus + + return ( +
    +
    +

    Cuentas

    +

    + Profesores que usan Gruperly, con su plan y su uso. +

    +
    + +
    + + + + + + + +
    + + {isPending ? ( +
    +
    + ) : null} + + {isError ? ( +
    +

    {errorMessage}

    + +
    + ) : null} + + {!isPending && !isError && accounts.length === 0 ? ( +
    + + +

    + {hasFilters ? 'Ninguna cuenta coincide' : 'Todavía no hay cuentas'} +

    + {hasFilters ? ( +

    + Probá con otra búsqueda o sacá algún filtro. +

    + ) : null} +
    + ) : null} + + {!isPending && !isError && accounts.length > 0 ? ( + <> +
    +
    + Cuenta + País + Plan + Suscripción + Grupos + Alumnos + +
    +
      + {accounts.map((account) => ( + + ))} +
    +
    + +
    + +

    + Página {page} de {totalPages} · {total} {total === 1 ? 'cuenta' : 'cuentas'} +

    + +
    + + ) : null} +
    + ) +} diff --git a/apps/web/src/features/admin/AdminGuard.tsx b/apps/web/src/features/admin/AdminGuard.tsx new file mode 100644 index 0000000..f31bb11 --- /dev/null +++ b/apps/web/src/features/admin/AdminGuard.tsx @@ -0,0 +1,61 @@ +import { useEffect } from 'react' +import type { ReactNode } from 'react' +import { Link, useNavigate } from '@tanstack/react-router' +import { Loader2, ShieldOff } from 'lucide-react' +import { Button } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { AdminLayout } from './AdminLayout' +import { useAdminAccess } from './useAdminAccess' + +/* El backoffice cuelga de la raíz y no de `_authenticated`: un admin no tiene + por qué completar el onboarding de profesor. La sesión y el permiso se + chequean acá; el backend vuelve a chequear el permiso en cada pedido. */ +export function AdminGuard({ children }: { children: ReactNode }) { + const { user, isPending } = useAuth() + const navigate = useNavigate() + const access = useAdminAccess(!!user) + + useEffect(() => { + if (!isPending && !user) void navigate({ to: '/login', replace: true }) + }, [isPending, user, navigate]) + + if (isPending || !user || access.isPending) { + return ( +
    + +
    + ) + } + + if (access.isError) { + return ( +
    +

    No pudimos verificar tu acceso al backoffice.

    + +
    + ) + } + + if (!access.data?.isAdmin) { + return ( +
    + + +
    +

    No tenés acceso

    +

    + El backoffice es solo para el equipo de Gruperly. +

    +
    + + Ir a la app + +
    + ) + } + + return {children} +} diff --git a/apps/web/src/features/admin/AdminLayout.tsx b/apps/web/src/features/admin/AdminLayout.tsx new file mode 100644 index 0000000..cfc54ea --- /dev/null +++ b/apps/web/src/features/admin/AdminLayout.tsx @@ -0,0 +1,33 @@ +import type { ReactNode } from 'react' +import { Link } from '@tanstack/react-router' +import { ArrowLeft } from 'lucide-react' +import { ThemeToggle } from '../../components/layout/ThemeToggle' + +/* Layout propio del backoffice: sin la navegación del profesor y pensado para + escritorio, aunque en móvil se lee igual (columna única). */ +export function AdminLayout({ children }: { children: ReactNode }) { + return ( +
    +
    +
    + + Gruperly · Backoffice + +
    + + +
    +
    +
    +
    + {children} +
    +
    + ) +} diff --git a/apps/web/src/features/admin/copy.ts b/apps/web/src/features/admin/copy.ts new file mode 100644 index 0000000..a86af9d --- /dev/null +++ b/apps/web/src/features/admin/copy.ts @@ -0,0 +1,75 @@ +import type { + AdminAccountDetail, + AdminPlanFilter, + AdminSubscriptionFilter, + CountryCode, + Plan, + SubscriptionStatus, +} from '@gruperly/shared' +import { COUNTRY_LABELS } from '@gruperly/shared' +import type { BadgeVariant } from '../../components/ui' +import { PLAN_NAMES, subscriptionStatusLabel } from '../billing' + +/* Copy del backoffice. Los nombres de plan y de estado de suscripción salen de + billing, así el equipo ve lo mismo que el profesor en su pantalla del plan. */ + +export const PLAN_FILTER_OPTIONS: readonly { value: AdminPlanFilter; label: string }[] = [ + { value: 'PRO', label: PLAN_NAMES.PRO }, + { value: 'FREE', label: PLAN_NAMES.FREE }, + { value: 'NOT_SELECTED', label: 'Sin elegir' }, +] + +export const SUBSCRIPTION_FILTER_OPTIONS: readonly { value: AdminSubscriptionFilter; label: string }[] = [ + { value: 'AUTHORIZED', label: subscriptionStatusLabel('AUTHORIZED') }, + { value: 'PENDING', label: subscriptionStatusLabel('PENDING') }, + { value: 'PAUSED', label: subscriptionStatusLabel('PAUSED') }, + { value: 'CANCELLED', label: subscriptionStatusLabel('CANCELLED') }, + { value: 'NONE', label: subscriptionStatusLabel(null) }, +] + +export const COUNTRY_OPTIONS = (Object.keys(COUNTRY_LABELS) as CountryCode[]).map((code) => ({ + value: code, + label: COUNTRY_LABELS[code], +})) + +export function countryLabel(country: CountryCode | null): string { + return country ? COUNTRY_LABELS[country] : 'Sin país' +} + +export function planLabel(plan: Plan | null): string { + return plan ? PLAN_NAMES[plan] : 'Sin elegir' +} + +export function planVariant(plan: Plan | null): BadgeVariant { + if (plan === 'PRO') return 'success' + return plan === 'FREE' ? 'neutral' : 'warning' +} + +export function subscriptionVariant(status: SubscriptionStatus | null): BadgeVariant { + switch (status) { + case 'AUTHORIZED': + return 'success' + case 'PENDING': + return 'info' + case 'PAUSED': + return 'warning' + case 'CANCELLED': + return 'danger' + default: + return 'neutral' + } +} + +export const MP_STATUS_LABELS: Record | 'NONE', string> = { + ACTIVE: 'Vinculada', + REQUIRES_REAUTH: 'Requiere volver a vincular', + REVOKED: 'Desvinculada', + NONE: 'Sin vincular', +} + +export const WHATSAPP_STATUS_LABELS: Record | 'NONE', string> = { + ACTIVE: 'Conectado', + PENDING: 'Conectando', + DISCONNECTED: 'Desconectado', + NONE: 'Sin conectar', +} diff --git a/apps/web/src/features/admin/useAdminAccess.ts b/apps/web/src/features/admin/useAdminAccess.ts new file mode 100644 index 0000000..953fa4e --- /dev/null +++ b/apps/web/src/features/admin/useAdminAccess.ts @@ -0,0 +1,12 @@ +import { useQuery } from '@tanstack/react-query' +import { getAdminMe } from '../../lib/api' + +/** Si el usuario es del equipo de Gruperly. La comparten el guard del backoffice y el menú. */ +export function useAdminAccess(enabled = true) { + return useQuery({ + queryKey: ['admin', 'me'], + queryFn: getAdminMe, + enabled, + staleTime: 10 * 60 * 1000, + }) +} diff --git a/apps/web/src/features/auth/ForgotPasswordPage.tsx b/apps/web/src/features/auth/ForgotPasswordPage.tsx new file mode 100644 index 0000000..a6408ed --- /dev/null +++ b/apps/web/src/features/auth/ForgotPasswordPage.tsx @@ -0,0 +1,95 @@ +import { useState } from 'react' +import { useForm } from 'react-hook-form' +import { z } from 'zod' +import { zodResolver } from '@hookform/resolvers/zod' +import { Link, useSearch } from '@tanstack/react-router' +import { Loader2, MailCheck } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button, Input, Label } from '../../components/ui' +import { AuthShell } from './AuthShell' + +const schema = z.object({ + email: z.string().email('Ingresá un email válido'), +}) + +type FormValues = z.infer + +export function ForgotPasswordPage() { + const { email: initialEmail } = useSearch({ strict: false }) as { email?: string } + const [sentTo, setSentTo] = useState(null) + const { + register, + handleSubmit, + setError, + formState: { errors, isSubmitting }, + } = useForm({ + resolver: zodResolver(schema), + defaultValues: { email: initialEmail ?? '' }, + }) + + const onSubmit = handleSubmit(async ({ email }) => { + // Absoluto: un redirectTo relativo Better Auth lo resuelve contra la URL de la API + const { error } = await authClient.requestPasswordReset({ + email, + redirectTo: `${window.location.origin}/reset-password`, + }) + if (error) { + setError('root', { message: error.message ?? 'No se pudo enviar el email' }) + return + } + setSentTo(email) + }) + + if (sentTo) { + return ( + +
    + +

    + Si hay una cuenta con {sentTo}, te + enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora. +

    + + Volver a iniciar sesión + +
    +
    + ) + } + + return ( + +
    +
    + + + {errors.email ?

    {errors.email.message}

    : null} +
    + + {errors.root ?

    {errors.root.message}

    : null} + + + +

    + + Volver a iniciar sesión + +

    +
    +
    + ) +} diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx index 1d76073..1fe14ba 100644 --- a/apps/web/src/features/auth/LoginPage.tsx +++ b/apps/web/src/features/auth/LoginPage.tsx @@ -1,7 +1,7 @@ import { useForm } from 'react-hook-form' import { z } from 'zod' import { zodResolver } from '@hookform/resolvers/zod' -import { Link, useNavigate } from '@tanstack/react-router' +import { Link, useNavigate, useSearch } from '@tanstack/react-router' import { Fingerprint, Loader2 } from 'lucide-react' import { authClient } from '../../lib/auth-client' import { Button, Input, Label } from '../../components/ui' @@ -16,10 +16,12 @@ type FormValues = z.infer export function LoginPage() { const navigate = useNavigate() + const { reset } = useSearch({ strict: false }) as { reset?: 'ok' } const { register, handleSubmit, setError, + watch, formState: { errors, isSubmitting }, } = useForm({ resolver: zodResolver(schema) }) @@ -48,6 +50,12 @@ export function LoginPage() { return (
    + {reset === 'ok' ? ( +

    + Tu contraseña se actualizó. Ingresá con la nueva. +

    + ) : null} +
    @@ -75,6 +83,15 @@ export function LoginPage() { {errors.password ? (

    {errors.password.message}

    ) : null} +
    + + ¿Olvidaste tu contraseña? + +
    {errors.root ?

    {errors.root.message}

    : null} diff --git a/apps/web/src/features/auth/ResetPasswordPage.tsx b/apps/web/src/features/auth/ResetPasswordPage.tsx new file mode 100644 index 0000000..51ffc1b --- /dev/null +++ b/apps/web/src/features/auth/ResetPasswordPage.tsx @@ -0,0 +1,107 @@ +import { useState } from 'react' +import { useForm } from 'react-hook-form' +import { z } from 'zod' +import { zodResolver } from '@hookform/resolvers/zod' +import { Link, useNavigate, useSearch } from '@tanstack/react-router' +import { Loader2, MailWarning } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button, Input, Label } from '../../components/ui' +import { AuthShell } from './AuthShell' + +const schema = z + .object({ + newPassword: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'), + confirmPassword: z.string(), + }) + .refine((v) => v.newPassword === v.confirmPassword, { + message: 'Las contraseñas no coinciden', + path: ['confirmPassword'], + }) + +type FormValues = z.infer + +export function ResetPasswordPage() { + const { token, error } = useSearch({ strict: false }) as { token?: string; error?: string } + const navigate = useNavigate() + const [invalidLink, setInvalidLink] = useState(!token || !!error) + const { + register, + handleSubmit, + setError, + formState: { errors, isSubmitting }, + } = useForm({ resolver: zodResolver(schema) }) + + const onSubmit = handleSubmit(async ({ newPassword }) => { + if (!token) return + const { error } = await authClient.resetPassword({ newPassword, token }) + if (error) { + if (error.code === 'INVALID_TOKEN') { + setInvalidLink(true) + return + } + setError('root', { message: error.message ?? 'No se pudo cambiar la contraseña' }) + return + } + navigate({ to: '/login', search: { reset: 'ok' } }) + }) + + if (invalidLink) { + return ( + +
    + +

    + El enlace para restablecer la contraseña no es válido o venció. +

    + + Pedir un enlace nuevo + +
    +
    + ) + } + + return ( + + +
    + + + {errors.newPassword ? ( +

    {errors.newPassword.message}

    + ) : null} +
    + +
    + + + {errors.confirmPassword ? ( +

    {errors.confirmPassword.message}

    + ) : null} +
    + + {errors.root ?

    {errors.root.message}

    : null} + + + +
    + ) +} diff --git a/apps/web/src/features/billing/index.ts b/apps/web/src/features/billing/index.ts index 0fe0bd0..4072182 100644 --- a/apps/web/src/features/billing/index.ts +++ b/apps/web/src/features/billing/index.ts @@ -1,5 +1,6 @@ export { formatBillingDate, + formatUsage, hasPlanFeature, isPlanProblem, PLAN_FEATURE_REQUIRED_MESSAGES, diff --git a/apps/web/src/features/onboarding/Stepper.tsx b/apps/web/src/features/onboarding/Stepper.tsx index 491d4d3..fda8c9a 100644 --- a/apps/web/src/features/onboarding/Stepper.tsx +++ b/apps/web/src/features/onboarding/Stepper.tsx @@ -35,7 +35,9 @@ export function Stepper({ steps, current }: StepperProps) { diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 2e467b9..f71a717 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -1,5 +1,9 @@ import type { AbsenceDetails, + AdminAccountDetail, + AdminAccountList, + AdminAccountQueryInput, + AdminMeDto, ApproveGroupPreRegistrationResult, AttendeeDetailDto, AttendeeDto, @@ -383,3 +387,18 @@ export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) method: 'POST', body: JSON.stringify({ status }), }) + +// — Backoffice (equipo de Gruperly) — + +export const getAdminMe = () => apiFetch('/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(`/api/v1/admin/accounts?${query.toString()}`) +} + +export const getAdminAccount = (accountId: string) => + apiFetch(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`) diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index d28ec83..f454893 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -10,8 +10,11 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as AuthenticatedRouteImport } from './routes/_authenticated' +import { Route as AdminRouteImport } from './routes/admin' +import { Route as ForgotPasswordRouteImport } from './routes/forgot-password' import { Route as LoginRouteImport } from './routes/login' import { Route as OnboardingRouteImport } from './routes/onboarding' +import { Route as ResetPasswordRouteImport } from './routes/reset-password' import { Route as SignupRouteImport } from './routes/signup' import { Route as VerifyEmailRouteImport } from './routes/verify-email' import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index' @@ -20,10 +23,12 @@ import { Route as AuthenticatedPaymentsRouteImport } from './routes/_authenticat import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile' import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticated/security' import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings' +import { Route as AdminIndexRouteImport } from './routes/admin/index' import { Route as JoinTokenRouteImport } from './routes/join.$token' import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token' import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index' import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new' +import { Route as AdminAccountsAccountIdRouteImport } from './routes/admin/accounts.$accountId' import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance' import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index' import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics' @@ -34,6 +39,16 @@ const AuthenticatedRoute = AuthenticatedRouteImport.update({ id: '/_authenticated', getParentRoute: () => rootRouteImport, } as any) +const AdminRoute = AdminRouteImport.update({ + id: '/admin', + path: '/admin', + getParentRoute: () => rootRouteImport, +} as any) +const ForgotPasswordRoute = ForgotPasswordRouteImport.update({ + id: '/forgot-password', + path: '/forgot-password', + getParentRoute: () => rootRouteImport, +} as any) const LoginRoute = LoginRouteImport.update({ id: '/login', path: '/login', @@ -44,6 +59,11 @@ const OnboardingRoute = OnboardingRouteImport.update({ path: '/onboarding', getParentRoute: () => rootRouteImport, } as any) +const ResetPasswordRoute = ResetPasswordRouteImport.update({ + id: '/reset-password', + path: '/reset-password', + getParentRoute: () => rootRouteImport, +} as any) const SignupRoute = SignupRouteImport.update({ id: '/signup', path: '/signup', @@ -84,6 +104,11 @@ const AuthenticatedSettingsRoute = AuthenticatedSettingsRouteImport.update({ path: '/settings', getParentRoute: () => AuthenticatedRoute, } as any) +const AdminIndexRoute = AdminIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => AdminRoute, +} as any) const JoinTokenRoute = JoinTokenRouteImport.update({ id: '/join/$token', path: '/join/$token', @@ -105,6 +130,11 @@ const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({ path: '/groups/new', getParentRoute: () => AuthenticatedRoute, } as any) +const AdminAccountsAccountIdRoute = AdminAccountsAccountIdRouteImport.update({ + id: '/accounts/$accountId', + path: '/accounts/$accountId', + getParentRoute: () => AdminRoute, +} as any) const AuthenticatedClassSessionIdAttendanceRoute = AuthenticatedClassSessionIdAttendanceRouteImport.update({ id: '/class/$sessionId/attendance', @@ -138,8 +168,11 @@ const AuthenticatedGroupsGroupIdAttendeesNewRoute = export interface FileRoutesByFullPath { '/': typeof AuthenticatedIndexRoute + '/admin': typeof AdminRouteWithChildren + '/forgot-password': typeof ForgotPasswordRoute '/login': typeof LoginRoute '/onboarding': typeof OnboardingRoute + '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute '/billing': typeof AuthenticatedBillingRoute @@ -149,7 +182,9 @@ export interface FileRoutesByFullPath { '/settings': typeof AuthenticatedSettingsRoute '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute + '/admin/': typeof AdminIndexRoute '/groups/new': typeof AuthenticatedGroupsNewRoute + '/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute '/groups/': typeof AuthenticatedGroupsIndexRoute '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute @@ -158,8 +193,10 @@ export interface FileRoutesByFullPath { '/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute } export interface FileRoutesByTo { + '/forgot-password': typeof ForgotPasswordRoute '/login': typeof LoginRoute '/onboarding': typeof OnboardingRoute + '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute '/billing': typeof AuthenticatedBillingRoute @@ -170,7 +207,9 @@ export interface FileRoutesByTo { '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute '/': typeof AuthenticatedIndexRoute + '/admin': typeof AdminIndexRoute '/groups/new': typeof AuthenticatedGroupsNewRoute + '/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute '/groups': typeof AuthenticatedGroupsIndexRoute '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute @@ -181,8 +220,11 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/_authenticated': typeof AuthenticatedRouteWithChildren + '/admin': typeof AdminRouteWithChildren + '/forgot-password': typeof ForgotPasswordRoute '/login': typeof LoginRoute '/onboarding': typeof OnboardingRoute + '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/verify-email': typeof VerifyEmailRoute '/_authenticated/billing': typeof AuthenticatedBillingRoute @@ -193,7 +235,9 @@ export interface FileRoutesById { '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute '/_authenticated/': typeof AuthenticatedIndexRoute + '/admin/': typeof AdminIndexRoute '/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute + '/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute '/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute '/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute '/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute @@ -205,8 +249,11 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/admin' + | '/forgot-password' | '/login' | '/onboarding' + | '/reset-password' | '/signup' | '/verify-email' | '/billing' @@ -216,7 +263,9 @@ export interface FileRouteTypes { | '/settings' | '/join/$token' | '/report-absence/$token' + | '/admin/' | '/groups/new' + | '/admin/accounts/$accountId' | '/groups/' | '/class/$sessionId/attendance' | '/groups/$groupId/analytics' @@ -225,8 +274,10 @@ export interface FileRouteTypes { | '/groups/$groupId/attendees/new' fileRoutesByTo: FileRoutesByTo to: + | '/forgot-password' | '/login' | '/onboarding' + | '/reset-password' | '/signup' | '/verify-email' | '/billing' @@ -237,7 +288,9 @@ export interface FileRouteTypes { | '/join/$token' | '/report-absence/$token' | '/' + | '/admin' | '/groups/new' + | '/admin/accounts/$accountId' | '/groups' | '/class/$sessionId/attendance' | '/groups/$groupId/analytics' @@ -247,8 +300,11 @@ export interface FileRouteTypes { id: | '__root__' | '/_authenticated' + | '/admin' + | '/forgot-password' | '/login' | '/onboarding' + | '/reset-password' | '/signup' | '/verify-email' | '/_authenticated/billing' @@ -259,7 +315,9 @@ export interface FileRouteTypes { | '/join/$token' | '/report-absence/$token' | '/_authenticated/' + | '/admin/' | '/_authenticated/groups/new' + | '/admin/accounts/$accountId' | '/_authenticated/groups/' | '/_authenticated/class/$sessionId/attendance' | '/_authenticated/groups/$groupId/analytics' @@ -270,8 +328,11 @@ export interface FileRouteTypes { } export interface RootRouteChildren { AuthenticatedRoute: typeof AuthenticatedRouteWithChildren + AdminRoute: typeof AdminRouteWithChildren + ForgotPasswordRoute: typeof ForgotPasswordRoute LoginRoute: typeof LoginRoute OnboardingRoute: typeof OnboardingRoute + ResetPasswordRoute: typeof ResetPasswordRoute SignupRoute: typeof SignupRoute VerifyEmailRoute: typeof VerifyEmailRoute JoinTokenRoute: typeof JoinTokenRoute @@ -287,6 +348,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedRouteImport parentRoute: typeof rootRouteImport } + '/admin': { + id: '/admin' + path: '/admin' + fullPath: '/admin' + preLoaderRoute: typeof AdminRouteImport + parentRoute: typeof rootRouteImport + } + '/forgot-password': { + id: '/forgot-password' + path: '/forgot-password' + fullPath: '/forgot-password' + preLoaderRoute: typeof ForgotPasswordRouteImport + parentRoute: typeof rootRouteImport + } '/login': { id: '/login' path: '/login' @@ -301,6 +376,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof OnboardingRouteImport parentRoute: typeof rootRouteImport } + '/reset-password': { + id: '/reset-password' + path: '/reset-password' + fullPath: '/reset-password' + preLoaderRoute: typeof ResetPasswordRouteImport + parentRoute: typeof rootRouteImport + } '/signup': { id: '/signup' path: '/signup' @@ -357,6 +439,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedSettingsRouteImport parentRoute: typeof AuthenticatedRoute } + '/admin/': { + id: '/admin/' + path: '/' + fullPath: '/admin/' + preLoaderRoute: typeof AdminIndexRouteImport + parentRoute: typeof AdminRoute + } '/join/$token': { id: '/join/$token' path: '/join/$token' @@ -385,6 +474,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedGroupsNewRouteImport parentRoute: typeof AuthenticatedRoute } + '/admin/accounts/$accountId': { + id: '/admin/accounts/$accountId' + path: '/accounts/$accountId' + fullPath: '/admin/accounts/$accountId' + preLoaderRoute: typeof AdminAccountsAccountIdRouteImport + parentRoute: typeof AdminRoute + } '/_authenticated/class/$sessionId/attendance': { id: '/_authenticated/class/$sessionId/attendance' path: '/class/$sessionId/attendance' @@ -463,10 +559,25 @@ const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren( AuthenticatedRouteChildren, ) +interface AdminRouteChildren { + AdminIndexRoute: typeof AdminIndexRoute + AdminAccountsAccountIdRoute: typeof AdminAccountsAccountIdRoute +} + +const AdminRouteChildren: AdminRouteChildren = { + AdminIndexRoute: AdminIndexRoute, + AdminAccountsAccountIdRoute: AdminAccountsAccountIdRoute, +} + +const AdminRouteWithChildren = AdminRoute._addFileChildren(AdminRouteChildren) + const rootRouteChildren: RootRouteChildren = { AuthenticatedRoute: AuthenticatedRouteWithChildren, + AdminRoute: AdminRouteWithChildren, + ForgotPasswordRoute: ForgotPasswordRoute, LoginRoute: LoginRoute, OnboardingRoute: OnboardingRoute, + ResetPasswordRoute: ResetPasswordRoute, SignupRoute: SignupRoute, VerifyEmailRoute: VerifyEmailRoute, JoinTokenRoute: JoinTokenRoute, diff --git a/apps/web/src/routes/admin.tsx b/apps/web/src/routes/admin.tsx new file mode 100644 index 0000000..9c09929 --- /dev/null +++ b/apps/web/src/routes/admin.tsx @@ -0,0 +1,10 @@ +import { createFileRoute, Outlet } from '@tanstack/react-router' +import { AdminGuard } from '../features/admin/AdminGuard' + +export const Route = createFileRoute('/admin')({ + component: () => ( + + + + ), +}) diff --git a/apps/web/src/routes/admin/accounts.$accountId.tsx b/apps/web/src/routes/admin/accounts.$accountId.tsx new file mode 100644 index 0000000..6b92f72 --- /dev/null +++ b/apps/web/src/routes/admin/accounts.$accountId.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, useParams } from '@tanstack/react-router' +import { AdminAccountDetailProvider } from '../../features/admin/AdminAccountDetailProvider' +import { AdminAccountDetailView } from '../../features/admin/AdminAccountDetailView' + +export const Route = createFileRoute('/admin/accounts/$accountId')({ + component: () => { + const { accountId } = useParams({ from: '/admin/accounts/$accountId' }) + return ( + + + + ) + }, +}) diff --git a/apps/web/src/routes/admin/index.tsx b/apps/web/src/routes/admin/index.tsx new file mode 100644 index 0000000..eca31f6 --- /dev/null +++ b/apps/web/src/routes/admin/index.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { AdminAccountsProvider } from '../../features/admin/AdminAccountsProvider' +import { AdminAccountsView } from '../../features/admin/AdminAccountsView' + +export const Route = createFileRoute('/admin/')({ + component: () => ( + + + + ), +}) diff --git a/apps/web/src/routes/forgot-password.tsx b/apps/web/src/routes/forgot-password.tsx new file mode 100644 index 0000000..1ef4783 --- /dev/null +++ b/apps/web/src/routes/forgot-password.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { ForgotPasswordPage } from '../features/auth/ForgotPasswordPage' + +export const Route = createFileRoute('/forgot-password')({ + validateSearch: (search: Record): { email?: string } => ({ + email: typeof search.email === 'string' ? search.email : undefined, + }), + component: ForgotPasswordPage, +}) diff --git a/apps/web/src/routes/login.tsx b/apps/web/src/routes/login.tsx index 649bea8..33bb93f 100644 --- a/apps/web/src/routes/login.tsx +++ b/apps/web/src/routes/login.tsx @@ -2,5 +2,8 @@ import { createFileRoute } from '@tanstack/react-router' import { LoginPage } from '../features/auth/LoginPage' export const Route = createFileRoute('/login')({ + validateSearch: (search: Record): { reset?: 'ok' } => ({ + reset: search.reset === 'ok' ? 'ok' : undefined, + }), component: LoginPage, }) diff --git a/apps/web/src/routes/reset-password.tsx b/apps/web/src/routes/reset-password.tsx new file mode 100644 index 0000000..ccf952d --- /dev/null +++ b/apps/web/src/routes/reset-password.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { ResetPasswordPage } from '../features/auth/ResetPasswordPage' + +export const Route = createFileRoute('/reset-password')({ + validateSearch: (search: Record): { token?: string; error?: string } => ({ + token: typeof search.token === 'string' ? search.token : undefined, + error: typeof search.error === 'string' ? search.error : undefined, + }), + component: ResetPasswordPage, +}) diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 621c1f9..83a7fc4 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2,6 +2,7 @@ export * from './lib/attendance-risk.js'; export * from './lib/phone.js'; export * from './lib/problem-details.js'; export * from './lib/result.js'; +export * from './schemas/admin.js'; export * from './schemas/analytics.js'; export * from './schemas/attendance.js'; export * from './schemas/attendees.js'; diff --git a/packages/shared/src/schemas/admin.ts b/packages/shared/src/schemas/admin.ts new file mode 100644 index 0000000..da2faae --- /dev/null +++ b/packages/shared/src/schemas/admin.ts @@ -0,0 +1,88 @@ +import { z } from 'zod'; +import { BillingChargeDtoSchema, planSchema, subscriptionStatusSchema } from './billing.js'; +import { countryCodeSchema } from './country.js'; +import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; + +const isoDateTimeSchema = z.string().datetime(); + +// Backoffice: Gruperly's own staff looking at the professors' accounts. Read only. + +export const AdminMeDtoSchema = z.object({ + isAdmin: z.boolean(), +}); +export type AdminMeDto = z.output; + +/** `NOT_SELECTED`: the professor never got past the onboarding step "Plan". */ +export const adminPlanFilterSchema = z.enum(['FREE', 'PRO', 'NOT_SELECTED']); +export type AdminPlanFilter = z.output; + +/** `NONE`: the professor never started a Pro subscription. */ +export const adminSubscriptionFilterSchema = z.enum([...subscriptionStatusSchema.options, 'NONE']); +export type AdminSubscriptionFilter = z.output; + +export const AdminAccountQuerySchema = z.object({ + page: createPageSchema(), + pageSize: createPageSizeSchema(20), + search: z.string().trim().max(100).optional(), + country: countryCodeSchema.optional(), + plan: adminPlanFilterSchema.optional(), + subscriptionStatus: adminSubscriptionFilterSchema.optional(), +}); +export type AdminAccountQuery = z.output; +export type AdminAccountQueryInput = z.input; + +const AdminSubscriptionSummarySchema = z.object({ + status: subscriptionStatusSchema, + amount: z.number(), + currency: z.string(), + paidThrough: isoDateTimeSchema.nullable(), + nextPaymentDate: isoDateTimeSchema.nullable(), +}); + +export const AdminAccountListItemSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string(), + /** `null` until the professor picks one in the onboarding. */ + country: countryCodeSchema.nullable(), + createdAt: isoDateTimeSchema, + onboardingCompleted: z.boolean(), + /** `null` while the professor has not chosen a plan. */ + plan: planSchema.nullable(), + subscription: AdminSubscriptionSummarySchema.nullable(), + groupsCount: z.number().int(), + /** ACTIVE attendees across the groups the professor owns. */ + attendeesCount: z.number().int(), +}); +export type AdminAccountListItem = z.output; + +export const AdminAccountListSchema = z.object({ + data: z.array(AdminAccountListItemSchema), + pagination: createPaginationSchema(), +}); +export type AdminAccountList = z.output; + +export const AdminAccountDetailSchema = AdminAccountListItemSchema.extend({ + planSelectedAt: isoDateTimeSchema.nullable(), + /** Set while a lapsed Pro still works. */ + graceUntil: isoDateTimeSchema.nullable(), + /** Free with more usage than its limits (only with BILLING_ENFORCEMENT on). */ + readOnly: z.boolean(), + subscription: AdminSubscriptionSummarySchema.extend({ + payerEmail: z.string(), + authorizedAt: isoDateTimeSchema.nullable(), + requestedAt: isoDateTimeSchema, + }).nullable(), + mpStatus: z.enum(['ACTIVE', 'REQUIRES_REAUTH', 'REVOKED']).nullable(), + whatsappStatus: z.enum(['PENDING', 'ACTIVE', 'DISCONNECTED']).nullable(), + groups: z.array( + z.object({ + id: z.string(), + name: z.string(), + createdAt: isoDateTimeSchema, + attendeesCount: z.number().int(), + }), + ), + charges: z.array(BillingChargeDtoSchema), +}); +export type AdminAccountDetail = z.output;