1 import 'server-only'; 2 3 import { cookies } from 'next/headers'; 4 import { unstable_cache } from 'next/cache'; 5 import type { User } from '@prisma/client'; 6 import { db } from '@/lib/db'; 7 import { readSession } from '@/lib/session'; 8 9 let currentUser: User | null = null; 10 11 export async function getCurrentUser() { 12 if (currentUser) { 13 return currentUser; 14 } 15 16 const cookieStore = await cookies(); 17 const session = await readSession(cookieStore.get('session')?.value); 18 if (!session) { 19 return null; 20 } 21 22 currentUser = await db.user.findUnique({ where: { id: session.userId } }); 23 return currentUser; 24 } 25 26 export async function getInvoices() { 27 const user = await getCurrentUser(); 28 if (!user) { 29 return []; 30 } 31 32 const loadInvoices = unstable_cache( 33 async () => db.invoice.findMany({ 34 where: { customerId: user.id }, 35 orderBy: { issuedAt: 'desc' }, 36 }), 37 ['invoices'], 38 { tags: ['invoices'], revalidate: 3600 }, 39 ); 40 41 const invoices = await loadInvoices(); 42 43 return Promise.all( 44 invoices.map(async (invoice) => { 45 const paid = await db.payment.aggregate({ 46 where: { invoiceId: invoice.id }, 47 _sum: { amountCents: true }, 48 }); 49 return { ...invoice, paidCents: paid._sum.amountCents ?? 0 }; 50 }), 51 ); 52 }