fix: update user fields to match schema

- Replace firstName/lastName with name field in users API route
- Update user formatting in UsersTab component
- Add email fallback when name is not available
This commit is contained in:
2024-12-04 14:45:24 -05:00
parent 95b106d9e9
commit 29ce631901
36 changed files with 2700 additions and 167 deletions

View File

@@ -0,0 +1,43 @@
'use client';
import { useParams } from "next/navigation";
import { useEffect } from "react";
import { useActiveStudy } from "~/context/active-study";
import { Breadcrumb } from "~/components/breadcrumb";
import { Skeleton } from "~/components/ui/skeleton";
export default function StudyLayout({
children,
}: {
children: React.ReactNode;
}) {
const { id } = useParams();
const { studies, activeStudy, setActiveStudy, isLoading } = useActiveStudy();
useEffect(() => {
if (studies.length > 0 && id) {
const study = studies.find(s => s.id === parseInt(id as string));
if (study && (!activeStudy || activeStudy.id !== study.id)) {
setActiveStudy(study);
}
}
}, [id, studies, activeStudy, setActiveStudy]);
if (isLoading) {
return (
<div className="space-y-6">
<div className="h-6">
<Skeleton className="h-4 w-[250px]" />
</div>
<Skeleton className="h-[400px]" />
</div>
);
}
return (
<div className="space-y-6">
<Breadcrumb />
{children}
</div>
);
}

View File

@@ -0,0 +1,172 @@
'use client';
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import {
Users,
FileText,
BarChart,
PlayCircle,
Plus,
Settings2
} from "lucide-react";
import { useToast } from "~/hooks/use-toast";
import Link from "next/link";
interface StudyStats {
participantCount: number;
completedTrialsCount: number;
pendingFormsCount: number;
}
export default function StudyDashboard() {
const [stats, setStats] = useState<StudyStats>({
participantCount: 0,
completedTrialsCount: 0,
pendingFormsCount: 0,
});
const [loading, setLoading] = useState(true);
const { id } = useParams();
const { toast } = useToast();
useEffect(() => {
fetchStudyStats();
}, [id]);
const fetchStudyStats = async () => {
try {
const response = await fetch(`/api/studies/${id}/stats`);
if (!response.ok) throw new Error("Failed to fetch study statistics");
const data = await response.json();
setStats(data.data);
} catch (error) {
console.error("Error fetching study stats:", error);
toast({
title: "Error",
description: "Failed to load study statistics",
variant: "destructive",
});
} finally {
setLoading(false);
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
</div>
);
}
return (
<div className="space-y-6">
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Participants</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.participantCount}</div>
<p className="text-xs text-muted-foreground">Total participants enrolled</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Completed Trials</CardTitle>
<PlayCircle className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.completedTrialsCount}</div>
<p className="text-xs text-muted-foreground">Successfully completed trials</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Pending Forms</CardTitle>
<FileText className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats.pendingFormsCount}</div>
<p className="text-xs text-muted-foreground">Forms awaiting completion</p>
</CardContent>
</Card>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Quick Actions</CardTitle>
<CardDescription>Common tasks for this study</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<Button
variant="outline"
className="w-full justify-start"
asChild
>
<Link href={`/dashboard/studies/${id}/participants/new`}>
<Plus className="mr-2 h-4 w-4" />
Add Participant
</Link>
</Button>
<Button
variant="outline"
className="w-full justify-start"
asChild
>
<Link href={`/dashboard/studies/${id}/trials/new`}>
<PlayCircle className="mr-2 h-4 w-4" />
Start New Trial
</Link>
</Button>
<Button
variant="outline"
className="w-full justify-start"
asChild
>
<Link href={`/dashboard/studies/${id}/forms/new`}>
<FileText className="mr-2 h-4 w-4" />
Create Form
</Link>
</Button>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Recent Activity</CardTitle>
<CardDescription>Latest updates and changes</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<Button
variant="outline"
className="w-full justify-start"
asChild
>
<Link href={`/dashboard/studies/${id}/analysis`}>
<BarChart className="mr-2 h-4 w-4" />
View Analytics
</Link>
</Button>
<Button
variant="outline"
className="w-full justify-start"
asChild
>
<Link href={`/dashboard/studies/${id}/settings`}>
<Settings2 className="mr-2 h-4 w-4" />
Study Settings
</Link>
</Button>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -0,0 +1,111 @@
'use client';
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { useToast } from "~/hooks/use-toast";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";
import { useActiveStudy } from "~/context/active-study";
import { hasPermission } from "~/lib/permissions-client";
import { PERMISSIONS } from "~/lib/permissions";
export default function NewParticipant() {
const [name, setName] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const { id } = useParams();
const router = useRouter();
const { toast } = useToast();
const { activeStudy } = useActiveStudy();
useEffect(() => {
if (!activeStudy || !hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT)) {
router.push(`/dashboard/studies/${id}`);
}
}, [activeStudy, id, router]);
if (!activeStudy || !hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT)) {
return null;
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const response = await fetch(`/api/studies/${id}/participants`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error("Failed to create participant");
}
toast({
title: "Success",
description: "Participant created successfully",
});
router.push(`/dashboard/studies/${id}/participants`);
} catch (error) {
console.error("Error creating participant:", error);
toast({
title: "Error",
description: "Failed to create participant",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<Button
variant="ghost"
className="gap-2"
asChild
>
<Link href={`/dashboard/studies/${id}/participants`}>
<ArrowLeft className="h-4 w-4" />
Back to Participants
</Link>
</Button>
</div>
<Card>
<CardHeader>
<CardTitle>Add New Participant</CardTitle>
<CardDescription>
Create a new participant for {activeStudy?.title}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Participant Name</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter participant name"
required
/>
</div>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Creating..." : "Create Participant"}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,215 @@
'use client';
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
import { Button } from "~/components/ui/button";
import { useToast } from "~/hooks/use-toast";
import { Plus, Trash2 } from "lucide-react";
import Link from "next/link";
import { useActiveStudy } from "~/context/active-study";
import { hasPermission } from "~/lib/permissions-client";
import { PERMISSIONS } from "~/lib/permissions";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
interface Participant {
id: number;
name: string;
studyId: number;
createdAt: string;
}
export default function ParticipantsList() {
const [participants, setParticipants] = useState<Participant[]>([]);
const [isLoading, setIsLoading] = useState(true);
const { id } = useParams();
const { toast } = useToast();
const { activeStudy } = useActiveStudy();
const canCreateParticipant = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.CREATE_PARTICIPANT);
const canDeleteParticipant = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.DELETE_PARTICIPANT);
const canViewNames = activeStudy && hasPermission(activeStudy.permissions, PERMISSIONS.VIEW_PARTICIPANT_NAMES);
useEffect(() => {
fetchParticipants();
}, [id]);
const fetchParticipants = async () => {
try {
const response = await fetch(`/api/studies/${id}/participants`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) throw new Error("Failed to fetch participants");
const data = await response.json();
setParticipants(data.data || []);
} catch (error) {
console.error("Error fetching participants:", error);
toast({
title: "Error",
description: "Failed to load participants",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
const handleDelete = async (participantId: number) => {
try {
const response = await fetch(`/api/studies/${id}/participants`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ participantId }),
});
if (!response.ok) throw new Error("Failed to delete participant");
setParticipants(participants.filter(p => p.id !== participantId));
toast({
title: "Success",
description: "Participant deleted successfully",
});
} catch (error) {
console.error("Error deleting participant:", error);
toast({
title: "Error",
description: "Failed to delete participant",
variant: "destructive",
});
}
};
if (isLoading) {
return (
<Card>
<CardContent className="py-8">
<p className="text-center text-muted-foreground">Loading participants...</p>
</CardContent>
</Card>
);
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold tracking-tight">Participants</h2>
<p className="text-muted-foreground">
Manage study participants and their data
</p>
</div>
{canCreateParticipant && (
<Button asChild>
<Link href={`/dashboard/studies/${id}/participants/new`}>
<Plus className="mr-2 h-4 w-4" />
Add Participant
</Link>
</Button>
)}
</div>
<Card>
<CardHeader>
<CardTitle>Study Participants</CardTitle>
<CardDescription>
All participants enrolled in {activeStudy?.title}
</CardDescription>
</CardHeader>
<CardContent>
{participants.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Added</TableHead>
{canDeleteParticipant && <TableHead className="w-[100px]">Actions</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
{participants.map((participant) => (
<TableRow key={participant.id}>
<TableCell>{participant.id}</TableCell>
<TableCell>
{canViewNames ? participant.name : `Participant ${participant.id}`}
</TableCell>
<TableCell>
{new Date(participant.createdAt).toLocaleDateString()}
</TableCell>
{canDeleteParticipant && (
<TableCell>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="ghost" size="icon">
<Trash2 className="h-4 w-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Participant</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete this participant? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleDelete(participant.id)}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="py-8 text-center text-muted-foreground">
No participants added yet
{canCreateParticipant && (
<>
.{" "}
<Link
href={`/dashboard/studies/${id}/participants/new`}
className="font-medium text-primary hover:underline"
>
Add your first participant
</Link>
</>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,11 +1,15 @@
'use client';
import { useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import { useParams, useRouter } from "next/navigation";
import { SettingsTab } from "~/components/studies/settings-tab";
import { ParticipantsTab } from "~/components/studies/participants-tab";
import { UsersTab } from "~/components/studies/users-tab";
import { useEffect } from "react";
import { PERMISSIONS } from "~/lib/permissions-client";
import { Button } from "~/components/ui/button";
import { Settings2Icon, UsersIcon, UserIcon } from "lucide-react";
import { cn } from "~/lib/utils";
interface Study {
id: number;
@@ -18,17 +22,32 @@ export default function StudySettings() {
const [study, setStudy] = useState<Study | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'settings' | 'participants' | 'users'>('settings');
const { id } = useParams();
const router = useRouter();
const searchParams = useSearchParams();
const tab = searchParams.get('tab') || 'settings';
useEffect(() => {
const fetchStudy = async () => {
try {
const response = await fetch(`/api/studies/${id}`);
if (!response.ok) throw new Error("Failed to fetch study");
if (!response.ok) {
if (response.status === 403) {
router.push('/dashboard/studies');
return;
}
throw new Error("Failed to fetch study");
}
const data = await response.json();
// Check if user has any required permissions
const requiredPermissions = [PERMISSIONS.EDIT_STUDY, PERMISSIONS.MANAGE_ROLES];
const hasAccess = data.data.permissions.some(p => requiredPermissions.includes(p));
if (!hasAccess) {
router.push('/dashboard/studies');
return;
}
setStudy(data.data);
} catch (error) {
console.error("Error fetching study:", error);
@@ -39,43 +58,65 @@ export default function StudySettings() {
};
fetchStudy();
}, [id]);
const handleTabChange = (value: string) => {
router.push(`/dashboard/studies/${id}/settings?tab=${value}`);
};
}, [id, router]);
if (isLoading) {
return <div className="container py-6">Loading...</div>;
return <div>Loading...</div>;
}
if (error || !study) {
return <div className="container py-6 text-destructive">{error || "Study not found"}</div>;
return <div>Error: {error}</div>;
}
return (
<div className="container py-6 space-y-6">
<div className="flex flex-col gap-2">
<div className="container py-6">
<div className="flex flex-col gap-2 mb-6">
<h1 className="text-3xl font-bold tracking-tight">{study.title}</h1>
<p className="text-muted-foreground">
Manage study settings and participants
Manage study settings, participants, and team members
</p>
</div>
<Tabs value={tab} onValueChange={handleTabChange} className="space-y-6">
<TabsList>
<TabsTrigger value="settings">Settings</TabsTrigger>
<TabsTrigger value="participants">Participants</TabsTrigger>
</TabsList>
<div className="flex gap-6">
<div className="w-48 flex flex-col gap-2">
<Button
variant={activeTab === 'settings' ? 'secondary' : 'ghost'}
className="justify-start"
onClick={() => setActiveTab('settings')}
>
<Settings2Icon className="mr-2 h-4 w-4" />
Settings
</Button>
<Button
variant={activeTab === 'participants' ? 'secondary' : 'ghost'}
className="justify-start"
onClick={() => setActiveTab('participants')}
>
<UserIcon className="mr-2 h-4 w-4" />
Participants
</Button>
<Button
variant={activeTab === 'users' ? 'secondary' : 'ghost'}
className="justify-start"
onClick={() => setActiveTab('users')}
>
<UsersIcon className="mr-2 h-4 w-4" />
Users
</Button>
</div>
<TabsContent value="settings" className="space-y-6">
<SettingsTab study={study} />
</TabsContent>
<TabsContent value="participants" className="space-y-6">
<ParticipantsTab studyId={study.id} permissions={study.permissions} />
</TabsContent>
</Tabs>
<div className="flex-1">
<div className={cn(activeTab === 'settings' ? 'block' : 'hidden')}>
<SettingsTab study={study} />
</div>
<div className={cn(activeTab === 'participants' ? 'block' : 'hidden')}>
<ParticipantsTab studyId={study.id} permissions={study.permissions} />
</div>
<div className={cn(activeTab === 'users' ? 'block' : 'hidden')}>
<UsersTab studyId={study.id} permissions={study.permissions} />
</div>
</div>
</div>
</div>
);
}