-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add org analytics view #1082
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add org analytics view #1082
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1f957d2
Add org analytics view
elie222 9c1ccd3
org tabs
elie222 cceff58
Merge branch 'main' into feat/org-analytics
elie222 e761526
refactor org stats api
elie222 7d9f220
fix permissions
elie222 5d3d147
fixes
elie222 d4d6e35
fixes
elie222 22c85ea
fix build
elie222 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
apps/web/app/(app)/organization/[organizationId]/OrganizationTabs.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| "use client"; | ||
|
|
||
| import { usePathname } from "next/navigation"; | ||
| import { TabSelect } from "@/components/TabSelect"; | ||
| import { PageHeading } from "@/components/Typography"; | ||
| import { LoadingContent } from "@/components/LoadingContent"; | ||
| import { Skeleton } from "@/components/ui/skeleton"; | ||
| import { useOrganization } from "@/hooks/useOrganization"; | ||
|
|
||
| interface OrganizationTabsProps { | ||
| organizationId: string; | ||
| } | ||
|
|
||
| export function OrganizationTabs({ organizationId }: OrganizationTabsProps) { | ||
| const pathname = usePathname(); | ||
| const { | ||
| data: organization, | ||
| isLoading, | ||
| error, | ||
| } = useOrganization(organizationId); | ||
|
|
||
| const tabs = [ | ||
| { | ||
| id: "members", | ||
| label: "Members", | ||
| href: `/organization/${organizationId}`, | ||
| }, | ||
| { | ||
| id: "stats", | ||
| label: "Analytics", | ||
| href: `/organization/${organizationId}/stats`, | ||
| }, | ||
| ]; | ||
|
|
||
| // Determine selected tab based on pathname | ||
| const selected = pathname.includes("/stats") ? "stats" : "members"; | ||
|
|
||
| return ( | ||
| <div> | ||
| <LoadingContent | ||
| loading={isLoading} | ||
| error={error} | ||
| loadingComponent={<Skeleton className="mb-2 h-8 w-48" />} | ||
| > | ||
| {organization?.name && ( | ||
| <PageHeading className="mb-2">{organization.name}</PageHeading> | ||
| )} | ||
| </LoadingContent> | ||
| <div className="border-b border-neutral-200"> | ||
| <TabSelect options={tabs} selected={selected} /> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
229 changes: 229 additions & 0 deletions
229
apps/web/app/(app)/organization/[organizationId]/stats/OrgStats.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| "use client"; | ||
|
|
||
| import { useState, useMemo, useCallback } from "react"; | ||
| import type { DateRange } from "react-day-picker"; | ||
| import { subDays } from "date-fns/subDays"; | ||
| import { Mail, Sparkles, Users } from "lucide-react"; | ||
| import { LoadingContent } from "@/components/LoadingContent"; | ||
| import { Skeleton } from "@/components/ui/skeleton"; | ||
| import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; | ||
| import { DatePickerWithRange } from "@/components/DatePickerWithRange"; | ||
| import { useOrgStatsTotals } from "@/hooks/useOrgStatsTotals"; | ||
| import { useOrgStatsEmailBuckets } from "@/hooks/useOrgStatsEmailBuckets"; | ||
| import { useOrgStatsRulesBuckets } from "@/hooks/useOrgStatsRulesBuckets"; | ||
|
|
||
| const selectOptions = [ | ||
| { label: "Last week", value: "7" }, | ||
| { label: "Last month", value: "30" }, | ||
| { label: "Last 3 months", value: "90" }, | ||
| { label: "All time", value: "0" }, | ||
| ]; | ||
| const defaultSelected = selectOptions[1]; | ||
|
|
||
| export function OrgStats({ organizationId }: { organizationId: string }) { | ||
| const [dateDropdown, setDateDropdown] = useState<string>( | ||
| defaultSelected.label, | ||
| ); | ||
|
|
||
| const now = useMemo(() => new Date(), []); | ||
| const [dateRange, setDateRange] = useState<DateRange | undefined>({ | ||
| from: subDays(now, Number.parseInt(defaultSelected.value)), | ||
| to: now, | ||
| }); | ||
|
|
||
| const onSetDateDropdown = useCallback( | ||
| (option: { label: string; value: string }) => { | ||
| setDateDropdown(option.label); | ||
| }, | ||
| [], | ||
| ); | ||
|
|
||
| const options = useMemo( | ||
| () => ({ | ||
| fromDate: dateRange?.from?.getTime(), | ||
| toDate: dateRange?.to?.getTime(), | ||
| }), | ||
| [dateRange], | ||
| ); | ||
|
|
||
| const { | ||
| data: totalsData, | ||
| isLoading: totalsLoading, | ||
| error: totalsError, | ||
| } = useOrgStatsTotals(organizationId, options); | ||
|
|
||
| const { | ||
| data: emailBucketsData, | ||
| isLoading: emailBucketsLoading, | ||
| error: emailBucketsError, | ||
| } = useOrgStatsEmailBuckets(organizationId, options); | ||
|
|
||
| const { | ||
| data: rulesBucketsData, | ||
| isLoading: rulesBucketsLoading, | ||
| error: rulesBucketsError, | ||
| } = useOrgStatsRulesBuckets(organizationId, options); | ||
|
|
||
| return ( | ||
| <div className="space-y-6"> | ||
| <div className="flex items-center justify-between"> | ||
| <DatePickerWithRange | ||
| dateRange={dateRange} | ||
| onSetDateRange={setDateRange} | ||
| selectOptions={selectOptions} | ||
| dateDropdown={dateDropdown} | ||
| onSetDateDropdown={onSetDateDropdown} | ||
| /> | ||
| </div> | ||
|
|
||
| <div className="space-y-6"> | ||
| <LoadingContent | ||
| loading={totalsLoading} | ||
| error={totalsError} | ||
| loadingComponent={ | ||
| <div className="grid gap-4 md:grid-cols-3"> | ||
| <Skeleton className="h-24" /> | ||
| <Skeleton className="h-24" /> | ||
| <Skeleton className="h-24" /> | ||
| </div> | ||
| } | ||
| > | ||
| {totalsData && ( | ||
| <div className="grid gap-4 md:grid-cols-3"> | ||
| <StatCard | ||
| title="Emails Received" | ||
| value={totalsData.totalEmails.toLocaleString()} | ||
| icon={<Mail className="h-4 w-4 text-muted-foreground" />} | ||
| /> | ||
| <StatCard | ||
| title="Rules Executed" | ||
| value={totalsData.totalRules.toLocaleString()} | ||
| icon={<Sparkles className="h-4 w-4 text-muted-foreground" />} | ||
| /> | ||
| <StatCard | ||
| title="Active Members" | ||
| value={totalsData.activeMembers.toLocaleString()} | ||
| icon={<Users className="h-4 w-4 text-muted-foreground" />} | ||
| /> | ||
| </div> | ||
| )} | ||
| </LoadingContent> | ||
|
|
||
| <div className="grid gap-4 md:grid-cols-2"> | ||
| <LoadingContent | ||
| loading={emailBucketsLoading} | ||
| error={emailBucketsError} | ||
| loadingComponent={<Skeleton className="h-64" />} | ||
| > | ||
| {emailBucketsData && ( | ||
| <BucketChart | ||
| title="Email Volume Distribution" | ||
| description="Number of users by emails received in selected period" | ||
| data={emailBucketsData} | ||
| emptyMessage="No email data available. Users need to load their stats first." | ||
| unit="emails" | ||
| /> | ||
| )} | ||
| </LoadingContent> | ||
|
|
||
| <LoadingContent | ||
| loading={rulesBucketsLoading} | ||
| error={rulesBucketsError} | ||
| loadingComponent={<Skeleton className="h-64" />} | ||
| > | ||
| {rulesBucketsData && ( | ||
| <BucketChart | ||
| title="Automation Usage Distribution" | ||
| description="Number of users by rules executed in selected period" | ||
| data={rulesBucketsData} | ||
| emptyMessage="No automation data yet." | ||
| unit="rules" | ||
| /> | ||
| )} | ||
| </LoadingContent> | ||
| </div> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| function StatCard({ | ||
| title, | ||
| value, | ||
| icon, | ||
| }: { | ||
| title: string; | ||
| value: string; | ||
| icon: React.ReactNode; | ||
| }) { | ||
| return ( | ||
| <Card> | ||
| <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> | ||
| <CardTitle className="text-sm font-medium">{title}</CardTitle> | ||
| {icon} | ||
| </CardHeader> | ||
| <CardContent> | ||
| <div className="text-2xl font-bold">{value}</div> | ||
| </CardContent> | ||
| </Card> | ||
| ); | ||
| } | ||
|
|
||
| function BucketChart({ | ||
| title, | ||
| description, | ||
| data, | ||
| emptyMessage, | ||
| unit = "emails", | ||
| }: { | ||
| title: string; | ||
| description: string; | ||
| data: { label: string; userCount: number }[]; | ||
| emptyMessage: string; | ||
| unit?: string; | ||
| }) { | ||
| const hasData = data.some((bucket) => bucket.userCount > 0); | ||
| const maxValue = Math.max(...data.map((d) => d.userCount), 1); | ||
|
|
||
| return ( | ||
| <Card> | ||
| <CardHeader> | ||
| <CardTitle className="text-base">{title}</CardTitle> | ||
| <p className="text-sm text-muted-foreground">{description}</p> | ||
| </CardHeader> | ||
| <CardContent> | ||
| {!hasData ? ( | ||
| <div className="flex h-40 items-center justify-center"> | ||
| <p className="text-sm text-muted-foreground text-center"> | ||
| {emptyMessage} | ||
| </p> | ||
| </div> | ||
| ) : ( | ||
| <div className="space-y-3"> | ||
| {data.map((bucket) => ( | ||
| <div key={bucket.label} className="space-y-1"> | ||
| <div className="flex items-center justify-between text-sm"> | ||
| <span className="text-muted-foreground"> | ||
| {bucket.label} {unit} | ||
| </span> | ||
| <span className="font-medium"> | ||
| {bucket.userCount}{" "} | ||
| {bucket.userCount === 1 ? "user" : "users"} | ||
| </span> | ||
| </div> | ||
| <div className="h-2 w-full rounded-full bg-secondary"> | ||
| <div | ||
| className="h-2 rounded-full bg-primary transition-all" | ||
| style={{ | ||
| width: `${(bucket.userCount / maxValue) * 100}%`, | ||
| }} | ||
| /> | ||
| </div> | ||
| </div> | ||
| ))} | ||
| </div> | ||
| )} | ||
| </CardContent> | ||
| </Card> | ||
| ); | ||
| } |
21 changes: 21 additions & 0 deletions
21
apps/web/app/(app)/organization/[organizationId]/stats/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { PageWrapper } from "@/components/PageWrapper"; | ||
| import { OrgStats } from "@/app/(app)/organization/[organizationId]/stats/OrgStats"; | ||
| import { OrganizationTabs } from "@/app/(app)/organization/[organizationId]/OrganizationTabs"; | ||
|
|
||
| export default async function OrgStatsPage({ | ||
| params, | ||
| }: { | ||
| params: Promise<{ organizationId: string }>; | ||
| }) { | ||
| const { organizationId } = await params; | ||
|
|
||
| return ( | ||
| <PageWrapper> | ||
| <OrganizationTabs organizationId={organizationId} /> | ||
|
|
||
| <div className="mt-6"> | ||
| <OrgStats organizationId={organizationId} /> | ||
| </div> | ||
| </PageWrapper> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import prisma from "@/utils/prisma"; | ||
| import { withAuth } from "@/utils/middleware"; | ||
| import { fetchAndCheckIsAdmin } from "@/utils/organizations/access"; | ||
|
|
||
| export type OrganizationResponse = Awaited<ReturnType<typeof getOrganization>>; | ||
|
|
||
| export const GET = withAuth( | ||
| "organizations/get", | ||
| async (request, { params }) => { | ||
| const { userId } = request.auth; | ||
| const { organizationId } = await params; | ||
|
|
||
| await fetchAndCheckIsAdmin({ organizationId, userId }); | ||
|
|
||
| const result = await getOrganization({ organizationId }); | ||
|
|
||
| return NextResponse.json(result); | ||
| }, | ||
| ); | ||
|
|
||
| async function getOrganization({ organizationId }: { organizationId: string }) { | ||
| const organization = await prisma.organization.findUnique({ | ||
| where: { id: organizationId }, | ||
| select: { id: true, name: true }, | ||
| }); | ||
|
|
||
| return organization; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use more precise pathname matching.
Using
pathname.includes("/stats")is fragile because it will match any occurrence of "stats" in the pathname, potentially causing incorrect tab selection if "stats" appears in a query parameter or elsewhere in the URL.Use a more precise check:
Or for even more precision:
🤖 Prompt for AI Agents