chore(deps): Update dependencies and enhance API error handling

- Added '@vercel/analytics' to package.json for improved analytics tracking.
- Updated 'next' version from 15.0.2 to 15.0.3 to incorporate the latest features and fixes.
- Refactored API routes for invitations and studies to improve error handling and response structure.
- Enhanced permission checks in the invitations and studies API to ensure proper access control.
- Removed the participants dashboard page as part of a restructuring effort.
- Updated the database schema to include environment settings for users and studies.
- Improved the dashboard components to handle loading states and display statistics more effectively.
This commit is contained in:
2024-12-04 12:32:54 -05:00
parent cb4c0f9c87
commit 95b106d9e9
22 changed files with 1160 additions and 771 deletions

View File

@@ -1,201 +1,79 @@
'use client';
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
import { useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import { InviteUserDialog } from "~/components/invite-user-dialog";
import { Button } from "~/components/ui/button";
import { Loader2 } from "lucide-react";
import { useToast } from "~/hooks/use-toast";
import { SettingsTab } from "~/components/studies/settings-tab";
import { ParticipantsTab } from "~/components/studies/participants-tab";
import { useEffect } from "react";
interface Study {
id: number;
title: string;
description: string;
description: string | null;
permissions: string[];
}
interface Invitation {
id: string;
email: string;
roleName: string;
accepted: boolean;
expiresAt: string;
}
export default function StudySettingsPage() {
const params = useParams();
export default function StudySettings() {
const [study, setStudy] = useState<Study | null>(null);
const [invitations, setInvitations] = useState<Invitation[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const { toast } = useToast();
const fetchStudyData = async () => {
try {
const response = await fetch(`/api/studies/${params.id}`);
if (!response.ok) throw new Error("Failed to fetch study");
const data = await response.json();
setStudy(data);
} catch (error) {
setError("Failed to load study details");
console.error("Error fetching study:", error);
toast({
title: "Error",
description: "Failed to load study details",
variant: "destructive",
});
}
};
const fetchInvitations = async () => {
try {
const response = await fetch(`/api/invitations?studyId=${params.id}`);
if (!response.ok) throw new Error("Failed to fetch invitations");
const data = await response.json();
setInvitations(data);
} catch (error) {
setError("Failed to load invitations");
console.error("Error fetching invitations:", error);
toast({
title: "Error",
description: "Failed to load invitations",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
};
const { id } = useParams();
const router = useRouter();
const searchParams = useSearchParams();
const tab = searchParams.get('tab') || 'settings';
useEffect(() => {
const loadData = async () => {
await Promise.all([fetchStudyData(), fetchInvitations()]);
};
loadData();
}, [params.id]); // eslint-disable-line react-hooks/exhaustive-deps
const handleDeleteInvitation = async (invitationId: string) => {
try {
const response = await fetch(`/api/invitations/${invitationId}`, {
method: "DELETE",
});
if (!response.ok) {
throw new Error("Failed to delete invitation");
const fetchStudy = async () => {
try {
const response = await fetch(`/api/studies/${id}`);
if (!response.ok) throw new Error("Failed to fetch study");
const data = await response.json();
setStudy(data.data);
} catch (error) {
console.error("Error fetching study:", error);
setError(error instanceof Error ? error.message : "Failed to load study");
} finally {
setIsLoading(false);
}
};
// Update local state
setInvitations(invitations.filter(inv => inv.id !== invitationId));
toast({
title: "Success",
description: "Invitation deleted successfully",
});
} catch (error) {
console.error("Error deleting invitation:", error);
toast({
title: "Error",
description: "Failed to delete invitation",
variant: "destructive",
});
}
fetchStudy();
}, [id]);
const handleTabChange = (value: string) => {
router.push(`/dashboard/studies/${id}/settings?tab=${value}`);
};
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 className="h-8 w-8 animate-spin" />
</div>
);
return <div className="container py-6">Loading...</div>;
}
if (error) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<p className="text-red-500">{error}</p>
</div>
);
}
if (!study) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<p className="text-gray-500">Study not found</p>
</div>
);
if (error || !study) {
return <div className="container py-6 text-destructive">{error || "Study not found"}</div>;
}
return (
<div className="container py-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">{study.title}</h1>
<p className="text-muted-foreground">{study.description}</p>
<div className="flex flex-col gap-2">
<h1 className="text-3xl font-bold tracking-tight">{study.title}</h1>
<p className="text-muted-foreground">
Manage study settings and participants
</p>
</div>
<Tabs defaultValue="invites" className="space-y-4">
<Tabs value={tab} onValueChange={handleTabChange} className="space-y-6">
<TabsList>
<TabsTrigger value="invites">Invites</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
<TabsTrigger value="participants">Participants</TabsTrigger>
</TabsList>
<TabsContent value="invites">
<Card>
<CardHeader>
<CardTitle>Manage Invitations</CardTitle>
<CardDescription>
Invite researchers and participants to collaborate on &ldquo;{study.title}&rdquo;
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div>
<InviteUserDialog studyId={study.id} onInviteSent={fetchInvitations} />
</div>
{invitations.length > 0 ? (
<div className="space-y-4">
{invitations.map((invitation) => (
<div
key={invitation.id}
className="flex items-center justify-between p-4 border rounded-lg bg-card"
>
<div>
<p className="font-medium">{invitation.email}</p>
<p className="text-sm text-muted-foreground">
Role: {invitation.roleName}
{invitation.accepted ? " • Accepted" : " • Pending"}
</p>
</div>
{!invitation.accepted && (
<Button
variant="outline"
size="sm"
onClick={() => handleDeleteInvitation(invitation.id)}
>
Cancel
</Button>
)}
</div>
))}
</div>
) : (
<p className="text-muted-foreground">No invitations sent yet.</p>
)}
</CardContent>
</Card>
<TabsContent value="settings" className="space-y-6">
<SettingsTab study={study} />
</TabsContent>
<TabsContent value="settings">
<Card>
<CardHeader>
<CardTitle>Study Settings</CardTitle>
<CardDescription>
Configure study settings and permissions
</CardDescription>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">Settings coming soon...</p>
</CardContent>
</Card>
<TabsContent value="participants" className="space-y-6">
<ParticipantsTab studyId={study.id} permissions={study.permissions} />
</TabsContent>
</Tabs>
</div>

View File

@@ -1,6 +1,6 @@
'use client';
import { useEffect, useState } from "react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { PlusIcon, Trash2Icon, Settings2 } from "lucide-react";
import { Button } from "~/components/ui/button";
@@ -9,73 +9,86 @@ import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { Textarea } from "~/components/ui/textarea";
import { useToast } from "~/hooks/use-toast";
import { PERMISSIONS, hasPermission } from "~/lib/permissions-client";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
AlertDialogFooter
} from "~/components/ui/alert-dialog";
import { ROLES } from "~/lib/roles";
interface Study {
id: number;
title: string;
description: string;
description: string | null;
createdAt: string;
updatedAt: string | null;
userId: string;
permissions: string[];
roles: string[];
}
// Helper function to format role name
function formatRoleName(role: string): string {
return role
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
export default function Studies() {
const [studies, setStudies] = useState<Study[]>([]);
const [newStudyTitle, setNewStudyTitle] = useState("");
const [newStudyDescription, setNewStudyDescription] = useState("");
const [loading, setLoading] = useState(true);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const router = useRouter();
const { toast } = useToast();
useEffect(() => {
fetchStudies();
}, []);
const fetchStudies = async () => {
try {
const response = await fetch('/api/studies');
const response = await fetch("/api/studies");
if (!response.ok) throw new Error("Failed to fetch studies");
const data = await response.json();
setStudies(data);
setStudies(data.data || []);
} catch (error) {
console.error('Error fetching studies:', error);
console.error("Error fetching studies:", error);
toast({
title: "Error",
description: "Failed to load studies",
variant: "destructive",
});
} finally {
setLoading(false);
}
};
const createStudy = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/studies', {
method: 'POST',
const response = await fetch("/api/studies", {
method: "POST",
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
},
body: JSON.stringify({
title: newStudyTitle,
description: newStudyDescription,
}),
body: JSON.stringify({ title, description }),
});
if (!response.ok) {
throw new Error('Failed to create study');
throw new Error("Failed to create study");
}
const newStudy = await response.json();
setStudies([...studies, newStudy]);
setNewStudyTitle("");
setNewStudyDescription("");
const data = await response.json();
setStudies([...studies, data.data]);
setTitle("");
setDescription("");
toast({
title: "Success",
description: "Study created successfully",
});
} catch (error) {
console.error('Error creating study:', error);
console.error("Error creating study:", error);
toast({
title: "Error",
description: "Failed to create study",
@@ -87,11 +100,11 @@ export default function Studies() {
const deleteStudy = async (id: number) => {
try {
const response = await fetch(`/api/studies/${id}`, {
method: 'DELETE',
method: "DELETE",
});
if (!response.ok) {
throw new Error('Failed to delete study');
throw new Error("Failed to delete study");
}
setStudies(studies.filter(study => study.id !== id));
@@ -100,7 +113,7 @@ export default function Studies() {
description: "Study deleted successfully",
});
} catch (error) {
console.error('Error deleting study:', error);
console.error("Error deleting study:", error);
toast({
title: "Error",
description: "Failed to delete study",
@@ -109,85 +122,128 @@ export default function Studies() {
}
};
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>
);
}
// Fetch studies on mount
useState(() => {
fetchStudies();
});
return (
<div className="container py-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">Studies</h1>
<p className="text-muted-foreground">Manage your research studies</p>
<div className="flex flex-col gap-2">
<h1 className="text-3xl font-bold tracking-tight">Studies</h1>
<p className="text-muted-foreground">
Manage your research studies and experiments
</p>
</div>
<Card>
<CardHeader>
<CardTitle>Create New Study</CardTitle>
<CardDescription>
Add a new research study to your collection
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={createStudy} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="title">Study Title</Label>
<Input
type="text"
id="title"
value={newStudyTitle}
onChange={(e) => setNewStudyTitle(e.target.value)}
placeholder="Enter study title"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={newStudyDescription}
onChange={(e) => setNewStudyDescription(e.target.value)}
placeholder="Enter study description"
rows={3}
/>
</div>
<Button type="submit">
<PlusIcon className="w-4 h-4 mr-2" />
Create Study
</Button>
</form>
</CardContent>
</Card>
{hasPermission(studies[0]?.permissions || [], PERMISSIONS.CREATE_STUDY) && (
<Card>
<CardHeader>
<CardTitle>Create New Study</CardTitle>
<CardDescription>Add a new research study to your collection</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={createStudy} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="title">Study Title</Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter study title"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Enter study description"
/>
</div>
<Button type="submit">
<PlusIcon className="w-4 h-4 mr-2" />
Create Study
</Button>
</form>
</CardContent>
</Card>
)}
<div className="grid gap-4">
{studies.length > 0 ? (
studies.map((study) => (
<Card key={study.id}>
<CardHeader>
<CardTitle>{study.title}</CardTitle>
<CardDescription>{study.description}</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => router.push(`/dashboard/studies/${study.id}/settings`)}
>
<Settings2 className="w-4 h-4 mr-2" />
Settings
</Button>
<Button
variant="outline"
onClick={() => deleteStudy(study.id)}
>
<Trash2Icon className="w-4 h-4 mr-2" />
Delete
</Button>
<Card key={study.id} className="overflow-hidden">
<div className="p-6">
<div className="flex flex-col gap-1.5">
<div className="flex items-start justify-between">
<div className="space-y-1">
<h3 className="font-semibold leading-none tracking-tight">
{study.title}
</h3>
<p className="text-sm text-muted-foreground">
{study.description || "No description provided."}
</p>
<p className="text-sm">
<span className="text-muted-foreground">Your Roles: </span>
<span className="text-foreground">
{study.roles?.map(formatRoleName).join(", ")}
</span>
</p>
</div>
<div className="flex items-center gap-2">
{(hasPermission(study.permissions, PERMISSIONS.EDIT_STUDY) ||
hasPermission(study.permissions, PERMISSIONS.MANAGE_ROLES)) && (
<Button
variant="outline"
size="sm"
onClick={() => router.push(`/dashboard/studies/${study.id}/settings`)}
>
<Settings2 className="w-4 h-4 mr-2" />
Settings
</Button>
)}
{hasPermission(study.permissions, PERMISSIONS.MANAGE_SYSTEM_SETTINGS) && (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm">
<Trash2Icon className="w-4 h-4 mr-2" />
Delete
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<div className="text-sm text-muted-foreground">
<p className="mb-2">
This action cannot be undone. This will permanently delete the study
&quot;{study.title}&quot; and all associated data including:
</p>
<ul className="list-disc list-inside">
<li>All participant data</li>
<li>All user roles and permissions</li>
<li>All pending invitations</li>
</ul>
</div>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => deleteStudy(study.id)}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete Study
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</div>
</div>
</div>
</CardContent>
</div>
</Card>
))
) : (