diff --git a/teressa-copeland-homes/src/app/portal/(protected)/dashboard/page.tsx b/teressa-copeland-homes/src/app/portal/(protected)/dashboard/page.tsx index 24e9172..dc61f34 100644 --- a/teressa-copeland-homes/src/app/portal/(protected)/dashboard/page.tsx +++ b/teressa-copeland-homes/src/app/portal/(protected)/dashboard/page.tsx @@ -1,7 +1,7 @@ import { auth } from "@/lib/auth"; import { db } from "@/lib/db"; -import { documents, clients } from "@/lib/db/schema"; -import { eq, desc } from "drizzle-orm"; +import { documents, clients, signingTokens } from "@/lib/db/schema"; +import { eq, desc, sql } from "drizzle-orm"; import { DocumentsTable } from "../../_components/DocumentsTable"; import { DashboardFilters } from "../../_components/DashboardFilters"; @@ -25,16 +25,44 @@ export default async function DashboardPage({ signedAt: documents.signedAt, clientName: clients.name, clientId: documents.clientId, + signers: documents.signers, }) .from(documents) .leftJoin(clients, eq(documents.clientId, clients.id)) .orderBy(desc(documents.createdAt)); + // Fetch signing token counts per document in one query (avoids N+1) + const tokenCounts = await db + .select({ + documentId: signingTokens.documentId, + total: sql`count(*)`.as("total"), + signed: sql`count(${signingTokens.usedAt})`.as("signed"), + }) + .from(signingTokens) + .groupBy(signingTokens.documentId); + + const tokenMap = new Map( + tokenCounts.map((t) => [ + t.documentId, + { total: Number(t.total), signed: Number(t.signed) }, + ]) + ); + const filteredRows = status && (VALID_STATUSES as readonly string[]).includes(status) ? allRows.filter((r) => r.status === (status as ValidStatus)) : allRows; + const enrichedRows = filteredRows.map((row) => { + const tc = tokenMap.get(row.id); + return { + ...row, + signedCount: tc?.signed ?? null, + totalSigners: tc?.total ?? null, + hasMultipleSigners: Array.isArray(row.signers) && row.signers.length > 0, + }; + }); + const firstName = session?.user?.email?.split("@")[0] ?? "Agent"; return ( @@ -51,7 +79,7 @@ export default async function DashboardPage({ Filter by status: - + );