chore: add initial query

This commit is contained in:
Ephraim Atta-Duncan
2024-09-17 16:04:13 +00:00
parent 7644c0d855
commit 08d94cf2b2
9 changed files with 496 additions and 5 deletions

View File

@ -0,0 +1,25 @@
import { Trans } from '@lingui/macro';
import { setupI18nSSR } from '@documenso/lib/client-only/providers/i18n.server';
import { getSigningVolume } from '@documenso/lib/server-only/admin/get-signing-volume';
import { DataTableDemo as Table } from './table';
export default async function Leaderboard() {
setupI18nSSR();
const signingVolume = await getSigningVolume();
console.log(signingVolume);
return (
<div>
<h2 className="text-4xl font-semibold">
<Trans>Signing Volume</Trans>
</h2>
<div className="mt-8">
<Table />
</div>
</div>
);
}

View File

@ -0,0 +1,263 @@
'use client';
import * as React from 'react';
import type {
ColumnDef,
ColumnFiltersState,
SortingState,
VisibilityState,
} from '@tanstack/react-table';
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table';
import {
ChevronDownIcon as CaretSortIcon,
ChevronDownIcon as DotsHorizontalIcon,
} from 'lucide-react';
import { Button } from '@documenso/ui/primitives/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@documenso/ui/primitives/dropdown-menu';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@documenso/ui/primitives/table';
const data: Payment[] = [
{
id: 'm5gr84i9',
amount: 316,
status: 'success',
email: 'ken99@yahoo.com',
},
{
id: '3u1reuv4',
amount: 242,
status: 'success',
email: 'Abe45@gmail.com',
},
{
id: 'derv1ws0',
amount: 837,
status: 'processing',
email: 'Monserrat44@gmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
{
id: 'bhqecj4p',
amount: 721,
status: 'failed',
email: 'carmella@hotmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
];
export type Payment = {
id: string;
amount: number;
status: 'pending' | 'processing' | 'success' | 'failed';
email: string;
};
export const columns: ColumnDef<Payment>[] = [
{
accessorKey: 'status',
header: 'Status',
cell: ({ row }) => <div className="capitalize">{row.getValue('status')}</div>,
},
{
accessorKey: 'email',
header: ({ column }) => {
return (
<Button
variant="ghost"
className="pl-0 hover:bg-transparent"
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
>
Customers
<CaretSortIcon className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => <div className="lowercase">{row.getValue('email')}</div>,
},
{
accessorKey: 'amount',
header: () => <div className="text-right">Amount</div>,
cell: ({ row }) => {
const amount = parseFloat(row.getValue('amount'));
// Format the amount as a dollar amount
const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(amount);
return <div className="text-right font-medium">{formatted}</div>;
},
},
{
id: 'actions',
enableHiding: false,
cell: ({ row }) => {
const payment = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<DotsHorizontalIcon className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem onClick={async () => navigator.clipboard.writeText(payment.id)}>
Copy payment ID
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem>View customer</DropdownMenuItem>
<DropdownMenuItem>View payment details</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];
export function DataTableDemo() {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({});
const [rowSelection, setRowSelection] = React.useState({});
const table = useReactTable({
data,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
},
});
return (
<div className="w-full">
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow key={row.id} data-state={row.getIsSelected() && 'selected'}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-end space-x-2 py-4">
<div className="text-muted-foreground flex-1 text-sm">
{table.getFilteredSelectedRowModel().rows.length} of{' '}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>
</div>
</div>
);
}

View File

@ -6,7 +6,7 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Trans } from '@lingui/macro';
import { BarChart3, FileStack, Settings, Users, Wallet2 } from 'lucide-react';
import { BarChart3, FileStack, Settings, Trophy, Users, Wallet2 } from 'lucide-react';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
@ -80,6 +80,20 @@ export const AdminNav = ({ className, ...props }: AdminNavProps) => {
</Link>
</Button>
<Button
variant="ghost"
className={cn(
'justify-start md:w-full',
pathname?.startsWith('/admin/leaderboard') && 'bg-secondary',
)}
asChild
>
<Link href="/admin/leaderboard">
<Trophy className="mr-2 h-5 w-5" />
<Trans>Leaderboard</Trans>
</Link>
</Button>
<Button
variant="ghost"
className={cn(

View File

@ -0,0 +1,49 @@
import { prisma } from '@documenso/prisma';
export const getSigningVolume = async () => {
const results = await prisma.$queryRaw`
WITH paying_customers AS (
SELECT DISTINCT
COALESCE(s."userId", t."ownerUserId") AS customer_id,
CASE
WHEN s."userId" IS NOT NULL THEN 'User'
ELSE 'Team'
END AS customer_type,
COALESCE(s."createdAt", t."createdAt") AS customer_created_at
FROM "Subscription" s
FULL OUTER JOIN "Team" t ON s."teamId" = t.id
WHERE s.status = 'ACTIVE'
),
document_counts AS (
SELECT
COALESCE(d."userId", t."ownerUserId") AS customer_id,
COUNT(DISTINCT d.id) AS total_documents,
COUNT(DISTINCT CASE WHEN d.status = 'COMPLETED' THEN d.id END) AS completed_documents
FROM "Document" d
LEFT JOIN "Team" t ON d."teamId" = t.id
GROUP BY COALESCE(d."userId", t."ownerUserId")
)
SELECT
pc.customer_id,
pc.customer_type,
pc.customer_created_at,
COALESCE(dc.total_documents, 0) AS total_documents,
COALESCE(dc.completed_documents, 0) AS completed_documents,
CASE
WHEN pc.customer_type = 'User' THEN u.email
ELSE te.email
END AS customer_email,
CASE
WHEN pc.customer_type = 'User' THEN u.name
ELSE t.name
END AS customer_name
FROM paying_customers pc
LEFT JOIN document_counts dc ON pc.customer_id = dc.customer_id
LEFT JOIN "User" u ON pc.customer_id = u.id AND pc.customer_type = 'User'
LEFT JOIN "Team" t ON pc.customer_id = t."ownerUserId" AND pc.customer_type = 'Team'
LEFT JOIN "TeamEmail" te ON t.id = te."teamId"
ORDER BY dc.completed_documents DESC NULLS LAST, pc.customer_created_at DESC
`;
return results;
};

File diff suppressed because one or more lines are too long

View File

@ -1791,6 +1791,10 @@ msgstr ""
msgid "Last used"
msgstr ""
#: apps/web/src/app/(dashboard)/admin/nav.tsx:93
msgid "Leaderboard"
msgstr ""
#: apps/web/src/components/(teams)/dialogs/leave-team-dialog.tsx:111
#: apps/web/src/components/(teams)/tables/current-user-teams-data-table.tsx:117
msgid "Leave"
@ -2804,6 +2808,10 @@ msgstr ""
msgid "Signing up..."
msgstr ""
#: apps/web/src/app/(dashboard)/admin/leaderboard/page.tsx:18
msgid "Signing Volume"
msgstr ""
#: apps/web/src/app/(profile)/p/[url]/page.tsx:109
msgid "Since {0}"
msgstr ""
@ -2812,7 +2820,7 @@ msgstr ""
msgid "Site Banner"
msgstr ""
#: apps/web/src/app/(dashboard)/admin/nav.tsx:93
#: apps/web/src/app/(dashboard)/admin/nav.tsx:107
#: apps/web/src/app/(dashboard)/admin/site-settings/page.tsx:26
msgid "Site Settings"
msgstr ""

File diff suppressed because one or more lines are too long

View File

@ -1809,6 +1809,10 @@ msgstr "Last updated at"
msgid "Last used"
msgstr "Last used"
#: apps/web/src/app/(dashboard)/admin/nav.tsx:93
msgid "Leaderboard"
msgstr "Leaderboard"
#: apps/web/src/components/(teams)/dialogs/leave-team-dialog.tsx:111
#: apps/web/src/components/(teams)/tables/current-user-teams-data-table.tsx:117
msgid "Leave"
@ -2826,6 +2830,10 @@ msgstr "Signing in..."
msgid "Signing up..."
msgstr "Signing up..."
#: apps/web/src/app/(dashboard)/admin/leaderboard/page.tsx:18
msgid "Signing Volume"
msgstr "Signing Volume"
#: apps/web/src/app/(profile)/p/[url]/page.tsx:109
msgid "Since {0}"
msgstr "Since {0}"
@ -2834,7 +2842,7 @@ msgstr "Since {0}"
msgid "Site Banner"
msgstr "Site Banner"
#: apps/web/src/app/(dashboard)/admin/nav.tsx:93
#: apps/web/src/app/(dashboard)/admin/nav.tsx:107
#: apps/web/src/app/(dashboard)/admin/site-settings/page.tsx:26
msgid "Site Settings"
msgstr "Site Settings"

View File

@ -0,0 +1,124 @@
import type { Subscription, Team, User } from '@prisma/client';
import { DocumentDataType, PrismaClient } from '@prisma/client';
import fs from 'node:fs';
import path from 'node:path';
import { hashSync } from '@documenso/lib/server-only/auth/hash';
const prisma = new PrismaClient();
const examplePdf = fs
.readFileSync(path.join(__dirname, '../../assets/example.pdf'))
.toString('base64');
async function seedLeaderboardData(numUsers: number, numTeams: number) {
const users: User[] = [];
const teams: Team[] = [];
const subscriptions: Subscription[] = [];
// Create users with subscriptions
for (let i = 0; i < numUsers; i++) {
const user = await prisma.user.create({
data: {
name: `User ${i + 1}`,
email: `user${i + 1}@documenso.com`,
password: hashSync('password'),
emailVerified: new Date(),
},
});
users.push(user);
const subscription = await prisma.subscription.create({
data: {
userId: user.id,
status: 'ACTIVE',
planId: `plan_${Date.now().toString()}`,
priceId: `price_${Date.now().toString()}`,
},
});
subscriptions.push(subscription);
}
// Create teams
for (let i = 0; i < numTeams; i++) {
const ownerUser = users[Math.floor(Math.random() * users.length)];
const team = await prisma.team.create({
data: {
name: `Team ${i + 1}`,
url: `team-${Date.now().toString()}`,
ownerUserId: ownerUser.id,
},
});
teams.push(team);
// Add random users to the team
const teamMembers = users.filter((u) => u.id !== ownerUser.id).slice(0, 3);
for (const member of teamMembers) {
await prisma.teamMember.create({
data: {
teamId: team.id,
userId: member.id,
role: 'MEMBER',
},
});
}
}
// Create documents for each user
for (const user of users) {
const numDocuments = Math.floor(Math.random() * 10) + 1; // 1 to 5 documents per user
for (let i = 0; i < numDocuments; i++) {
const documentData = await prisma.documentData.create({
data: {
type: DocumentDataType.BYTES_64,
data: examplePdf,
initialData: examplePdf,
},
});
await prisma.document.create({
data: {
title: `Personal Document ${i + 1} for User ${user.id}`,
userId: user.id,
status: 'COMPLETED',
documentDataId: documentData.id,
source: 'DOCUMENT',
},
});
}
}
// Create documents for each team
for (const team of teams) {
const numDocuments = Math.floor(Math.random() * 10) + 1; // 1 to 10 documents per team
for (let i = 0; i < numDocuments; i++) {
const documentData = await prisma.documentData.create({
data: {
type: DocumentDataType.BYTES_64,
data: 'base64encodeddata', // Replace with actual data if needed
initialData: 'base64encodeddata', // Replace with actual data if needed
},
});
await prisma.document.create({
data: {
title: `Team Document ${i + 1} for Team ${team.id}`,
userId: team.ownerUserId, // Assign to team owner
teamId: team.id,
status: 'COMPLETED',
documentDataId: documentData.id,
source: 'DOCUMENT',
},
});
}
}
console.log(`Seeded ${users.length} users, ${teams.length} teams, and their documents.`);
}
// Usage
seedLeaderboardData(50, 10)
.catch((e) => console.error(e))
.finally(() => {
void prisma.$disconnect();
});