Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: Dashboard add
Richie McIlroyca07f1484ce2
diff --git a/apps/web/app/(org)/dashboard/admin/AdminDashboardClient.tsx b/apps/web/app/(org)/dashboard/admin/AdminDashboardClient.tsxnew file mode 100644index 000000000..c1d956b01--- /dev/null+++ b/apps/web/app/(org)/dashboard/admin/AdminDashboardClient.tsx@@ -0,0 +1,113 @@+"use client";++import { useState, useEffect } from "react";+import {+ DateRange,+ getUsersCreatedInRange,+ getPaidUsersStatsInRange,+} from "./actions";+import UserLookup from "./UserLookup";++type Stats = {+ newUsers: number | null;+ paidUsersStats: {+ totalPaidUsers: number;+ usersWhoCreatedVideoFirst: number;+ percentage: number;+ } | null;+};++export default function AdminDashboardClient() {+ const [dateRange, setDateRange] = useState<DateRange>("today");+ const [stats, setStats] = useState<Stats>({+ newUsers: null,+ paidUsersStats: null,+ });+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const fetchStats = async () => {+ setLoading(true);+ const [newUsers, paidUsersStats] = await Promise.all([+ getUsersCreatedInRange(dateRange),+ getPaidUsersStatsInRange(dateRange),+ ]);+ setStats({ newUsers, paidUsersStats });+ setLoading(false);+ };++ fetchStats();+ }, [dateRange]);++ return (+ <div className="max-w-7xl mx-auto p-6">+ <div className="flex items-center justify-between mb-8">+ <h1 className="text-2xl font-medium">Admin Dashboard</h1>+ <select+ value={dateRange}+ onChange={(e) => setDateRange(e.target.value as DateRange)}+ className="px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"+ >+ <option value="today">Today</option>+ <option value="yesterday">Yesterday</option>+ <option value="last7days">Last 7 days</option>+ <option value="thisMonth">This month</option>+ <option value="allTime">All time</option>+ </select>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">+ <div className="bg-white rounded-lg shadow p-6">+ <h2 className="text-sm font-medium text-gray-600 mb-2">New Users</h2>+ {loading ? (+ <div className="h-9 bg-gray-200 rounded animate-pulse"></div>+ ) : (+ <p className="text-3xl font-medium text-gray-900">+ {stats.newUsers || 0}+ </p>+ )}+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <h2 className="text-sm font-medium text-gray-600 mb-2">+ Total Paid Users+ </h2>+ {loading ? (+ <div className="h-9 bg-gray-200 rounded animate-pulse"></div>+ ) : (+ <p className="text-3xl font-medium text-gray-900">+ {stats.paidUsersStats?.totalPaidUsers || 0}+ </p>+ )}+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <h2 className="text-sm font-medium text-gray-600 mb-2">+ Created Video Before Paying+ </h2>+ {loading ? (+ <div>+ <div className="h-9 bg-gray-200 rounded animate-pulse mb-2"></div>+ <div className="h-4 bg-gray-200 rounded animate-pulse w-3/4"></div>+ </div>+ ) : (+ <>+ <p className="text-3xl font-medium text-gray-900">+ {stats.paidUsersStats?.percentage || 0}%+ </p>+ <p className="text-xs text-gray-500 mt-1">+ {stats.paidUsersStats?.usersWhoCreatedVideoFirst || 0} of{" "}+ {stats.paidUsersStats?.totalPaidUsers || 0} users+ </p>+ </>+ )}+ </div>+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <h2 className="text-lg font-medium mb-4">User Lookup</h2>+ <UserLookup />+ </div>+ </div>+ );+}diff --git a/apps/web/app/(org)/dashboard/admin/UserLookup.tsx b/apps/web/app/(org)/dashboard/admin/UserLookup.tsxnew file mode 100644index 000000000..8ba811426--- /dev/null+++ b/apps/web/app/(org)/dashboard/admin/UserLookup.tsx@@ -0,0 +1,64 @@+"use client";++import { useState } from "react";+import { lookupUserById } from "./actions";++export default function UserLookup() {+ const [data, setData] = useState<any>(null);+ const [loading, setLoading] = useState(false);++ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();+ setLoading(true);+ try {+ const formData = new FormData(e.currentTarget);+ const result = await lookupUserById(formData);+ setData(result);+ } catch (error) {+ console.error("Error looking up user:", error);+ } finally {+ setLoading(false);+ }+ };++ return (+ <div>+ <form onSubmit={handleSubmit} className="space-y-4">+ <div>+ <label+ htmlFor="userId"+ className="block text-sm font-medium text-gray-700 mb-1"+ >+ Lookup user by ID+ </label>+ <div className="flex gap-2">+ <input+ type="text"+ name="id"+ id="userId"+ className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"+ placeholder="Enter user ID"+ required+ />+ <button+ type="submit"+ disabled={loading}+ className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {loading ? "Loading..." : "Lookup"}+ </button>+ </div>+ </div>+ </form>++ {data && (+ <div className="mt-6 p-4 bg-gray-50 rounded-md">+ <h3 className="text-sm font-medium text-gray-700 mb-2">User Data:</h3>+ <pre className="text-xs text-gray-600 overflow-x-auto">+ {JSON.stringify(data, null, 2)}+ </pre>+ </div>+ )}+ </div>+ );+}diff --git a/apps/web/app/(org)/dashboard/admin/actions.ts b/apps/web/app/(org)/dashboard/admin/actions.tsindex faf128f1c..00f19fa2b 100644--- a/apps/web/app/(org)/dashboard/admin/actions.ts+++ b/apps/web/app/(org)/dashboard/admin/actions.ts@@ -2,8 +2,50 @@import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";-import { users } from "@cap/database/schema";-import { eq } from "drizzle-orm";+import { users, videos } from "@cap/database/schema";+import { eq, gte, and, sql, isNotNull, or, lte } from "drizzle-orm";+import { stripe } from "@cap/utils";++export type DateRange = "today" | "yesterday" | "last7days" | "thisMonth" | "allTime";++export function getDateRangeFilter(range: DateRange): { start: Date; end: Date } {+ const now = new Date();+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());++ switch (range) {+ case "today":+ return {+ start: today,+ end: new Date(today.getTime() + 24 * 60 * 60 * 1000)+ };+ case "yesterday":+ const yesterday = new Date(today);+ yesterday.setDate(yesterday.getDate() - 1);+ return {+ start: yesterday,+ end: today+ };+ case "last7days":+ const last7Days = new Date(today);+ last7Days.setDate(last7Days.getDate() - 7);+ return {+ start: last7Days,+ end: new Date(today.getTime() + 24 * 60 * 60 * 1000)+ };+ case "thisMonth":+ const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);+ const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);+ return {+ start: monthStart,+ end: monthEnd+ };+ case "allTime":+ return {+ start: new Date(0),+ end: new Date()+ };+ }+}export async function lookupUserById(data: FormData) {const currentUser = await getCurrentUser();@@ -16,3 +58,273 @@ export async function lookupUserById(data: FormData) {return user;}++export async function getUsersCreatedToday() {+ const currentUser = await getCurrentUser();+ if (!currentUser?.email.endsWith("@cap.so")) return null;++ const startOfToday = new Date();+ startOfToday.setHours(0, 0, 0, 0);++ const result = await db()+ .select({ count: sql<number>`count(*)` })+ .from(users)+ .where(gte(users.created_at, startOfToday));++ return result[0]?.count || 0;+}++export async function getUsersCreatedInRange(dateRange: DateRange) {+ const currentUser = await getCurrentUser();+ if (!currentUser?.email.endsWith("@cap.so")) return null;++ const { start, end } = getDateRangeFilter(dateRange);++ const result = await db()+ .select({ count: sql<number>`count(*)` })+ .from(users)+ .where(+ and(+ gte(users.created_at, start),+ lte(users.created_at, end)+ )+ );++ return result[0]?.count || 0;+}++export async function getPaidUsersStats() {+ const currentUser = await getCurrentUser();+ if (!currentUser?.email.endsWith("@cap.so")) return null;++ // Get all users with active subscriptions (including third-party)+ const paidUsers = await db()+ .select({+ id: users.id,+ email: users.email,+ stripeCustomerId: users.stripeCustomerId,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ stripeSubscriptionId: users.stripeSubscriptionId,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ created_at: users.created_at,+ })+ .from(users)+ .where(+ or(+ and(+ isNotNull(users.stripeSubscriptionId),+ or(+ eq(users.stripeSubscriptionStatus, "active"),+ eq(users.stripeSubscriptionStatus, "trialing")+ )+ ),+ isNotNull(users.thirdPartyStripeSubscriptionId)+ )+ );++ // For each paid user, check if they created videos before subscribing+ const paidUsersWithVideoCheck = await Promise.all(+ paidUsers.map(async (user) => {+ // Get subscription start date from Stripe+ let subscriptionStartDate: Date | null = null;++ if (user.stripeCustomerId && user.stripeSubscriptionId && !user.thirdPartyStripeSubscriptionId) {+ try {+ const subscription = await stripe().subscriptions.retrieve(+ user.stripeSubscriptionId+ );+ subscriptionStartDate = new Date(subscription.created * 1000);+ } catch (error) {+ console.error(`Failed to fetch subscription for user ${user.id}:`, error);+ // For third-party subscriptions or errors, assume they subscribed when first video was created+ const firstVideo = await db()+ .select({ createdAt: videos.createdAt })+ .from(videos)+ .where(eq(videos.ownerId, user.id))+ .orderBy(videos.createdAt)+ .limit(1);++ if (firstVideo[0]) {+ // Add 1 day to first video as a conservative estimate+ subscriptionStartDate = new Date(firstVideo[0].createdAt);+ subscriptionStartDate.setDate(subscriptionStartDate.getDate() + 1);+ }+ }+ } else if (user.thirdPartyStripeSubscriptionId) {+ // For third-party subscriptions, we can't get the exact date from Stripe+ // So we'll use a conservative approach: assume they subscribed after their first video+ const firstVideo = await db()+ .select({ createdAt: videos.createdAt })+ .from(videos)+ .where(eq(videos.ownerId, user.id))+ .orderBy(videos.createdAt)+ .limit(1);++ if (firstVideo[0]) {+ // Add 1 day to first video as a conservative estimate+ subscriptionStartDate = new Date(firstVideo[0].createdAt);+ subscriptionStartDate.setDate(subscriptionStartDate.getDate() + 1);+ }+ }++ // Check if user created videos before subscription+ let createdVideoBeforeSubscription = false;+ if (subscriptionStartDate) {+ const videosBeforeSubscription = await db()+ .select({ count: sql<number>`count(*)` })+ .from(videos)+ .where(+ and(+ eq(videos.ownerId, user.id),+ sql`${videos.createdAt} < ${subscriptionStartDate}`+ )+ );++ createdVideoBeforeSubscription = (videosBeforeSubscription[0]?.count || 0) > 0;+ }++ return {+ ...user,+ subscriptionStartDate,+ createdVideoBeforeSubscription,+ };+ })+ );++ const totalPaidUsers = paidUsersWithVideoCheck.length;+ const usersWhoCreatedVideoFirst = paidUsersWithVideoCheck.filter(+ (user) => user.createdVideoBeforeSubscription+ ).length;++ const percentage = totalPaidUsers > 0+ ? Math.round((usersWhoCreatedVideoFirst / totalPaidUsers) * 100)+ : 0;++ return {+ totalPaidUsers,+ usersWhoCreatedVideoFirst,+ percentage,+ };+}++export async function getPaidUsersStatsInRange(dateRange: DateRange) {+ const currentUser = await getCurrentUser();+ if (!currentUser?.email.endsWith("@cap.so")) return null;++ const { start, end } = getDateRangeFilter(dateRange);++ // Get all users with active subscriptions created in the date range+ const paidUsers = await db()+ .select({+ id: users.id,+ email: users.email,+ stripeCustomerId: users.stripeCustomerId,+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ stripeSubscriptionId: users.stripeSubscriptionId,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ created_at: users.created_at,+ })+ .from(users)+ .where(+ and(+ or(+ and(+ isNotNull(users.stripeSubscriptionId),+ or(+ eq(users.stripeSubscriptionStatus, "active"),+ eq(users.stripeSubscriptionStatus, "trialing")+ )+ ),+ isNotNull(users.thirdPartyStripeSubscriptionId)+ ),+ dateRange !== "allTime" ? and(+ gte(users.created_at, start),+ lte(users.created_at, end)+ ) : sql`1=1`+ )+ );++ // For each paid user, check if they created videos before subscribing+ const paidUsersWithVideoCheck = await Promise.all(+ paidUsers.map(async (user) => {+ // Get subscription start date from Stripe+ let subscriptionStartDate: Date | null = null;++ if (user.stripeCustomerId && user.stripeSubscriptionId && !user.thirdPartyStripeSubscriptionId) {+ try {+ const subscription = await stripe().subscriptions.retrieve(+ user.stripeSubscriptionId+ );+ subscriptionStartDate = new Date(subscription.created * 1000);+ } catch (error) {+ console.error(`Failed to fetch subscription for user ${user.id}:`, error);+ // For third-party subscriptions or errors, assume they subscribed when first video was created+ const firstVideo = await db()+ .select({ createdAt: videos.createdAt })+ .from(videos)+ .where(eq(videos.ownerId, user.id))+ .orderBy(videos.createdAt)+ .limit(1);++ if (firstVideo[0]) {+ // Add 1 day to first video as a conservative estimate+ subscriptionStartDate = new Date(firstVideo[0].createdAt);+ subscriptionStartDate.setDate(subscriptionStartDate.getDate() + 1);+ }+ }+ } else if (user.thirdPartyStripeSubscriptionId) {+ // For third-party subscriptions, we can't get the exact date from Stripe+ // So we'll use a conservative approach: assume they subscribed after their first video+ const firstVideo = await db()+ .select({ createdAt: videos.createdAt })+ .from(videos)+ .where(eq(videos.ownerId, user.id))+ .orderBy(videos.createdAt)+ .limit(1);++ if (firstVideo[0]) {+ // Add 1 day to first video as a conservative estimate+ subscriptionStartDate = new Date(firstVideo[0].createdAt);+ subscriptionStartDate.setDate(subscriptionStartDate.getDate() + 1);+ }+ }++ // Check if user created videos before subscription+ let createdVideoBeforeSubscription = false;+ if (subscriptionStartDate) {+ const videosBeforeSubscription = await db()+ .select({ count: sql<number>`count(*)` })+ .from(videos)+ .where(+ and(+ eq(videos.ownerId, user.id),+ sql`${videos.createdAt} < ${subscriptionStartDate}`+ )+ );++ createdVideoBeforeSubscription = (videosBeforeSubscription[0]?.count || 0) > 0;+ }++ return {+ ...user,+ subscriptionStartDate,+ createdVideoBeforeSubscription,+ };+ })+ );++ const totalPaidUsers = paidUsersWithVideoCheck.length;+ const usersWhoCreatedVideoFirst = paidUsersWithVideoCheck.filter(+ (user) => user.createdVideoBeforeSubscription+ ).length;++ const percentage = totalPaidUsers > 0+ ? Math.round((usersWhoCreatedVideoFirst / totalPaidUsers) * 100)+ : 0;++ return {+ totalPaidUsers,+ usersWhoCreatedVideoFirst,+ percentage,+ };+}diff --git a/apps/web/app/(org)/dashboard/admin/loading.tsx b/apps/web/app/(org)/dashboard/admin/loading.tsxnew file mode 100644index 000000000..661cec897--- /dev/null+++ b/apps/web/app/(org)/dashboard/admin/loading.tsx@@ -0,0 +1,40 @@+export default function AdminDashboardLoading() {+ return (+ <div className="max-w-7xl mx-auto p-6">+ <h1 className="text-2xl font-medium mb-8">Admin Dashboard</h1>++ <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">+ <div className="bg-white rounded-lg shadow p-6">+ <div className="animate-pulse">+ <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>+ <div className="h-8 bg-gray-300 rounded w-1/2"></div>+ </div>+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <div className="animate-pulse">+ <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>+ <div className="h-8 bg-gray-300 rounded w-1/2"></div>+ </div>+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <div className="animate-pulse">+ <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>+ <div className="h-8 bg-gray-300 rounded w-1/2"></div>+ </div>+ </div>+ </div>++ <div className="bg-white rounded-lg shadow p-6">+ <div className="animate-pulse">+ <div className="h-5 bg-gray-200 rounded w-1/4 mb-4"></div>+ <div className="space-y-2">+ <div className="h-4 bg-gray-100 rounded w-full"></div>+ <div className="h-4 bg-gray-100 rounded w-full"></div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/app/(org)/dashboard/admin/page.tsx b/apps/web/app/(org)/dashboard/admin/page.tsxindex 6e1f6a656..f751caa03 100644--- a/apps/web/app/(org)/dashboard/admin/page.tsx+++ b/apps/web/app/(org)/dashboard/admin/page.tsx@@ -1,25 +1,13 @@-"use client";+import { redirect } from "next/navigation";+import { getCurrentUser } from "@cap/database/auth/session";+import AdminDashboardClient from "./AdminDashboardClient";-import { useState } from "react";-import { lookupUserById } from "./actions";+export default async function AdminDashboard() {+ const currentUser = await getCurrentUser();-export default function () {- const [data, setData] = useState<any>(null);+ if (currentUser?.email !== "[email protected]") {+ redirect("/dashboard");+ }- return (- <div>- <label>Lookup user by ID</label>- <form- onSubmit={(e) => {- e.preventDefault();- lookupUserById(new FormData(e.currentTarget)).then(setData);- }}- >- <input type="text" name="id" />- <button type="submit">Lookup</button>- </form>-- {data && <pre>{JSON.stringify(data, null, 4)}</pre>}- </div>- );+ return <AdminDashboardClient />;}