feat: add subscription plans. Add admin panel. Add password recovery
This commit is contained in:
@@ -43,6 +43,9 @@ BILLING_ENFORCEMENT="off"
|
||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||
BILLING_GRACE_DAYS="7"
|
||||
|
||||
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||
ADMIN_EMAILS=""
|
||||
|
||||
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
|
||||
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
||||
WHATSAPP_PROVIDER="openwa"
|
||||
|
||||
@@ -10,6 +10,7 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
|
||||
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
|
||||
import { sessionAuthMiddleware } from '@/http/session-auth';
|
||||
import { logger } from '@/logger';
|
||||
import { adminRoutes } from './modules/admin';
|
||||
import {
|
||||
groupsRiskOverviewRoute,
|
||||
studentStatusRoutes,
|
||||
@@ -48,6 +49,7 @@ for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/studen
|
||||
api.use(`${prefix}/*`, planReadOnly);
|
||||
}
|
||||
|
||||
api.route('/admin', adminRoutes);
|
||||
api.route('/auth', authRoutes);
|
||||
api.route('/health', healthCheckRoutes);
|
||||
api.route('/invitations', invitationsRoutes);
|
||||
|
||||
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: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await emailProvider.sendPasswordResetEmail({
|
||||
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 { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
||||
import {
|
||||
@@ -53,6 +53,21 @@ export function resolvePlan(
|
||||
return { plan: 'FREE', graceUntil: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `resolvePlan` written as a query, for listing accounts by plan: a
|
||||
* subscription is Pro when its paid period (or, before the first charge, its
|
||||
* authorization) is younger than the grace period. Keep both in step.
|
||||
*/
|
||||
export function proSubscriptionWhere(now: Date, graceDays: number): Prisma.BillingSubscriptionWhereInput {
|
||||
const cutoff = new Date(now.getTime() - graceDays * DAY_MS);
|
||||
return {
|
||||
OR: [
|
||||
{ paidThrough: { gt: cutoff } },
|
||||
{ paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export type PlanUsage = { groups: number; attendees: number };
|
||||
|
||||
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
|
||||
|
||||
@@ -5,6 +5,7 @@ export {
|
||||
PlanGuard,
|
||||
type PlanResolution,
|
||||
type PlanUsage,
|
||||
proSubscriptionWhere,
|
||||
resolvePlan,
|
||||
type SubscriptionSnapshot,
|
||||
} 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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user