mirror of
https://github.com/documenso/documenso.git
synced 2025-11-20 03:32:14 +10:00
chore: minor changes
This commit is contained in:
@ -4,6 +4,7 @@ import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
|
||||
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@ -13,7 +14,7 @@ import {
|
||||
} from '@documenso/ui/primitives/select';
|
||||
|
||||
type DateRangeFilterProps = {
|
||||
currentRange: string;
|
||||
currentRange: DateRange;
|
||||
};
|
||||
|
||||
export const DateRangeFilter = ({ currentRange }: DateRangeFilterProps) => {
|
||||
@ -24,7 +25,7 @@ export const DateRangeFilter = ({ currentRange }: DateRangeFilterProps) => {
|
||||
const handleRangeChange = (value: string) => {
|
||||
startTransition(() => {
|
||||
updateSearchParams({
|
||||
dateRange: value,
|
||||
dateRange: value as DateRange,
|
||||
page: 1,
|
||||
});
|
||||
});
|
||||
@ -32,7 +33,6 @@ export const DateRangeFilter = ({ currentRange }: DateRangeFilterProps) => {
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{_(msg`Time Range:`)}</span>
|
||||
<Select value={currentRange} onValueChange={handleRangeChange} disabled={isPending}>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue />
|
||||
|
||||
@ -3,6 +3,7 @@ import { useEffect, useMemo, useState, useTransition } from 'react';
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { useLingui } from '@lingui/react';
|
||||
import { ChevronDownIcon, ChevronUpIcon, ChevronsUpDown, Loader } from 'lucide-react';
|
||||
import { Link } from 'react-router';
|
||||
|
||||
import { useDebouncedValue } from '@documenso/lib/client-only/hooks/use-debounced-value';
|
||||
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
|
||||
@ -16,7 +17,7 @@ export type OrganisationOverview = {
|
||||
name: string;
|
||||
signingVolume: number;
|
||||
createdAt: Date;
|
||||
planId: string;
|
||||
customerId: string;
|
||||
subscriptionStatus?: string;
|
||||
isActive?: boolean;
|
||||
teamCount?: number;
|
||||
@ -71,16 +72,16 @@ export const AdminOrganisationOverviewTable = ({
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<a
|
||||
<Link
|
||||
className="text-primary underline"
|
||||
href={`/admin/organisation-insights/${row.original.id}`}
|
||||
to={`/admin/organisation-insights/${row.original.id}`}
|
||||
>
|
||||
{row.getValue('name')}
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
size: 200,
|
||||
size: 240,
|
||||
},
|
||||
{
|
||||
header: () => (
|
||||
@ -88,7 +89,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
className="flex cursor-pointer items-center"
|
||||
onClick={() => handleColumnSort('signingVolume')}
|
||||
>
|
||||
{_(msg`Document Volume`)}
|
||||
<span className="whitespace-nowrap">{_(msg`Document Volume`)}</span>
|
||||
{sortBy === 'signingVolume' ? (
|
||||
sortOrder === 'asc' ? (
|
||||
<ChevronUpIcon className="ml-2 h-4 w-4" />
|
||||
@ -102,26 +103,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
),
|
||||
accessorKey: 'signingVolume',
|
||||
cell: ({ row }) => <div>{Number(row.getValue('signingVolume'))}</div>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
header: () => {
|
||||
return <div>{_(msg`Status`)}</div>;
|
||||
},
|
||||
accessorKey: 'subscriptionStatus',
|
||||
cell: ({ row }) => {
|
||||
const status = row.original.subscriptionStatus;
|
||||
return (
|
||||
<div
|
||||
className={`inline-flex items-center rounded-full px-2 py-1 text-xs font-medium ${
|
||||
status ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{status || 'Free'}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
size: 100,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
header: () => {
|
||||
@ -129,7 +111,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
},
|
||||
accessorKey: 'teamCount',
|
||||
cell: ({ row }) => <div>{Number(row.original.teamCount) || 0}</div>,
|
||||
size: 80,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
header: () => {
|
||||
@ -137,7 +119,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
},
|
||||
accessorKey: 'memberCount',
|
||||
cell: ({ row }) => <div>{Number(row.original.memberCount) || 0}</div>,
|
||||
size: 80,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
header: () => {
|
||||
@ -146,7 +128,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
className="flex cursor-pointer items-center"
|
||||
onClick={() => handleColumnSort('createdAt')}
|
||||
>
|
||||
{_(msg`Created`)}
|
||||
<span className="whitespace-nowrap">{_(msg`Created`)}</span>
|
||||
{sortBy === 'createdAt' ? (
|
||||
sortOrder === 'asc' ? (
|
||||
<ChevronUpIcon className="ml-2 h-4 w-4" />
|
||||
@ -160,7 +142,7 @@ export const AdminOrganisationOverviewTable = ({
|
||||
);
|
||||
},
|
||||
accessorKey: 'createdAt',
|
||||
cell: ({ row }) => i18n.date(row.original.createdAt),
|
||||
cell: ({ row }) => i18n.date(new Date(row.original.createdAt)),
|
||||
size: 120,
|
||||
},
|
||||
] satisfies DataTableColumnDef<OrganisationOverview>[];
|
||||
|
||||
@ -93,7 +93,8 @@ export const AdminOrganisationsTable = ({
|
||||
),
|
||||
},
|
||||
{
|
||||
header: t`Status`,
|
||||
id: 'role',
|
||||
header: t`Role`,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="neutral">
|
||||
{row.original.owner.id === memberUserId ? t`Owner` : t`Member`}
|
||||
@ -101,6 +102,7 @@ export const AdminOrganisationsTable = ({
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'billingStatus',
|
||||
header: t`Status`,
|
||||
cell: ({ row }) => {
|
||||
const subscription = row.original.subscription;
|
||||
@ -111,7 +113,7 @@ export const AdminOrganisationsTable = ({
|
||||
isPaid ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{isPaid ? 'Paid' : 'Free'}
|
||||
{isPaid ? t`Paid` : t`Free`}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
@ -184,7 +186,7 @@ export const AdminOrganisationsTable = ({
|
||||
onPaginationChange={onPaginationChange}
|
||||
columnVisibility={{
|
||||
owner: showOwnerColumn,
|
||||
status: memberUserId !== undefined,
|
||||
role: memberUserId !== undefined,
|
||||
}}
|
||||
error={{
|
||||
enable: isLoadingError,
|
||||
|
||||
@ -6,18 +6,21 @@ import { Archive, Building2, Loader, TrendingUp, Users } from 'lucide-react';
|
||||
|
||||
import { useUpdateSearchParams } from '@documenso/lib/client-only/hooks/use-update-search-params';
|
||||
import type { OrganisationDetailedInsights } from '@documenso/lib/server-only/admin/get-organisation-detailed-insights';
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
import type { ExtendedDocumentStatus } from '@documenso/prisma/types/extended-document-status';
|
||||
import { Button } from '@documenso/ui/primitives/button';
|
||||
import type { DataTableColumnDef } from '@documenso/ui/primitives/data-table';
|
||||
import { DataTable } from '@documenso/ui/primitives/data-table';
|
||||
import { DataTablePagination } from '@documenso/ui/primitives/data-table-pagination';
|
||||
|
||||
import { DateRangeFilter } from '~/components/filters/date-range-filter';
|
||||
import { DocumentStatus } from '~/components/general/document/document-status';
|
||||
|
||||
type OrganisationInsightsTableProps = {
|
||||
insights: OrganisationDetailedInsights;
|
||||
page: number;
|
||||
perPage: number;
|
||||
dateRange: string;
|
||||
dateRange: DateRange;
|
||||
view: 'teams' | 'users' | 'documents';
|
||||
};
|
||||
|
||||
@ -54,82 +57,104 @@ export const OrganisationInsightsTable = ({
|
||||
{
|
||||
header: _(msg`Team Name`),
|
||||
accessorKey: 'name',
|
||||
cell: ({ row }) => row.getValue('name'),
|
||||
cell: ({ row }) => <span className="block max-w-full truncate">{row.getValue('name')}</span>,
|
||||
size: 240,
|
||||
},
|
||||
{
|
||||
header: _(msg`Members`),
|
||||
accessorKey: 'memberCount',
|
||||
cell: ({ row }) => Number(row.getValue('memberCount')),
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
header: _(msg`Documents`),
|
||||
accessorKey: 'documentCount',
|
||||
cell: ({ row }) => Number(row.getValue('documentCount')),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
header: _(msg`Created`),
|
||||
accessorKey: 'createdAt',
|
||||
cell: ({ row }) => i18n.date(row.getValue('createdAt')),
|
||||
cell: ({ row }) => i18n.date(new Date(row.getValue('createdAt'))),
|
||||
size: 160,
|
||||
},
|
||||
] satisfies DataTableColumnDef<(typeof insights.teams)[number]>[];
|
||||
|
||||
const usersColumns = [
|
||||
{
|
||||
header: _(msg`Name`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Name`)}</span>,
|
||||
accessorKey: 'name',
|
||||
cell: ({ row }) => row.getValue('name') || row.getValue('email'),
|
||||
cell: ({ row }) => (
|
||||
<span className="block max-w-full truncate">
|
||||
{(row.getValue('name') as string) || (row.getValue('email') as string)}
|
||||
</span>
|
||||
),
|
||||
size: 220,
|
||||
},
|
||||
{
|
||||
header: _(msg`Email`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Email`)}</span>,
|
||||
accessorKey: 'email',
|
||||
cell: ({ row }) => row.getValue('email'),
|
||||
cell: ({ row }) => <span className="block max-w-full truncate">{row.getValue('email')}</span>,
|
||||
size: 260,
|
||||
},
|
||||
{
|
||||
header: _(msg`Documents Created`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Documents Created`)}</span>,
|
||||
accessorKey: 'documentCount',
|
||||
cell: ({ row }) => Number(row.getValue('documentCount')),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
header: _(msg`Documents Signed`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Documents Signed`)}</span>,
|
||||
accessorKey: 'signedDocumentCount',
|
||||
cell: ({ row }) => Number(row.getValue('signedDocumentCount')),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
header: _(msg`Joined`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Joined`)}</span>,
|
||||
accessorKey: 'createdAt',
|
||||
cell: ({ row }) => i18n.date(row.getValue('createdAt')),
|
||||
cell: ({ row }) => i18n.date(new Date(row.getValue('createdAt'))),
|
||||
size: 160,
|
||||
},
|
||||
] satisfies DataTableColumnDef<(typeof insights.users)[number]>[];
|
||||
|
||||
const documentsColumns = [
|
||||
{
|
||||
header: _(msg`Title`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Title`)}</span>,
|
||||
accessorKey: 'title',
|
||||
cell: ({ row }) => row.getValue('title'),
|
||||
cell: ({ row }) => <span className="block max-w-full truncate">{row.getValue('title')}</span>,
|
||||
size: 240,
|
||||
},
|
||||
{
|
||||
header: _(msg`Status`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Status`)}</span>,
|
||||
accessorKey: 'status',
|
||||
cell: ({ row }) => row.getValue('status'),
|
||||
cell: ({ row }) => (
|
||||
<DocumentStatus status={row.getValue('status') as ExtendedDocumentStatus} />
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
header: _(msg`Team`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Team`)}</span>,
|
||||
accessorKey: 'teamName',
|
||||
cell: ({ row }) => row.getValue('teamName'),
|
||||
cell: ({ row }) => (
|
||||
<span className="block max-w-full truncate">{row.getValue('teamName')}</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
header: _(msg`Created`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Created`)}</span>,
|
||||
accessorKey: 'createdAt',
|
||||
cell: ({ row }) => i18n.date(row.getValue('createdAt')),
|
||||
cell: ({ row }) => i18n.date(new Date(row.getValue('createdAt'))),
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
header: _(msg`Completed`),
|
||||
header: () => <span className="whitespace-nowrap">{_(msg`Completed`)}</span>,
|
||||
accessorKey: 'completedAt',
|
||||
cell: ({ row }) => {
|
||||
const completedAt = row.getValue('completedAt') as Date | null;
|
||||
|
||||
return completedAt ? i18n.date(completedAt) : '-';
|
||||
return completedAt ? i18n.date(new Date(completedAt)) : '-';
|
||||
},
|
||||
size: 160,
|
||||
},
|
||||
] satisfies DataTableColumnDef<(typeof insights.documents)[number]>[];
|
||||
|
||||
|
||||
@ -114,7 +114,7 @@ export default function AdminLayout() {
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'justify-start md:w-full',
|
||||
pathname?.startsWith('/admin/org-insights') && 'bg-secondary',
|
||||
pathname?.startsWith('/admin/organisation-insights') && 'bg-secondary',
|
||||
)}
|
||||
asChild
|
||||
>
|
||||
@ -128,7 +128,7 @@ export default function AdminLayout() {
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
'justify-start md:w-full',
|
||||
pathname?.startsWith('/admin/banner') && 'bg-secondary',
|
||||
pathname?.startsWith('/admin/site-settings') && 'bg-secondary',
|
||||
)}
|
||||
asChild
|
||||
>
|
||||
|
||||
@ -57,6 +57,7 @@ export default function AdminDocumentsPage() {
|
||||
header: _(msg`Created`),
|
||||
accessorKey: 'createdAt',
|
||||
cell: ({ row }) => i18n.date(row.original.createdAt),
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
header: _(msg`Title`),
|
||||
@ -65,17 +66,19 @@ export default function AdminDocumentsPage() {
|
||||
return (
|
||||
<Link
|
||||
to={`/admin/documents/${row.original.id}`}
|
||||
className="block max-w-[5rem] truncate font-medium hover:underline md:max-w-[10rem]"
|
||||
className="block truncate font-medium hover:underline"
|
||||
>
|
||||
{row.original.title}
|
||||
</Link>
|
||||
);
|
||||
},
|
||||
size: 240,
|
||||
},
|
||||
{
|
||||
header: _(msg`Status`),
|
||||
accessorKey: 'status',
|
||||
cell: ({ row }) => <DocumentStatus status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
header: _(msg`Owner`),
|
||||
@ -112,11 +115,13 @@ export default function AdminDocumentsPage() {
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
header: 'Last updated',
|
||||
accessorKey: 'updatedAt',
|
||||
cell: ({ row }) => i18n.date(row.original.updatedAt),
|
||||
size: 160,
|
||||
},
|
||||
] satisfies DataTableColumnDef<(typeof results)['data'][number]>[];
|
||||
}, []);
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
|
||||
import { getOrganisationDetailedInsights } from '@documenso/lib/server-only/admin/get-organisation-detailed-insights';
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
import { getAdminOrganisation } from '@documenso/trpc/server/admin-router/get-admin-organisation';
|
||||
|
||||
import { OrganisationInsightsTable } from '~/components/tables/organisation-insights-table';
|
||||
@ -13,11 +12,7 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
|
||||
const page = Number(url.searchParams.get('page')) || 1;
|
||||
const perPage = Number(url.searchParams.get('perPage')) || 10;
|
||||
const dateRange = (url.searchParams.get('dateRange') || 'last30days') as
|
||||
| 'last30days'
|
||||
| 'last90days'
|
||||
| 'lastYear'
|
||||
| 'allTime';
|
||||
const dateRange = (url.searchParams.get('dateRange') || 'last30days') as DateRange;
|
||||
const view = (url.searchParams.get('view') || 'teams') as 'teams' | 'users' | 'documents';
|
||||
|
||||
const [insights, organisation] = await Promise.all([
|
||||
@ -48,9 +43,7 @@ export default function OrganisationInsights({ loaderData }: Route.ComponentProp
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-4xl font-semibold">
|
||||
<Trans>{organisationName}</Trans>
|
||||
</h2>
|
||||
<h2 className="text-4xl font-semibold">{organisationName}</h2>
|
||||
</div>
|
||||
<div className="mt-8">
|
||||
<OrganisationInsightsTable
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
|
||||
import { getOrganisationInsights } from '@documenso/lib/server-only/admin/get-signing-volume';
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
|
||||
import { DateRangeFilter } from '~/components/filters/date-range-filter';
|
||||
import {
|
||||
@ -16,23 +17,20 @@ export async function loader({ request }: Route.LoaderArgs) {
|
||||
const rawSortBy = url.searchParams.get('sortBy') || 'signingVolume';
|
||||
const rawSortOrder = url.searchParams.get('sortOrder') || 'desc';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
const sortOrder = (['asc', 'desc'].includes(rawSortOrder) ? rawSortOrder : 'desc') as
|
||||
| 'asc'
|
||||
| 'desc';
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
const sortBy = (
|
||||
['name', 'createdAt', 'signingVolume'].includes(rawSortBy) ? rawSortBy : 'signingVolume'
|
||||
) as 'name' | 'createdAt' | 'signingVolume';
|
||||
const isSortOrder = (value: string): value is 'asc' | 'desc' =>
|
||||
value === 'asc' || value === 'desc';
|
||||
const isSortBy = (value: string): value is 'name' | 'createdAt' | 'signingVolume' =>
|
||||
value === 'name' || value === 'createdAt' || value === 'signingVolume';
|
||||
|
||||
const sortOrder: 'asc' | 'desc' = isSortOrder(rawSortOrder) ? rawSortOrder : 'desc';
|
||||
const sortBy: 'name' | 'createdAt' | 'signingVolume' = isSortBy(rawSortBy)
|
||||
? rawSortBy
|
||||
: 'signingVolume';
|
||||
|
||||
const page = Number(url.searchParams.get('page')) || 1;
|
||||
const perPage = Number(url.searchParams.get('perPage')) || 10;
|
||||
const search = url.searchParams.get('search') || '';
|
||||
const dateRange = (url.searchParams.get('dateRange') || 'last30days') as
|
||||
| 'last30days'
|
||||
| 'last90days'
|
||||
| 'lastYear'
|
||||
| 'allTime';
|
||||
const dateRange = (url.searchParams.get('dateRange') || 'last30days') as DateRange;
|
||||
|
||||
const { organisations, totalPages } = await getOrganisationInsights({
|
||||
search,
|
||||
@ -48,7 +46,7 @@ export async function loader({ request }: Route.LoaderArgs) {
|
||||
name: item.name || '',
|
||||
signingVolume: item.signingVolume,
|
||||
createdAt: item.createdAt || new Date(),
|
||||
planId: item.customerId || '',
|
||||
customerId: item.customerId || '',
|
||||
subscriptionStatus: item.subscriptionStatus,
|
||||
teamCount: item.teamCount || 0,
|
||||
memberCount: item.memberCount || 0,
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import type { DocumentStatus } from '@prisma/client';
|
||||
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
import { kyselyPrisma, sql } from '@documenso/prisma';
|
||||
|
||||
export type OrganisationSummary = {
|
||||
@ -50,7 +51,7 @@ export type GetOrganisationDetailedInsightsOptions = {
|
||||
organisationId: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
dateRange?: 'last30days' | 'last90days' | 'lastYear' | 'allTime';
|
||||
dateRange?: DateRange;
|
||||
view: 'teams' | 'users' | 'documents';
|
||||
};
|
||||
|
||||
@ -63,42 +64,38 @@ export async function getOrganisationDetailedInsights({
|
||||
}: GetOrganisationDetailedInsightsOptions): Promise<OrganisationDetailedInsights> {
|
||||
const offset = Math.max(page - 1, 0) * perPage;
|
||||
|
||||
let dateFilter = sql``;
|
||||
const now = new Date();
|
||||
let createdAtFrom: Date | null = null;
|
||||
|
||||
switch (dateRange) {
|
||||
case 'last30days': {
|
||||
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
dateFilter = sql`AND d."createdAt" >= ${thirtyDaysAgo}`;
|
||||
createdAtFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
break;
|
||||
}
|
||||
case 'last90days': {
|
||||
const ninetyDaysAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
|
||||
dateFilter = sql`AND d."createdAt" >= ${ninetyDaysAgo}`;
|
||||
createdAtFrom = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
|
||||
break;
|
||||
}
|
||||
case 'lastYear': {
|
||||
const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
|
||||
dateFilter = sql`AND d."createdAt" >= ${oneYearAgo}`;
|
||||
createdAtFrom = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
|
||||
break;
|
||||
}
|
||||
case 'allTime':
|
||||
default:
|
||||
dateFilter = sql``;
|
||||
createdAtFrom = null;
|
||||
break;
|
||||
}
|
||||
|
||||
// Get organisation summary metrics
|
||||
const summaryData = await getOrganisationSummary(organisationId, dateFilter);
|
||||
const summaryData = await getOrganisationSummary(organisationId, createdAtFrom);
|
||||
|
||||
const viewData = await (async () => {
|
||||
switch (view) {
|
||||
case 'teams':
|
||||
return await getTeamInsights(organisationId, offset, perPage, dateFilter);
|
||||
return await getTeamInsights(organisationId, offset, perPage, createdAtFrom);
|
||||
case 'users':
|
||||
return await getUserInsights(organisationId, offset, perPage, dateFilter);
|
||||
return await getUserInsights(organisationId, offset, perPage, createdAtFrom);
|
||||
case 'documents':
|
||||
return await getDocumentInsights(organisationId, offset, perPage, dateFilter);
|
||||
return await getDocumentInsights(organisationId, offset, perPage, createdAtFrom);
|
||||
default:
|
||||
throw new Error(`Invalid view: ${view}`);
|
||||
}
|
||||
@ -114,8 +111,7 @@ async function getTeamInsights(
|
||||
organisationId: string,
|
||||
offset: number,
|
||||
perPage: number,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
dateFilter: any,
|
||||
createdAtFrom: Date | null,
|
||||
): Promise<OrganisationDetailedInsights> {
|
||||
const teamsQuery = kyselyPrisma.$kysely
|
||||
.selectFrom('Team as t')
|
||||
@ -132,9 +128,10 @@ async function getTeamInsights(
|
||||
't.name as name',
|
||||
't.createdAt as createdAt',
|
||||
sql<number>`COUNT(DISTINCT om."userId")`.as('memberCount'),
|
||||
sql<number>`COUNT(DISTINCT CASE WHEN d.id IS NOT NULL ${dateFilter} THEN d.id END)`.as(
|
||||
'documentCount',
|
||||
),
|
||||
(createdAtFrom
|
||||
? sql<number>`COUNT(DISTINCT CASE WHEN d.id IS NOT NULL AND d."createdAt" >= ${createdAtFrom} THEN d.id END)`
|
||||
: sql<number>`COUNT(DISTINCT d.id)`
|
||||
).as('documentCount'),
|
||||
])
|
||||
.groupBy(['t.id', 't.name', 't.createdAt'])
|
||||
.orderBy('documentCount', 'desc')
|
||||
@ -161,26 +158,42 @@ async function getUserInsights(
|
||||
organisationId: string,
|
||||
offset: number,
|
||||
perPage: number,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, unused-imports/no-unused-vars
|
||||
_dateFilter: any,
|
||||
createdAtFrom: Date | null,
|
||||
): Promise<OrganisationDetailedInsights> {
|
||||
const usersQuery = kyselyPrisma.$kysely
|
||||
const usersBase = kyselyPrisma.$kysely
|
||||
.selectFrom('OrganisationMember as om')
|
||||
.innerJoin('User as u', 'u.id', 'om.userId')
|
||||
.where('om.organisationId', '=', organisationId)
|
||||
.leftJoin('Document as d', (join) =>
|
||||
join.onRef('d.userId', '=', 'u.id').on('d.deletedAt', 'is', null),
|
||||
)
|
||||
.leftJoin('Team as td', (join) =>
|
||||
join.onRef('td.id', '=', 'd.teamId').on('td.organisationId', '=', organisationId),
|
||||
)
|
||||
.leftJoin('Recipient as r', (join) =>
|
||||
join.onRef('r.email', '=', 'u.email').on('r.signedAt', 'is not', null),
|
||||
)
|
||||
.where('om.organisationId', '=', organisationId)
|
||||
.leftJoin('Document as sd', (join) =>
|
||||
join.onRef('sd.id', '=', 'r.documentId').on('sd.deletedAt', 'is', null),
|
||||
)
|
||||
.leftJoin('Team as ts', (join) =>
|
||||
join.onRef('ts.id', '=', 'sd.teamId').on('ts.organisationId', '=', organisationId),
|
||||
);
|
||||
|
||||
const usersQuery = usersBase
|
||||
.select([
|
||||
'u.id as id',
|
||||
'u.name as name',
|
||||
'u.email as email',
|
||||
'u.createdAt as createdAt',
|
||||
sql<number>`COUNT(DISTINCT d.id)`.as('documentCount'),
|
||||
sql<number>`COUNT(DISTINCT r.id)`.as('signedDocumentCount'),
|
||||
(createdAtFrom
|
||||
? sql<number>`COUNT(DISTINCT CASE WHEN d.id IS NOT NULL AND td.id IS NOT NULL AND d."createdAt" >= ${createdAtFrom} THEN d.id END)`
|
||||
: sql<number>`COUNT(DISTINCT CASE WHEN td.id IS NOT NULL THEN d.id END)`
|
||||
).as('documentCount'),
|
||||
(createdAtFrom
|
||||
? sql<number>`COUNT(DISTINCT CASE WHEN r.id IS NOT NULL AND ts.id IS NOT NULL AND r."signedAt" >= ${createdAtFrom} AND r.role = 'SIGNER'::"RecipientRole" THEN r.id END)`
|
||||
: sql<number>`COUNT(DISTINCT CASE WHEN ts.id IS NOT NULL AND r.role = 'SIGNER'::"RecipientRole" THEN r.id END)`
|
||||
).as('signedDocumentCount'),
|
||||
])
|
||||
.groupBy(['u.id', 'u.name', 'u.email', 'u.createdAt'])
|
||||
.orderBy('u.createdAt', 'desc')
|
||||
@ -208,8 +221,7 @@ async function getDocumentInsights(
|
||||
organisationId: string,
|
||||
offset: number,
|
||||
perPage: number,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
dateFilter: any,
|
||||
createdAtFrom: Date | null,
|
||||
): Promise<OrganisationDetailedInsights> {
|
||||
let documentsQuery = kyselyPrisma.$kysely
|
||||
.selectFrom('Document as d')
|
||||
@ -217,9 +229,8 @@ async function getDocumentInsights(
|
||||
.where('t.organisationId', '=', organisationId)
|
||||
.where('d.deletedAt', 'is', null);
|
||||
|
||||
// Apply date filter if it's not empty (which means all time)
|
||||
if (dateFilter && dateFilter.sql && dateFilter.sql !== '') {
|
||||
documentsQuery = documentsQuery.where(sql`${dateFilter}`);
|
||||
if (createdAtFrom) {
|
||||
documentsQuery = documentsQuery.where('d.createdAt', '>=', createdAtFrom);
|
||||
}
|
||||
|
||||
documentsQuery = documentsQuery
|
||||
@ -241,9 +252,8 @@ async function getDocumentInsights(
|
||||
.where('t.organisationId', '=', organisationId)
|
||||
.where('d.deletedAt', 'is', null);
|
||||
|
||||
// Apply same date filter to count query
|
||||
if (dateFilter && dateFilter.sql && dateFilter.sql !== '') {
|
||||
countQuery = countQuery.where(sql`${dateFilter}`);
|
||||
if (createdAtFrom) {
|
||||
countQuery = countQuery.where('d.createdAt', '>=', createdAtFrom);
|
||||
}
|
||||
|
||||
countQuery = countQuery.select(({ fn }) => [fn.countAll().as('count')]);
|
||||
@ -268,39 +278,67 @@ async function getDocumentInsights(
|
||||
|
||||
async function getOrganisationSummary(
|
||||
organisationId: string,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
dateFilter: any,
|
||||
createdAtFrom: Date | null,
|
||||
): Promise<OrganisationSummary> {
|
||||
const summaryQuery = kyselyPrisma.$kysely
|
||||
.selectFrom('Organisation as o')
|
||||
.leftJoin('Team as t', 'o.id', 't.organisationId')
|
||||
.leftJoin('OrganisationMember as om', 'o.id', 'om.organisationId')
|
||||
.leftJoin('Document as d', (join) =>
|
||||
join.onRef('t.id', '=', 'd.teamId').on('d.deletedAt', 'is', null),
|
||||
)
|
||||
.where('o.id', '=', organisationId)
|
||||
.select([
|
||||
sql<number>`COUNT(DISTINCT t.id)`.as('totalTeams'),
|
||||
sql<number>`COUNT(DISTINCT om."userId")`.as('totalMembers'),
|
||||
sql<number>`COUNT(DISTINCT d.id)`.as('totalDocuments'),
|
||||
sql<number>`COUNT(DISTINCT CASE WHEN d.status IN ('DRAFT', 'PENDING') THEN d.id END)`.as(
|
||||
'activeDocuments',
|
||||
sql<number>`(SELECT COUNT(DISTINCT t2.id) FROM "Team" AS t2 WHERE t2."organisationId" = o.id)`.as(
|
||||
'totalTeams',
|
||||
),
|
||||
sql<number>`COUNT(DISTINCT CASE WHEN d.status = 'COMPLETED' THEN d.id END)`.as(
|
||||
'completedDocuments',
|
||||
),
|
||||
sql<number>`COUNT(DISTINCT CASE WHEN d.id IS NOT NULL AND d.status = 'COMPLETED' ${dateFilter} THEN d.id END)`.as(
|
||||
'volumeThisPeriod',
|
||||
),
|
||||
sql<number>`COUNT(DISTINCT CASE WHEN d.status = 'COMPLETED' THEN d.id END)`.as(
|
||||
'volumeAllTime',
|
||||
sql<number>`(SELECT COUNT(DISTINCT om2."userId") FROM "OrganisationMember" AS om2 WHERE om2."organisationId" = o.id)`.as(
|
||||
'totalMembers',
|
||||
),
|
||||
sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id AND d2."deletedAt" IS NULL
|
||||
)`.as('totalDocuments'),
|
||||
sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id AND d2."deletedAt" IS NULL AND d2.status IN ('DRAFT', 'PENDING')
|
||||
)`.as('activeDocuments'),
|
||||
sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id AND d2."deletedAt" IS NULL AND d2.status = 'COMPLETED'
|
||||
)`.as('completedDocuments'),
|
||||
(createdAtFrom
|
||||
? sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id
|
||||
AND d2."deletedAt" IS NULL
|
||||
AND d2.status = 'COMPLETED'
|
||||
AND d2."createdAt" >= ${createdAtFrom}
|
||||
)`
|
||||
: sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id
|
||||
AND d2."deletedAt" IS NULL
|
||||
AND d2.status = 'COMPLETED'
|
||||
)`
|
||||
).as('volumeThisPeriod'),
|
||||
sql<number>`(
|
||||
SELECT COUNT(DISTINCT d2.id)
|
||||
FROM "Document" AS d2
|
||||
INNER JOIN "Team" AS t2 ON t2.id = d2."teamId"
|
||||
WHERE t2."organisationId" = o.id AND d2."deletedAt" IS NULL AND d2.status = 'COMPLETED'
|
||||
)`.as('volumeAllTime'),
|
||||
]);
|
||||
|
||||
const result = await summaryQuery.executeTakeFirst();
|
||||
|
||||
return {
|
||||
totalTeams: Math.max(Number(result?.totalTeams || 0), 1),
|
||||
totalTeams: Number(result?.totalTeams || 0),
|
||||
totalMembers: Number(result?.totalMembers || 0),
|
||||
totalDocuments: Number(result?.totalDocuments || 0),
|
||||
activeDocuments: Number(result?.activeDocuments || 0),
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { DocumentStatus } from '@prisma/client';
|
||||
|
||||
import type { DateRange } from '@documenso/lib/types/search-params';
|
||||
import { kyselyPrisma, sql } from '@documenso/prisma';
|
||||
|
||||
export type OrganisationInsights = {
|
||||
@ -73,7 +74,7 @@ export async function getSigningVolume({
|
||||
.where((eb) =>
|
||||
eb.or([eb('o.name', 'ilike', `%${search}%`), eb('t.name', 'ilike', `%${search}%`)]),
|
||||
)
|
||||
.select(({ fn }) => [fn.countAll().as('count')]);
|
||||
.select(() => [sql<number>`COUNT(DISTINCT o.id)`.as('count')]);
|
||||
|
||||
const [results, [{ count }]] = await Promise.all([findQuery.execute(), countQuery.execute()]);
|
||||
|
||||
@ -84,7 +85,7 @@ export async function getSigningVolume({
|
||||
}
|
||||
|
||||
export type GetOrganisationInsightsOptions = GetSigningVolumeOptions & {
|
||||
dateRange?: 'last30days' | 'last90days' | 'lastYear' | 'allTime';
|
||||
dateRange?: DateRange;
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
};
|
||||
@ -182,7 +183,7 @@ export async function getOrganisationInsights({
|
||||
.where((eb) =>
|
||||
eb.or([eb('o.name', 'ilike', `%${search}%`), eb('t.name', 'ilike', `%${search}%`)]),
|
||||
)
|
||||
.select(({ fn }) => [fn.countAll().as('count')]);
|
||||
.select(() => [sql<number>`COUNT(DISTINCT o.id)`.as('count')]);
|
||||
|
||||
const [results, [{ count }]] = await Promise.all([findQuery.execute(), countQuery.execute()]);
|
||||
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export type DateRange = 'last30days' | 'last90days' | 'lastYear' | 'allTime';
|
||||
|
||||
/**
|
||||
* Backend only schema is used for find search params.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user