feat: add subscription plans. Add admin panel. Add password recovery
This commit is contained in:
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;
|
||||
Reference in New Issue
Block a user