feat: add subscription plans. Add admin panel. Add password recovery
This commit is contained in:
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `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`).
|
- `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/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).
|
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ BILLING_ENFORCEMENT="off"
|
|||||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||||
BILLING_GRACE_DAYS="7"
|
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).
|
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
|
||||||
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
||||||
WHATSAPP_PROVIDER="openwa"
|
WHATSAPP_PROVIDER="openwa"
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
|
|||||||
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
|
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
|
||||||
import { sessionAuthMiddleware } from '@/http/session-auth';
|
import { sessionAuthMiddleware } from '@/http/session-auth';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
|
import { adminRoutes } from './modules/admin';
|
||||||
import {
|
import {
|
||||||
groupsRiskOverviewRoute,
|
groupsRiskOverviewRoute,
|
||||||
studentStatusRoutes,
|
studentStatusRoutes,
|
||||||
@@ -48,6 +49,7 @@ for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/studen
|
|||||||
api.use(`${prefix}/*`, planReadOnly);
|
api.use(`${prefix}/*`, planReadOnly);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
api.route('/admin', adminRoutes);
|
||||||
api.route('/auth', authRoutes);
|
api.route('/auth', authRoutes);
|
||||||
api.route('/health', healthCheckRoutes);
|
api.route('/health', healthCheckRoutes);
|
||||||
api.route('/invitations', invitationsRoutes);
|
api.route('/invitations', invitationsRoutes);
|
||||||
|
|||||||
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal file
@@ -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;
|
||||||
@@ -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<PrismaClient, 'user' | 'billingCharge'>;
|
||||||
|
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<Result<AdminAccountDetail, ProblemDetails>> {
|
||||||
|
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),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -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<PrismaClient, 'user' | 'group'>;
|
||||||
|
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<Result<AdminAccountList, ProblemDetails>> {
|
||||||
|
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<string, AccountUsage>();
|
||||||
|
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),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
16
apps/backend/src/modules/admin/features/me/route.ts
Normal file
16
apps/backend/src/modules/admin/features/me/route.ts
Normal file
@@ -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;
|
||||||
1
apps/backend/src/modules/admin/index.ts
Normal file
1
apps/backend/src/modules/admin/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { default as adminRoutes } from './routes';
|
||||||
39
apps/backend/src/modules/admin/lib/access.ts
Normal file
39
apps/backend/src/modules/admin/lib/access.ts
Normal file
@@ -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<string, string | undefined> = 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<string, string | undefined> = process.env,
|
||||||
|
): MiddlewareHandler<BackendEnv> {
|
||||||
|
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();
|
||||||
|
};
|
||||||
|
}
|
||||||
93
apps/backend/src/modules/admin/lib/account-summary.ts
Normal file
93
apps/backend/src/modules/admin/lib/account-summary.ts
Normal file
@@ -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<AccountRecord, 'planSelectedAt' | 'subscription'>,
|
||||||
|
{ 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<AdminAccountQuery, 'search' | 'country' | 'plan' | 'subscriptionStatus'>,
|
||||||
|
{ 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 } : {};
|
||||||
|
}
|
||||||
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export { adminOnlyMiddleware, isAdminEmail } from './access';
|
||||||
|
export {
|
||||||
|
type AccountRecord,
|
||||||
|
type AccountUsage,
|
||||||
|
accountPlan,
|
||||||
|
buildAccountWhere,
|
||||||
|
type PlanContext,
|
||||||
|
toAccountListItem,
|
||||||
|
} from './account-summary';
|
||||||
17
apps/backend/src/modules/admin/routes.ts
Normal file
17
apps/backend/src/modules/admin/routes.ts
Normal file
@@ -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;
|
||||||
@@ -14,6 +14,7 @@ export const auth = betterAuth({
|
|||||||
emailAndPassword: {
|
emailAndPassword: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
minPasswordLength: 8,
|
minPasswordLength: 8,
|
||||||
|
revokeSessionsOnPasswordReset: true,
|
||||||
sendResetPassword: async ({ user, url }) => {
|
sendResetPassword: async ({ user, url }) => {
|
||||||
await emailProvider.sendPasswordResetEmail({
|
await emailProvider.sendPasswordResetEmail({
|
||||||
email: user.email,
|
email: user.email,
|
||||||
|
|||||||
@@ -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 type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
@@ -53,6 +53,21 @@ export function resolvePlan(
|
|||||||
return { plan: 'FREE', graceUntil: null };
|
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 type PlanUsage = { groups: number; attendees: number };
|
||||||
|
|
||||||
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
|
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export {
|
|||||||
PlanGuard,
|
PlanGuard,
|
||||||
type PlanResolution,
|
type PlanResolution,
|
||||||
type PlanUsage,
|
type PlanUsage,
|
||||||
|
proSubscriptionWhere,
|
||||||
resolvePlan,
|
resolvePlan,
|
||||||
type SubscriptionSnapshot,
|
type SubscriptionSnapshot,
|
||||||
} from './entitlements';
|
} from './entitlements';
|
||||||
|
|||||||
315
apps/backend/test/admin.test.ts
Normal file
315
apps/backend/test/admin.test.ts
Normal file
@@ -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<string, unknown> = {}) {
|
||||||
|
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<string, unknown> = {}) {
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
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 { cn } from '../../lib/utils'
|
||||||
import { signOut } from '../../lib/auth-client'
|
import { signOut } from '../../lib/auth-client'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||||
|
import { useAdminAccess } from '../../features/admin/useAdminAccess'
|
||||||
import { Avatar } from '../ui'
|
import { Avatar } from '../ui'
|
||||||
|
|
||||||
const itemClass =
|
const itemClass =
|
||||||
@@ -17,6 +18,8 @@ export function UserMenu() {
|
|||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
// Solo el equipo de Gruperly ve el acceso al backoffice.
|
||||||
|
const isAdmin = useAdminAccess(!!user).data?.isAdmin ?? false
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || isMobile) return
|
if (!open || isMobile) return
|
||||||
@@ -124,6 +127,17 @@ export function UserMenu() {
|
|||||||
<Settings className="size-5 text-foreground/60" />
|
<Settings className="size-5 text-foreground/60" />
|
||||||
Ajustes
|
Ajustes
|
||||||
</Link>
|
</Link>
|
||||||
|
{isAdmin ? (
|
||||||
|
<Link
|
||||||
|
role="menuitem"
|
||||||
|
to="/admin"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
className={cn(itemClass, 'py-3.5')}
|
||||||
|
>
|
||||||
|
<ShieldCheck className="size-5 text-foreground/60" />
|
||||||
|
Backoffice
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -162,6 +176,12 @@ export function UserMenu() {
|
|||||||
<Settings className="size-4 text-foreground/60" />
|
<Settings className="size-4 text-foreground/60" />
|
||||||
Ajustes
|
Ajustes
|
||||||
</Link>
|
</Link>
|
||||||
|
{isAdmin ? (
|
||||||
|
<Link role="menuitem" to="/admin" onClick={() => setOpen(false)} className={itemClass}>
|
||||||
|
<ShieldCheck className="size-4 text-foreground/60" />
|
||||||
|
Backoffice
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
<div className="mx-3 my-1 h-px bg-border" />
|
<div className="mx-3 my-1 h-px bg-border" />
|
||||||
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
|
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
|
||||||
<LogOut className="size-4 text-foreground/60" />
|
<LogOut className="size-4 text-foreground/60" />
|
||||||
|
|||||||
60
apps/web/src/features/admin/AdminAccountDetailProvider.tsx
Normal file
60
apps/web/src/features/admin/AdminAccountDetailProvider.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import type { AdminAccountDetail } from '@gruperly/shared'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { createContext, useContext } from 'react'
|
||||||
|
import { ApiError, getAdminAccount } from '../../lib/api'
|
||||||
|
|
||||||
|
type AdminAccountDetailContextValue = {
|
||||||
|
account: AdminAccountDetail | null
|
||||||
|
isPending: boolean
|
||||||
|
isError: boolean
|
||||||
|
isNotFound: boolean
|
||||||
|
errorMessage: string | null
|
||||||
|
retry: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminAccountDetailContext = createContext<AdminAccountDetailContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AdminAccountDetailProvider({
|
||||||
|
accountId,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
accountId: string
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
|
const accountQuery = useQuery({
|
||||||
|
queryKey: ['admin', 'accounts', 'detail', accountId],
|
||||||
|
queryFn: () => getAdminAccount(accountId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const error = accountQuery.error
|
||||||
|
const isNotFound = error instanceof ApiError && error.status === 404
|
||||||
|
const errorMessage = accountQuery.isError
|
||||||
|
? error instanceof ApiError
|
||||||
|
? (error.problem?.detail ?? 'No pudimos cargar la cuenta.')
|
||||||
|
: 'No pudimos cargar la cuenta.'
|
||||||
|
: null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdminAccountDetailContext.Provider
|
||||||
|
value={{
|
||||||
|
account: accountQuery.data ?? null,
|
||||||
|
isPending: accountQuery.isPending,
|
||||||
|
isError: accountQuery.isError,
|
||||||
|
isNotFound,
|
||||||
|
errorMessage,
|
||||||
|
retry: () => void accountQuery.refetch(),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AdminAccountDetailContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAdminAccountDetail() {
|
||||||
|
const context = useContext(AdminAccountDetailContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAdminAccountDetail debe usarse dentro de <AdminAccountDetailProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
160
apps/web/src/features/admin/AdminAccountDetailView.tsx
Normal file
160
apps/web/src/features/admin/AdminAccountDetailView.tsx
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
import type { AdminAccountDetail } from '@gruperly/shared'
|
||||||
|
import { PLAN_LIMITS } from '@gruperly/shared'
|
||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { Badge, Button } from '../../components/ui'
|
||||||
|
import { formatPrice } from '../../lib/format'
|
||||||
|
import { formatBillingDate, formatUsage, subscriptionStatusLabel } from '../billing'
|
||||||
|
import { useAdminAccountDetail } from './AdminAccountDetailProvider'
|
||||||
|
import {
|
||||||
|
countryLabel,
|
||||||
|
MP_STATUS_LABELS,
|
||||||
|
planLabel,
|
||||||
|
planVariant,
|
||||||
|
subscriptionVariant,
|
||||||
|
WHATSAPP_STATUS_LABELS,
|
||||||
|
} from './copy'
|
||||||
|
|
||||||
|
export function AdminAccountDetailView() {
|
||||||
|
const { account, isPending, isError, isNotFound, errorMessage, retry } = useAdminAccountDetail()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section>
|
||||||
|
<Link
|
||||||
|
to="/admin"
|
||||||
|
className="hidden items-center gap-1.5 text-sm font-medium text-foreground/60 hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||||
|
Cuentas
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* El h1 va siempre, también cargando, para que el layout no salte. */}
|
||||||
|
<h1 className="mt-2 truncate text-2xl font-bold text-primary">{account?.name ?? 'Cuenta'}</h1>
|
||||||
|
{account ? <p className="mt-0.5 truncate text-sm text-foreground/60">{account.email}</p> : null}
|
||||||
|
|
||||||
|
{isPending ? (
|
||||||
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
|
<span className="sr-only">Cargando cuenta</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isError ? (
|
||||||
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
<p>{isNotFound ? 'Esta cuenta no existe.' : errorMessage}</p>
|
||||||
|
{isNotFound ? null : (
|
||||||
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{account ? <AccountDetail account={account} /> : null}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
||||||
|
const subscription = account.subscription
|
||||||
|
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-6 grid gap-4 lg:grid-cols-2">
|
||||||
|
<Card title="Cuenta">
|
||||||
|
<Field label="País">{countryLabel(account.country)}</Field>
|
||||||
|
<Field label="Alta">{formatBillingDate(account.createdAt)}</Field>
|
||||||
|
<Field label="Onboarding">{account.onboardingCompleted ? 'Completo' : 'Sin terminar'}</Field>
|
||||||
|
<Field label="Mercado Pago">{MP_STATUS_LABELS[account.mpStatus ?? 'NONE']}</Field>
|
||||||
|
<Field label="WhatsApp">{WHATSAPP_STATUS_LABELS[account.whatsappStatus ?? 'NONE']}</Field>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Plan">
|
||||||
|
<Field label="Plan">
|
||||||
|
<span className="inline-flex flex-wrap items-center gap-1.5">
|
||||||
|
<Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
||||||
|
{account.readOnly ? <Badge variant="danger">Solo lectura</Badge> : null}
|
||||||
|
</span>
|
||||||
|
</Field>
|
||||||
|
<Field label="Elegido el">{formatBillingDate(account.planSelectedAt) ?? '—'}</Field>
|
||||||
|
<Field label="Suscripción">
|
||||||
|
<Badge variant={subscriptionVariant(subscription?.status ?? null)}>
|
||||||
|
{subscriptionStatusLabel(subscription?.status ?? null)}
|
||||||
|
</Badge>
|
||||||
|
</Field>
|
||||||
|
{subscription ? (
|
||||||
|
<>
|
||||||
|
<Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field>
|
||||||
|
<Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
|
||||||
|
<Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
|
||||||
|
<Field label="Email de pago">{subscription.payerEmail}</Field>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{account.graceUntil ? (
|
||||||
|
<Field label="En gracia hasta">{formatBillingDate(account.graceUntil)}</Field>
|
||||||
|
) : null}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Uso">
|
||||||
|
<Field label="Grupos">{formatUsage(account.groupsCount, limits.maxGroups)}</Field>
|
||||||
|
<Field label="Alumnos activos">{formatUsage(account.attendeesCount, limits.maxAttendees)}</Field>
|
||||||
|
{account.groups.length > 0 ? (
|
||||||
|
<ul className="mt-2 divide-y divide-border border-t border-border">
|
||||||
|
{account.groups.map((group) => (
|
||||||
|
<li key={group.id} className="flex items-center justify-between gap-3 py-2 text-sm">
|
||||||
|
<span className="min-w-0 truncate text-primary">{group.name}</span>
|
||||||
|
<span className="shrink-0 text-xs text-foreground/60">
|
||||||
|
{group.attendeesCount} {group.attendeesCount === 1 ? 'alumno' : 'alumnos'} · desde{' '}
|
||||||
|
{formatBillingDate(group.createdAt)}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="mt-2 text-sm text-foreground/60">Todavía no creó grupos.</p>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Cobros de Gruperly">
|
||||||
|
{account.charges.length > 0 ? (
|
||||||
|
<ul className="divide-y divide-border">
|
||||||
|
{account.charges.map((charge) => (
|
||||||
|
<li key={charge.id} className="flex items-center justify-between gap-3 py-2 text-sm">
|
||||||
|
<span className="text-primary">
|
||||||
|
{formatBillingDate(charge.paidAt ?? charge.createdAt)}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<span className="tabular-nums text-foreground/70">
|
||||||
|
{formatPrice(charge.amount, charge.currency)}
|
||||||
|
</span>
|
||||||
|
<Badge variant={charge.status === 'approved' ? 'success' : 'warning'}>{charge.status}</Badge>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-foreground/60">Sin cobros registrados.</p>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Card({ title, children }: { title: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-border bg-surface p-4">
|
||||||
|
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">{title}</h2>
|
||||||
|
<div className="mt-3 space-y-2">{children}</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-start justify-between gap-4 text-sm">
|
||||||
|
<span className="shrink-0 text-foreground/60">{label}</span>
|
||||||
|
<span className="min-w-0 text-right text-primary [overflow-wrap:anywhere]">{children}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
72
apps/web/src/features/admin/AdminAccountRow.tsx
Normal file
72
apps/web/src/features/admin/AdminAccountRow.tsx
Normal file
@@ -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 = <Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
||||||
|
const statusBadge = <Badge variant={subscriptionVariant(status)}>{subscriptionStatusLabel(status)}</Badge>
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<Link
|
||||||
|
to="/admin/accounts/$accountId"
|
||||||
|
params={{ accountId: account.id }}
|
||||||
|
className="block rounded-xl border border-border bg-surface px-4 py-3 transition-colors hover:bg-primary-soft lg:rounded-none lg:border-0 lg:border-b lg:bg-transparent"
|
||||||
|
>
|
||||||
|
{/* Móvil */}
|
||||||
|
<div className="lg:hidden">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate text-sm font-semibold text-primary">{account.name}</p>
|
||||||
|
<p className="truncate text-xs text-foreground/60">{account.email}</p>
|
||||||
|
</div>
|
||||||
|
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||||
|
{planBadge}
|
||||||
|
{statusBadge}
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 text-xs text-foreground/60">
|
||||||
|
{countryLabel(account.country)} · {account.groupsCount}{' '}
|
||||||
|
{account.groupsCount === 1 ? 'grupo' : 'grupos'} · {account.attendeesCount}{' '}
|
||||||
|
{account.attendeesCount === 1 ? 'alumno' : 'alumnos'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Escritorio */}
|
||||||
|
<div className={`hidden items-center gap-4 lg:grid ${ACCOUNT_GRID_COLUMNS}`}>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-sm font-semibold text-primary">{account.name}</p>
|
||||||
|
<p className="truncate text-xs text-foreground/60">{account.email}</p>
|
||||||
|
</div>
|
||||||
|
<p className="truncate text-sm text-foreground/70">{countryLabel(account.country)}</p>
|
||||||
|
<div>{planBadge}</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
{statusBadge}
|
||||||
|
{subscription ? (
|
||||||
|
<p className="mt-1 truncate text-xs text-foreground/50">
|
||||||
|
{formatPrice(subscription.amount, subscription.currency)}
|
||||||
|
{paidThrough ? ` · hasta ${paidThrough}` : ''}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p className="text-right text-sm tabular-nums text-foreground/70">{account.groupsCount}</p>
|
||||||
|
<p className="text-right text-sm tabular-nums text-foreground/70">{account.attendeesCount}</p>
|
||||||
|
<ChevronRight className="size-4 text-foreground/40" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
123
apps/web/src/features/admin/AdminAccountsProvider.tsx
Normal file
123
apps/web/src/features/admin/AdminAccountsProvider.tsx
Normal file
@@ -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<AdminAccountsContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AdminAccountsProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
const [debouncedSearch, setDebouncedSearch] = useState('')
|
||||||
|
const [country, setCountry] = useState<CountryCode | null>(null)
|
||||||
|
const [plan, setPlan] = useState<AdminPlanFilter | null>(null)
|
||||||
|
const [subscriptionStatus, setSubscriptionStatus] = useState<AdminSubscriptionFilter | null>(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<AdminAccountQueryInput>(
|
||||||
|
() => ({
|
||||||
|
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 =
|
||||||
|
<T,>(setter: (value: T) => void) =>
|
||||||
|
(value: T) => {
|
||||||
|
setter(value)
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdminAccountsContext.Provider
|
||||||
|
value={{
|
||||||
|
accounts: data?.data ?? [],
|
||||||
|
total: data?.pagination.total ?? 0,
|
||||||
|
page,
|
||||||
|
totalPages: Math.max(data?.pagination.totalPages ?? 1, 1),
|
||||||
|
isPending: accountsQuery.isPending,
|
||||||
|
isFetching: accountsQuery.isFetching,
|
||||||
|
isError: accountsQuery.isError,
|
||||||
|
errorMessage,
|
||||||
|
search,
|
||||||
|
setSearch,
|
||||||
|
country,
|
||||||
|
setCountry: withFirstPage(setCountry),
|
||||||
|
plan,
|
||||||
|
setPlan: withFirstPage(setPlan),
|
||||||
|
subscriptionStatus,
|
||||||
|
setSubscriptionStatus: withFirstPage(setSubscriptionStatus),
|
||||||
|
setPage,
|
||||||
|
retry: () => void accountsQuery.refetch(),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AdminAccountsContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAdminAccounts() {
|
||||||
|
const context = useContext(AdminAccountsContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAdminAccounts debe usarse dentro de <AdminAccountsProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
198
apps/web/src/features/admin/AdminAccountsView.tsx
Normal file
198
apps/web/src/features/admin/AdminAccountsView.tsx
Normal file
@@ -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 (
|
||||||
|
<section>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-primary">Cuentas</h1>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
|
Profesores que usan Gruperly, con su plan y su uso.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(0,2fr)_repeat(3,minmax(0,1fr))]">
|
||||||
|
<label className="block sm:col-span-2 lg:col-span-1">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">Buscar</span>
|
||||||
|
<div className="relative">
|
||||||
|
<Search
|
||||||
|
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/40"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
type="search"
|
||||||
|
autoFocus
|
||||||
|
value={search}
|
||||||
|
onChange={(event) => setSearch(event.target.value)}
|
||||||
|
placeholder="Nombre o email"
|
||||||
|
className="pl-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">País</span>
|
||||||
|
<select
|
||||||
|
value={country ?? ''}
|
||||||
|
onChange={(event) => setCountry((event.target.value || null) as CountryCode | null)}
|
||||||
|
className={selectClass}
|
||||||
|
>
|
||||||
|
<option value="">Todos</option>
|
||||||
|
{COUNTRY_OPTIONS.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">Plan</span>
|
||||||
|
<select
|
||||||
|
value={plan ?? ''}
|
||||||
|
onChange={(event) => setPlan((event.target.value || null) as AdminPlanFilter | null)}
|
||||||
|
className={selectClass}
|
||||||
|
>
|
||||||
|
<option value="">Todos</option>
|
||||||
|
{PLAN_FILTER_OPTIONS.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">Suscripción</span>
|
||||||
|
<select
|
||||||
|
value={subscriptionStatus ?? ''}
|
||||||
|
onChange={(event) =>
|
||||||
|
setSubscriptionStatus((event.target.value || null) as AdminSubscriptionFilter | null)
|
||||||
|
}
|
||||||
|
className={selectClass}
|
||||||
|
>
|
||||||
|
<option value="">Todas</option>
|
||||||
|
{SUBSCRIPTION_FILTER_OPTIONS.map((option) => (
|
||||||
|
<option key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isPending ? (
|
||||||
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
|
<span className="sr-only">Cargando cuentas</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isError ? (
|
||||||
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
<p>{errorMessage}</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!isPending && !isError && accounts.length === 0 ? (
|
||||||
|
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
|
||||||
|
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
|
||||||
|
<Users className="size-7" aria-hidden="true" />
|
||||||
|
</span>
|
||||||
|
<p className="mt-4 text-base font-semibold text-primary">
|
||||||
|
{hasFilters ? 'Ninguna cuenta coincide' : 'Todavía no hay cuentas'}
|
||||||
|
</p>
|
||||||
|
{hasFilters ? (
|
||||||
|
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
|
||||||
|
Probá con otra búsqueda o sacá algún filtro.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{!isPending && !isError && accounts.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'mt-6 lg:rounded-xl lg:border lg:border-border lg:bg-surface',
|
||||||
|
isFetching && 'opacity-70 transition-opacity',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'hidden gap-4 border-b border-border px-4 py-2.5 text-xs font-medium uppercase tracking-wide text-foreground/50 lg:grid',
|
||||||
|
ACCOUNT_GRID_COLUMNS,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span>Cuenta</span>
|
||||||
|
<span>País</span>
|
||||||
|
<span>Plan</span>
|
||||||
|
<span>Suscripción</span>
|
||||||
|
<span className="text-right">Grupos</span>
|
||||||
|
<span className="text-right">Alumnos</span>
|
||||||
|
<span />
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-3 lg:space-y-0">
|
||||||
|
{accounts.map((account) => (
|
||||||
|
<AdminAccountRow key={account.id} account={account} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 flex items-center justify-between gap-3">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
|
<ChevronLeft className="size-4" />
|
||||||
|
Anteriores
|
||||||
|
</Button>
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
Página {page} de {totalPages} · {total} {total === 1 ? 'cuenta' : 'cuentas'}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={page >= totalPages}
|
||||||
|
onClick={() => setPage(page + 1)}
|
||||||
|
>
|
||||||
|
Siguientes
|
||||||
|
<ChevronRight className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
61
apps/web/src/features/admin/AdminGuard.tsx
Normal file
61
apps/web/src/features/admin/AdminGuard.tsx
Normal file
@@ -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 (
|
||||||
|
<div className="flex min-h-dvh items-center justify-center">
|
||||||
|
<Loader2 className="size-6 animate-spin text-foreground/40" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (access.isError) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-dvh flex-col items-center justify-center gap-3 px-4 text-center">
|
||||||
|
<p className="text-sm text-danger">No pudimos verificar tu acceso al backoffice.</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => void access.refetch()}>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!access.data?.isAdmin) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-dvh flex-col items-center justify-center gap-4 px-4 text-center">
|
||||||
|
<span className="flex size-14 items-center justify-center rounded-2xl bg-danger-soft text-danger">
|
||||||
|
<ShieldOff className="size-7" aria-hidden="true" />
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-primary">No tenés acceso</h1>
|
||||||
|
<p className="mt-1 max-w-[36ch] text-sm text-secondary">
|
||||||
|
El backoffice es solo para el equipo de Gruperly.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Link to="/" className="text-sm font-medium text-accent-fg hover:underline">
|
||||||
|
Ir a la app
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AdminLayout>{children}</AdminLayout>
|
||||||
|
}
|
||||||
33
apps/web/src/features/admin/AdminLayout.tsx
Normal file
33
apps/web/src/features/admin/AdminLayout.tsx
Normal file
@@ -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 (
|
||||||
|
<div className="min-h-dvh bg-background">
|
||||||
|
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
|
||||||
|
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
|
||||||
|
<Link to="/admin" className="text-base font-bold text-primary">
|
||||||
|
Gruperly <span className="font-medium text-foreground/50">· Backoffice</span>
|
||||||
|
</Link>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ThemeToggle />
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="hidden items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm font-medium text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||||
|
Volver a la app
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main className="mx-auto max-w-6xl px-4 py-6 pb-[calc(2rem+env(safe-area-inset-bottom))] lg:px-8 lg:py-8">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
75
apps/web/src/features/admin/copy.ts
Normal file
75
apps/web/src/features/admin/copy.ts
Normal file
@@ -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<NonNullable<AdminAccountDetail['mpStatus']> | 'NONE', string> = {
|
||||||
|
ACTIVE: 'Vinculada',
|
||||||
|
REQUIRES_REAUTH: 'Requiere volver a vincular',
|
||||||
|
REVOKED: 'Desvinculada',
|
||||||
|
NONE: 'Sin vincular',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const WHATSAPP_STATUS_LABELS: Record<NonNullable<AdminAccountDetail['whatsappStatus']> | 'NONE', string> = {
|
||||||
|
ACTIVE: 'Conectado',
|
||||||
|
PENDING: 'Conectando',
|
||||||
|
DISCONNECTED: 'Desconectado',
|
||||||
|
NONE: 'Sin conectar',
|
||||||
|
}
|
||||||
12
apps/web/src/features/admin/useAdminAccess.ts
Normal file
12
apps/web/src/features/admin/useAdminAccess.ts
Normal file
@@ -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,
|
||||||
|
})
|
||||||
|
}
|
||||||
95
apps/web/src/features/auth/ForgotPasswordPage.tsx
Normal file
95
apps/web/src/features/auth/ForgotPasswordPage.tsx
Normal file
@@ -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<typeof schema>
|
||||||
|
|
||||||
|
export function ForgotPasswordPage() {
|
||||||
|
const { email: initialEmail } = useSearch({ strict: false }) as { email?: string }
|
||||||
|
const [sentTo, setSentTo] = useState<string | null>(null)
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
setError,
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
} = useForm<FormValues>({
|
||||||
|
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 (
|
||||||
|
<AuthShell title="Revisá tu email">
|
||||||
|
<div className="flex flex-col items-center gap-4 py-2 text-center">
|
||||||
|
<MailCheck className="size-10 text-success" />
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
Si hay una cuenta con <span className="font-medium text-primary">{sentTo}</span>, te
|
||||||
|
enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora.
|
||||||
|
</p>
|
||||||
|
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
|
||||||
|
Volver a iniciar sesión
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthShell
|
||||||
|
title="Recuperar contraseña"
|
||||||
|
subtitle="Te enviamos un enlace para elegir una nueva"
|
||||||
|
>
|
||||||
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
autoFocus
|
||||||
|
placeholder="vos@ejemplo.com"
|
||||||
|
invalid={!!errors.email}
|
||||||
|
{...register('email')}
|
||||||
|
/>
|
||||||
|
{errors.email ? <p className="mt-1 text-sm text-danger">{errors.email.message}</p> : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|
||||||
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
{isSubmitting ? 'Enviando…' : 'Enviar enlace'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<p className="text-center text-sm text-foreground/60">
|
||||||
|
<Link to="/login" className="font-medium text-accent hover:underline">
|
||||||
|
Volver a iniciar sesión
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { zodResolver } from '@hookform/resolvers/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 { Fingerprint, Loader2 } from 'lucide-react'
|
||||||
import { authClient } from '../../lib/auth-client'
|
import { authClient } from '../../lib/auth-client'
|
||||||
import { Button, Input, Label } from '../../components/ui'
|
import { Button, Input, Label } from '../../components/ui'
|
||||||
@@ -16,10 +16,12 @@ type FormValues = z.infer<typeof schema>
|
|||||||
|
|
||||||
export function LoginPage() {
|
export function LoginPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { reset } = useSearch({ strict: false }) as { reset?: 'ok' }
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
setError,
|
setError,
|
||||||
|
watch,
|
||||||
formState: { errors, isSubmitting },
|
formState: { errors, isSubmitting },
|
||||||
} = useForm<FormValues>({ resolver: zodResolver(schema) })
|
} = useForm<FormValues>({ resolver: zodResolver(schema) })
|
||||||
|
|
||||||
@@ -48,6 +50,12 @@ export function LoginPage() {
|
|||||||
return (
|
return (
|
||||||
<AuthShell title="Iniciar sesión" subtitle="Accedé a tus cobros grupales">
|
<AuthShell title="Iniciar sesión" subtitle="Accedé a tus cobros grupales">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{reset === 'ok' ? (
|
||||||
|
<p className="rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
||||||
|
Tu contraseña se actualizó. Ingresá con la nueva.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<form onSubmit={onSubmit} className="space-y-4">
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">Email</Label>
|
||||||
@@ -75,6 +83,15 @@ export function LoginPage() {
|
|||||||
{errors.password ? (
|
{errors.password ? (
|
||||||
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
|
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
<div className="mt-1 text-right">
|
||||||
|
<Link
|
||||||
|
to="/forgot-password"
|
||||||
|
search={{ email: watch('email') || undefined }}
|
||||||
|
className="text-sm text-accent hover:underline"
|
||||||
|
>
|
||||||
|
¿Olvidaste tu contraseña?
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|||||||
107
apps/web/src/features/auth/ResetPasswordPage.tsx
Normal file
107
apps/web/src/features/auth/ResetPasswordPage.tsx
Normal file
@@ -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<typeof schema>
|
||||||
|
|
||||||
|
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<FormValues>({ 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 (
|
||||||
|
<AuthShell title="Vínculo inválido">
|
||||||
|
<div className="flex flex-col items-center gap-4 py-2 text-center">
|
||||||
|
<MailWarning className="size-10 text-warning" />
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
El enlace para restablecer la contraseña no es válido o venció.
|
||||||
|
</p>
|
||||||
|
<Link to="/forgot-password" className="text-sm font-medium text-accent hover:underline">
|
||||||
|
Pedir un enlace nuevo
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthShell title="Nueva contraseña" subtitle="Elegí una contraseña para tu cuenta">
|
||||||
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="newPassword">Nueva contraseña</Label>
|
||||||
|
<Input
|
||||||
|
id="newPassword"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
autoFocus
|
||||||
|
placeholder="••••••••"
|
||||||
|
invalid={!!errors.newPassword}
|
||||||
|
{...register('newPassword')}
|
||||||
|
/>
|
||||||
|
{errors.newPassword ? (
|
||||||
|
<p className="mt-1 text-sm text-danger">{errors.newPassword.message}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="confirmPassword">Repetir contraseña</Label>
|
||||||
|
<Input
|
||||||
|
id="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder="••••••••"
|
||||||
|
invalid={!!errors.confirmPassword}
|
||||||
|
{...register('confirmPassword')}
|
||||||
|
/>
|
||||||
|
{errors.confirmPassword ? (
|
||||||
|
<p className="mt-1 text-sm text-danger">{errors.confirmPassword.message}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|
||||||
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
{isSubmitting ? 'Guardando…' : 'Guardar contraseña'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
export {
|
export {
|
||||||
formatBillingDate,
|
formatBillingDate,
|
||||||
|
formatUsage,
|
||||||
hasPlanFeature,
|
hasPlanFeature,
|
||||||
isPlanProblem,
|
isPlanProblem,
|
||||||
PLAN_FEATURE_REQUIRED_MESSAGES,
|
PLAN_FEATURE_REQUIRED_MESSAGES,
|
||||||
|
|||||||
@@ -35,7 +35,9 @@ export function Stepper({ steps, current }: StepperProps) {
|
|||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'hidden text-xs font-medium sm:block',
|
// Sin corte: con 7 pasos en max-w-md, "Tu grupo" partía en dos
|
||||||
|
// líneas. Si falta lugar, se achica la línea entre pasos.
|
||||||
|
'hidden whitespace-nowrap text-xs font-medium sm:block',
|
||||||
isActive ? 'text-accent' : 'text-foreground/50',
|
isActive ? 'text-accent' : 'text-foreground/50',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import type {
|
import type {
|
||||||
AbsenceDetails,
|
AbsenceDetails,
|
||||||
|
AdminAccountDetail,
|
||||||
|
AdminAccountList,
|
||||||
|
AdminAccountQueryInput,
|
||||||
|
AdminMeDto,
|
||||||
ApproveGroupPreRegistrationResult,
|
ApproveGroupPreRegistrationResult,
|
||||||
AttendeeDetailDto,
|
AttendeeDetailDto,
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
@@ -383,3 +387,18 @@ export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus)
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ status }),
|
body: JSON.stringify({ status }),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// — Backoffice (equipo de Gruperly) —
|
||||||
|
|
||||||
|
export const getAdminMe = () => apiFetch<AdminMeDto>('/api/v1/admin/me')
|
||||||
|
|
||||||
|
export const getAdminAccounts = (params: AdminAccountQueryInput) => {
|
||||||
|
const query = new URLSearchParams()
|
||||||
|
for (const [key, value] of Object.entries(params)) {
|
||||||
|
if (value !== undefined && value !== '') query.set(key, String(value))
|
||||||
|
}
|
||||||
|
return apiFetch<AdminAccountList>(`/api/v1/admin/accounts?${query.toString()}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getAdminAccount = (accountId: string) =>
|
||||||
|
apiFetch<AdminAccountDetail>(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`)
|
||||||
|
|||||||
@@ -10,8 +10,11 @@
|
|||||||
|
|
||||||
import { Route as rootRouteImport } from './routes/__root'
|
import { Route as rootRouteImport } from './routes/__root'
|
||||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
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 LoginRouteImport } from './routes/login'
|
||||||
import { Route as OnboardingRouteImport } from './routes/onboarding'
|
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 SignupRouteImport } from './routes/signup'
|
||||||
import { Route as VerifyEmailRouteImport } from './routes/verify-email'
|
import { Route as VerifyEmailRouteImport } from './routes/verify-email'
|
||||||
import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'
|
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 AuthenticatedProfileRouteImport } from './routes/_authenticated/profile'
|
||||||
import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticated/security'
|
import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticated/security'
|
||||||
import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings'
|
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 JoinTokenRouteImport } from './routes/join.$token'
|
||||||
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
|
import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token'
|
||||||
import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index'
|
import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index'
|
||||||
import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new'
|
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 AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
||||||
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
||||||
@@ -34,6 +39,16 @@ const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
|||||||
id: '/_authenticated',
|
id: '/_authenticated',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} 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({
|
const LoginRoute = LoginRouteImport.update({
|
||||||
id: '/login',
|
id: '/login',
|
||||||
path: '/login',
|
path: '/login',
|
||||||
@@ -44,6 +59,11 @@ const OnboardingRoute = OnboardingRouteImport.update({
|
|||||||
path: '/onboarding',
|
path: '/onboarding',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const ResetPasswordRoute = ResetPasswordRouteImport.update({
|
||||||
|
id: '/reset-password',
|
||||||
|
path: '/reset-password',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const SignupRoute = SignupRouteImport.update({
|
const SignupRoute = SignupRouteImport.update({
|
||||||
id: '/signup',
|
id: '/signup',
|
||||||
path: '/signup',
|
path: '/signup',
|
||||||
@@ -84,6 +104,11 @@ const AuthenticatedSettingsRoute = AuthenticatedSettingsRouteImport.update({
|
|||||||
path: '/settings',
|
path: '/settings',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AdminIndexRoute = AdminIndexRouteImport.update({
|
||||||
|
id: '/',
|
||||||
|
path: '/',
|
||||||
|
getParentRoute: () => AdminRoute,
|
||||||
|
} as any)
|
||||||
const JoinTokenRoute = JoinTokenRouteImport.update({
|
const JoinTokenRoute = JoinTokenRouteImport.update({
|
||||||
id: '/join/$token',
|
id: '/join/$token',
|
||||||
path: '/join/$token',
|
path: '/join/$token',
|
||||||
@@ -105,6 +130,11 @@ const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({
|
|||||||
path: '/groups/new',
|
path: '/groups/new',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AdminAccountsAccountIdRoute = AdminAccountsAccountIdRouteImport.update({
|
||||||
|
id: '/accounts/$accountId',
|
||||||
|
path: '/accounts/$accountId',
|
||||||
|
getParentRoute: () => AdminRoute,
|
||||||
|
} as any)
|
||||||
const AuthenticatedClassSessionIdAttendanceRoute =
|
const AuthenticatedClassSessionIdAttendanceRoute =
|
||||||
AuthenticatedClassSessionIdAttendanceRouteImport.update({
|
AuthenticatedClassSessionIdAttendanceRouteImport.update({
|
||||||
id: '/class/$sessionId/attendance',
|
id: '/class/$sessionId/attendance',
|
||||||
@@ -138,8 +168,11 @@ const AuthenticatedGroupsGroupIdAttendeesNewRoute =
|
|||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
|
'/admin': typeof AdminRouteWithChildren
|
||||||
|
'/forgot-password': typeof ForgotPasswordRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/onboarding': typeof OnboardingRoute
|
'/onboarding': typeof OnboardingRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
'/signup': typeof SignupRoute
|
'/signup': typeof SignupRoute
|
||||||
'/verify-email': typeof VerifyEmailRoute
|
'/verify-email': typeof VerifyEmailRoute
|
||||||
'/billing': typeof AuthenticatedBillingRoute
|
'/billing': typeof AuthenticatedBillingRoute
|
||||||
@@ -149,7 +182,9 @@ export interface FileRoutesByFullPath {
|
|||||||
'/settings': typeof AuthenticatedSettingsRoute
|
'/settings': typeof AuthenticatedSettingsRoute
|
||||||
'/join/$token': typeof JoinTokenRoute
|
'/join/$token': typeof JoinTokenRoute
|
||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
|
'/admin/': typeof AdminIndexRoute
|
||||||
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/groups/': typeof AuthenticatedGroupsIndexRoute
|
'/groups/': typeof AuthenticatedGroupsIndexRoute
|
||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
@@ -158,8 +193,10 @@ export interface FileRoutesByFullPath {
|
|||||||
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
'/groups/$groupId/attendees/new': typeof AuthenticatedGroupsGroupIdAttendeesNewRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
|
'/forgot-password': typeof ForgotPasswordRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/onboarding': typeof OnboardingRoute
|
'/onboarding': typeof OnboardingRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
'/signup': typeof SignupRoute
|
'/signup': typeof SignupRoute
|
||||||
'/verify-email': typeof VerifyEmailRoute
|
'/verify-email': typeof VerifyEmailRoute
|
||||||
'/billing': typeof AuthenticatedBillingRoute
|
'/billing': typeof AuthenticatedBillingRoute
|
||||||
@@ -170,7 +207,9 @@ export interface FileRoutesByTo {
|
|||||||
'/join/$token': typeof JoinTokenRoute
|
'/join/$token': typeof JoinTokenRoute
|
||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
|
'/admin': typeof AdminIndexRoute
|
||||||
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/groups': typeof AuthenticatedGroupsIndexRoute
|
'/groups': typeof AuthenticatedGroupsIndexRoute
|
||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
@@ -181,8 +220,11 @@ export interface FileRoutesByTo {
|
|||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||||
|
'/admin': typeof AdminRouteWithChildren
|
||||||
|
'/forgot-password': typeof ForgotPasswordRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/onboarding': typeof OnboardingRoute
|
'/onboarding': typeof OnboardingRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
'/signup': typeof SignupRoute
|
'/signup': typeof SignupRoute
|
||||||
'/verify-email': typeof VerifyEmailRoute
|
'/verify-email': typeof VerifyEmailRoute
|
||||||
'/_authenticated/billing': typeof AuthenticatedBillingRoute
|
'/_authenticated/billing': typeof AuthenticatedBillingRoute
|
||||||
@@ -193,7 +235,9 @@ export interface FileRoutesById {
|
|||||||
'/join/$token': typeof JoinTokenRoute
|
'/join/$token': typeof JoinTokenRoute
|
||||||
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
'/report-absence/$token': typeof ReportAbsenceTokenRoute
|
||||||
'/_authenticated/': typeof AuthenticatedIndexRoute
|
'/_authenticated/': typeof AuthenticatedIndexRoute
|
||||||
|
'/admin/': typeof AdminIndexRoute
|
||||||
'/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute
|
'/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute
|
||||||
|
'/admin/accounts/$accountId': typeof AdminAccountsAccountIdRoute
|
||||||
'/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute
|
'/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute
|
||||||
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
@@ -205,8 +249,11 @@ export interface FileRouteTypes {
|
|||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
fullPaths:
|
fullPaths:
|
||||||
| '/'
|
| '/'
|
||||||
|
| '/admin'
|
||||||
|
| '/forgot-password'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/onboarding'
|
| '/onboarding'
|
||||||
|
| '/reset-password'
|
||||||
| '/signup'
|
| '/signup'
|
||||||
| '/verify-email'
|
| '/verify-email'
|
||||||
| '/billing'
|
| '/billing'
|
||||||
@@ -216,7 +263,9 @@ export interface FileRouteTypes {
|
|||||||
| '/settings'
|
| '/settings'
|
||||||
| '/join/$token'
|
| '/join/$token'
|
||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
|
| '/admin/'
|
||||||
| '/groups/new'
|
| '/groups/new'
|
||||||
|
| '/admin/accounts/$accountId'
|
||||||
| '/groups/'
|
| '/groups/'
|
||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
@@ -225,8 +274,10 @@ export interface FileRouteTypes {
|
|||||||
| '/groups/$groupId/attendees/new'
|
| '/groups/$groupId/attendees/new'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
|
| '/forgot-password'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/onboarding'
|
| '/onboarding'
|
||||||
|
| '/reset-password'
|
||||||
| '/signup'
|
| '/signup'
|
||||||
| '/verify-email'
|
| '/verify-email'
|
||||||
| '/billing'
|
| '/billing'
|
||||||
@@ -237,7 +288,9 @@ export interface FileRouteTypes {
|
|||||||
| '/join/$token'
|
| '/join/$token'
|
||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
| '/'
|
| '/'
|
||||||
|
| '/admin'
|
||||||
| '/groups/new'
|
| '/groups/new'
|
||||||
|
| '/admin/accounts/$accountId'
|
||||||
| '/groups'
|
| '/groups'
|
||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
@@ -247,8 +300,11 @@ export interface FileRouteTypes {
|
|||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/_authenticated'
|
| '/_authenticated'
|
||||||
|
| '/admin'
|
||||||
|
| '/forgot-password'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/onboarding'
|
| '/onboarding'
|
||||||
|
| '/reset-password'
|
||||||
| '/signup'
|
| '/signup'
|
||||||
| '/verify-email'
|
| '/verify-email'
|
||||||
| '/_authenticated/billing'
|
| '/_authenticated/billing'
|
||||||
@@ -259,7 +315,9 @@ export interface FileRouteTypes {
|
|||||||
| '/join/$token'
|
| '/join/$token'
|
||||||
| '/report-absence/$token'
|
| '/report-absence/$token'
|
||||||
| '/_authenticated/'
|
| '/_authenticated/'
|
||||||
|
| '/admin/'
|
||||||
| '/_authenticated/groups/new'
|
| '/_authenticated/groups/new'
|
||||||
|
| '/admin/accounts/$accountId'
|
||||||
| '/_authenticated/groups/'
|
| '/_authenticated/groups/'
|
||||||
| '/_authenticated/class/$sessionId/attendance'
|
| '/_authenticated/class/$sessionId/attendance'
|
||||||
| '/_authenticated/groups/$groupId/analytics'
|
| '/_authenticated/groups/$groupId/analytics'
|
||||||
@@ -270,8 +328,11 @@ export interface FileRouteTypes {
|
|||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
||||||
|
AdminRoute: typeof AdminRouteWithChildren
|
||||||
|
ForgotPasswordRoute: typeof ForgotPasswordRoute
|
||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
OnboardingRoute: typeof OnboardingRoute
|
OnboardingRoute: typeof OnboardingRoute
|
||||||
|
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||||
SignupRoute: typeof SignupRoute
|
SignupRoute: typeof SignupRoute
|
||||||
VerifyEmailRoute: typeof VerifyEmailRoute
|
VerifyEmailRoute: typeof VerifyEmailRoute
|
||||||
JoinTokenRoute: typeof JoinTokenRoute
|
JoinTokenRoute: typeof JoinTokenRoute
|
||||||
@@ -287,6 +348,20 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedRouteImport
|
preLoaderRoute: typeof AuthenticatedRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
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': {
|
'/login': {
|
||||||
id: '/login'
|
id: '/login'
|
||||||
path: '/login'
|
path: '/login'
|
||||||
@@ -301,6 +376,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof OnboardingRouteImport
|
preLoaderRoute: typeof OnboardingRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/reset-password': {
|
||||||
|
id: '/reset-password'
|
||||||
|
path: '/reset-password'
|
||||||
|
fullPath: '/reset-password'
|
||||||
|
preLoaderRoute: typeof ResetPasswordRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/signup': {
|
'/signup': {
|
||||||
id: '/signup'
|
id: '/signup'
|
||||||
path: '/signup'
|
path: '/signup'
|
||||||
@@ -357,6 +439,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedSettingsRouteImport
|
preLoaderRoute: typeof AuthenticatedSettingsRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
parentRoute: typeof AuthenticatedRoute
|
||||||
}
|
}
|
||||||
|
'/admin/': {
|
||||||
|
id: '/admin/'
|
||||||
|
path: '/'
|
||||||
|
fullPath: '/admin/'
|
||||||
|
preLoaderRoute: typeof AdminIndexRouteImport
|
||||||
|
parentRoute: typeof AdminRoute
|
||||||
|
}
|
||||||
'/join/$token': {
|
'/join/$token': {
|
||||||
id: '/join/$token'
|
id: '/join/$token'
|
||||||
path: '/join/$token'
|
path: '/join/$token'
|
||||||
@@ -385,6 +474,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedGroupsNewRouteImport
|
preLoaderRoute: typeof AuthenticatedGroupsNewRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
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': {
|
'/_authenticated/class/$sessionId/attendance': {
|
||||||
id: '/_authenticated/class/$sessionId/attendance'
|
id: '/_authenticated/class/$sessionId/attendance'
|
||||||
path: '/class/$sessionId/attendance'
|
path: '/class/$sessionId/attendance'
|
||||||
@@ -463,10 +559,25 @@ const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
|||||||
AuthenticatedRouteChildren,
|
AuthenticatedRouteChildren,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
interface AdminRouteChildren {
|
||||||
|
AdminIndexRoute: typeof AdminIndexRoute
|
||||||
|
AdminAccountsAccountIdRoute: typeof AdminAccountsAccountIdRoute
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminRouteChildren: AdminRouteChildren = {
|
||||||
|
AdminIndexRoute: AdminIndexRoute,
|
||||||
|
AdminAccountsAccountIdRoute: AdminAccountsAccountIdRoute,
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminRouteWithChildren = AdminRoute._addFileChildren(AdminRouteChildren)
|
||||||
|
|
||||||
const rootRouteChildren: RootRouteChildren = {
|
const rootRouteChildren: RootRouteChildren = {
|
||||||
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
||||||
|
AdminRoute: AdminRouteWithChildren,
|
||||||
|
ForgotPasswordRoute: ForgotPasswordRoute,
|
||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
OnboardingRoute: OnboardingRoute,
|
OnboardingRoute: OnboardingRoute,
|
||||||
|
ResetPasswordRoute: ResetPasswordRoute,
|
||||||
SignupRoute: SignupRoute,
|
SignupRoute: SignupRoute,
|
||||||
VerifyEmailRoute: VerifyEmailRoute,
|
VerifyEmailRoute: VerifyEmailRoute,
|
||||||
JoinTokenRoute: JoinTokenRoute,
|
JoinTokenRoute: JoinTokenRoute,
|
||||||
|
|||||||
10
apps/web/src/routes/admin.tsx
Normal file
10
apps/web/src/routes/admin.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { createFileRoute, Outlet } from '@tanstack/react-router'
|
||||||
|
import { AdminGuard } from '../features/admin/AdminGuard'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/admin')({
|
||||||
|
component: () => (
|
||||||
|
<AdminGuard>
|
||||||
|
<Outlet />
|
||||||
|
</AdminGuard>
|
||||||
|
),
|
||||||
|
})
|
||||||
14
apps/web/src/routes/admin/accounts.$accountId.tsx
Normal file
14
apps/web/src/routes/admin/accounts.$accountId.tsx
Normal file
@@ -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 (
|
||||||
|
<AdminAccountDetailProvider accountId={accountId}>
|
||||||
|
<AdminAccountDetailView />
|
||||||
|
</AdminAccountDetailProvider>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
11
apps/web/src/routes/admin/index.tsx
Normal file
11
apps/web/src/routes/admin/index.tsx
Normal file
@@ -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: () => (
|
||||||
|
<AdminAccountsProvider>
|
||||||
|
<AdminAccountsView />
|
||||||
|
</AdminAccountsProvider>
|
||||||
|
),
|
||||||
|
})
|
||||||
9
apps/web/src/routes/forgot-password.tsx
Normal file
9
apps/web/src/routes/forgot-password.tsx
Normal file
@@ -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<string, unknown>): { email?: string } => ({
|
||||||
|
email: typeof search.email === 'string' ? search.email : undefined,
|
||||||
|
}),
|
||||||
|
component: ForgotPasswordPage,
|
||||||
|
})
|
||||||
@@ -2,5 +2,8 @@ import { createFileRoute } from '@tanstack/react-router'
|
|||||||
import { LoginPage } from '../features/auth/LoginPage'
|
import { LoginPage } from '../features/auth/LoginPage'
|
||||||
|
|
||||||
export const Route = createFileRoute('/login')({
|
export const Route = createFileRoute('/login')({
|
||||||
|
validateSearch: (search: Record<string, unknown>): { reset?: 'ok' } => ({
|
||||||
|
reset: search.reset === 'ok' ? 'ok' : undefined,
|
||||||
|
}),
|
||||||
component: LoginPage,
|
component: LoginPage,
|
||||||
})
|
})
|
||||||
|
|||||||
10
apps/web/src/routes/reset-password.tsx
Normal file
10
apps/web/src/routes/reset-password.tsx
Normal file
@@ -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<string, unknown>): { token?: string; error?: string } => ({
|
||||||
|
token: typeof search.token === 'string' ? search.token : undefined,
|
||||||
|
error: typeof search.error === 'string' ? search.error : undefined,
|
||||||
|
}),
|
||||||
|
component: ResetPasswordPage,
|
||||||
|
})
|
||||||
@@ -2,6 +2,7 @@ export * from './lib/attendance-risk.js';
|
|||||||
export * from './lib/phone.js';
|
export * from './lib/phone.js';
|
||||||
export * from './lib/problem-details.js';
|
export * from './lib/problem-details.js';
|
||||||
export * from './lib/result.js';
|
export * from './lib/result.js';
|
||||||
|
export * from './schemas/admin.js';
|
||||||
export * from './schemas/analytics.js';
|
export * from './schemas/analytics.js';
|
||||||
export * from './schemas/attendance.js';
|
export * from './schemas/attendance.js';
|
||||||
export * from './schemas/attendees.js';
|
export * from './schemas/attendees.js';
|
||||||
|
|||||||
88
packages/shared/src/schemas/admin.ts
Normal file
88
packages/shared/src/schemas/admin.ts
Normal file
@@ -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<typeof AdminMeDtoSchema>;
|
||||||
|
|
||||||
|
/** `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<typeof adminPlanFilterSchema>;
|
||||||
|
|
||||||
|
/** `NONE`: the professor never started a Pro subscription. */
|
||||||
|
export const adminSubscriptionFilterSchema = z.enum([...subscriptionStatusSchema.options, 'NONE']);
|
||||||
|
export type AdminSubscriptionFilter = z.output<typeof adminSubscriptionFilterSchema>;
|
||||||
|
|
||||||
|
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<typeof AdminAccountQuerySchema>;
|
||||||
|
export type AdminAccountQueryInput = z.input<typeof AdminAccountQuerySchema>;
|
||||||
|
|
||||||
|
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<typeof AdminAccountListItemSchema>;
|
||||||
|
|
||||||
|
export const AdminAccountListSchema = z.object({
|
||||||
|
data: z.array(AdminAccountListItemSchema),
|
||||||
|
pagination: createPaginationSchema(),
|
||||||
|
});
|
||||||
|
export type AdminAccountList = z.output<typeof AdminAccountListSchema>;
|
||||||
|
|
||||||
|
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<typeof AdminAccountDetailSchema>;
|
||||||
Reference in New Issue
Block a user