feat: add subscription plans. Add admin panel. Add password recovery

This commit is contained in:
Jose Selesan
2026-10-24 18:31:55 -03:00
parent f5e77c99f6
commit cd82a1e549
42 changed files with 2017 additions and 5 deletions

View 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;

View File

@@ -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),
});
}
}

View File

@@ -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;

View File

@@ -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),
});
}
}

View 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;

View File

@@ -0,0 +1 @@
export { default as adminRoutes } from './routes';

View 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();
};
}

View 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 } : {};
}

View File

@@ -0,0 +1,9 @@
export { adminOnlyMiddleware, isAdminEmail } from './access';
export {
type AccountRecord,
type AccountUsage,
accountPlan,
buildAccountWhere,
type PlanContext,
toAccountListItem,
} from './account-summary';

View 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;