import { afterAll, beforeEach, describe, expect, it, mock } from 'bun:test'; import { Hono } from 'hono'; const db = { user: { findMany: mock(), count: mock(), findUnique: mock() }, group: { findMany: mock() }, billingCharge: { findMany: mock() }, }; mock.module('@/lib/prisma', () => ({ default: db, getPrismaClient: mock(), UnitOfWork: class {}, })); import { adminRoutes } from '@/modules/admin'; import { GetAccount } from '@/modules/admin/features/get-account/use-case'; import { ListAccounts } from '@/modules/admin/features/list-accounts/use-case'; import { buildAccountWhere, isAdminEmail } from '@/modules/admin/lib'; const now = new Date('2026-10-22T12:00:00.000Z'); const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000); const context = { now, graceDays: 7 }; function subscription(overrides: Record = {}) { return { id: 'sub-1', userId: 'u1', country: 'AR', currency: 'ARS', amount: { toString: () => '15000' }, payerEmail: 'pagos@ana.com', mpPreapprovalId: 'pre-1', status: 'AUTHORIZED', requestedAt: days(-40), authorizedAt: days(-40), nextPaymentDate: days(20), paidThrough: days(10), lastSyncedAt: null, createdAt: days(-40), updatedAt: days(-1), ...overrides, }; } function user(id: string, overrides: Record = {}) { return { id, name: `Profe ${id}`, email: `${id}@gruperly.test`, country: 'AR', createdAt: days(-60), onboardingCompleted: true, planSelectedAt: days(-60), subscription: null, ...overrides, }; } function makeApp(email: string | null) { const app = new Hono(); app.use('*', async (c, next) => { c.set('user', email ? ({ id: 'staff-1', email } as never) : null); await next(); }); app.route('/admin', adminRoutes); return app; } const previousAdminEmails = process.env.ADMIN_EMAILS; beforeEach(() => { process.env.ADMIN_EMAILS = 'staff@gruperly.com, Otra@Gruperly.com'; db.user.findMany.mockReset(); db.user.count.mockReset(); db.user.findUnique.mockReset(); db.group.findMany.mockReset(); db.billingCharge.findMany.mockReset(); }); afterAll(() => { process.env.ADMIN_EMAILS = previousAdminEmails; }); describe('admin access', () => { it('matches the allowlist ignoring case and spaces', () => { const env = { ADMIN_EMAILS: ' staff@gruperly.com ,Otra@Gruperly.com' }; expect(isAdminEmail('STAFF@gruperly.com', env)).toBe(true); expect(isAdminEmail('otra@gruperly.com', env)).toBe(true); expect(isAdminEmail('profe@gmail.com', env)).toBe(false); }); it('lets nobody in with an empty allowlist', () => { expect(isAdminEmail('staff@gruperly.com', {})).toBe(false); expect(isAdminEmail('', { ADMIN_EMAILS: ',' })).toBe(false); }); it('tells any signed-in user whether they are an admin', async () => { const admin = await makeApp('staff@gruperly.com').request('/admin/me'); expect(await admin.json()).toEqual({ isAdmin: true }); const professor = await makeApp('profe@gmail.com').request('/admin/me'); expect(professor.status).toBe(200); expect(await professor.json()).toEqual({ isAdmin: false }); }); it('forbids the accounts to anyone outside the allowlist', async () => { const list = await makeApp('profe@gmail.com').request('/admin/accounts'); expect(list.status).toBe(403); expect(await list.json()).toMatchObject({ code: 'admin_required' }); const detail = await makeApp('profe@gmail.com').request('/admin/accounts/u1'); expect(detail.status).toBe(403); expect(db.user.findUnique).not.toHaveBeenCalled(); }); it('forbids the plans to anyone outside the allowlist', async () => { const app = makeApp('profe@gmail.com'); expect((await app.request('/admin/plans')).status).toBe(403); expect((await app.request('/admin/plans/FREE/impact?maxGroups=1')).status).toBe(403); const json = { 'Content-Type': 'application/json' }; const limits = await app.request('/admin/plans/FREE/limits', { method: 'PUT', headers: json, body: JSON.stringify({ maxGroups: 1, maxAttendees: 1, whatsappAutomations: false, mpCharges: false }), }); expect(limits.status).toBe(403); const price = await app.request('/admin/plans/prices/AR', { method: 'PUT', headers: json, body: JSON.stringify({ amount: 1, applyToExisting: true }), }); expect(price.status).toBe(403); }); 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(); }); });