import { beforeEach, describe, expect, it, vi } from 'vitest' import { listBillingAccounts } from './admin.billing.service' import { prisma } from '../../lib/prisma' vi.mock('../../lib/prisma', () => ({ prisma: { subscriptionInvoice: { findMany: vi.fn() }, company: { findMany: vi.fn(), findUniqueOrThrow: vi.fn() }, billingAccount: { findMany: vi.fn(), count: vi.fn(), create: vi.fn(), updateMany: vi.fn(), findUniqueOrThrow: vi.fn(), }, billingInvoice: { groupBy: vi.fn(), findFirst: vi.fn(), create: vi.fn() }, billingCreditBalance: { create: vi.fn() }, billingEvent: { create: vi.fn() }, }, })) vi.mock('../../services/invoicePdfService', () => ({ generateInvoicePdf: vi.fn(), })) describe('admin billing service', () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(prisma.subscriptionInvoice.findMany).mockResolvedValue([]) vi.mocked(prisma.company.findMany).mockResolvedValue([{ id: 'company_1' }] as never) vi.mocked(prisma.billingAccount.count).mockResolvedValue(1 as never) vi.mocked(prisma.billingInvoice.groupBy) .mockResolvedValueOnce([ { billingAccountId: 'billing_empty', _count: { _all: 0 }, _sum: { amountDue: 0 } }, { billingAccountId: 'billing_due', _count: { _all: 1 }, _sum: { amountDue: 14900 } }, ] as never) .mockResolvedValueOnce([ { status: 'OPEN', _count: { _all: 1 }, _sum: { amountDue: 14900, totalAmount: 14900 } }, ] as never) }) it('demotes duplicate primary billing accounts and lists only the canonical company row', async () => { vi.mocked(prisma.billingAccount.findMany) .mockResolvedValueOnce([ { id: 'billing_empty', companyId: 'company_1', isPrimary: true, createdAt: new Date('2026-08-10T12:00:00.000Z'), creditBalances: [] }, { id: 'billing_due', companyId: 'company_1', isPrimary: true, createdAt: new Date('2026-08-09T12:00:00.000Z'), creditBalances: [] }, ] as never) .mockResolvedValueOnce([ { id: 'billing_due', companyId: 'company_1', isPrimary: true, legalName: 'Atlas car', billingEmail: 'moulay.elabidi@gmail.com', createdAt: new Date('2026-08-09T12:00:00.000Z'), company: { id: 'company_1', name: 'Atlas car', email: 'moulay.elabidi@gmail.com', slug: 'atlas-car', status: 'PENDING', subscription: { status: 'PAYMENT_PENDING' } }, creditBalances: [], invoices: [{ id: 'invoice_1', status: 'OPEN', amountDue: 14900, amountPaid: 0, currency: 'MAD' }], }, ] as never) const result = await listBillingAccounts({ page: 1, pageSize: 100 }) expect(prisma.billingAccount.updateMany).toHaveBeenCalledWith({ where: { companyId: 'company_1', id: { not: 'billing_due' }, isPrimary: true }, data: { isPrimary: false }, }) expect(prisma.billingAccount.findMany).toHaveBeenLastCalledWith(expect.objectContaining({ where: { isPrimary: true }, })) expect(result.data).toHaveLength(1) expect(result.data[0].id).toBe('billing_due') expect(result.data[0].openBalance).toBe(14900) }) })