Add experiment management system

This commit is contained in:
2025-07-18 21:25:27 -04:00
parent 0cc5c8ae89
commit adf0820f32
9 changed files with 1400 additions and 69 deletions

View File

@@ -12,7 +12,8 @@ export default async function ExperimentDesignerPage({
params,
}: ExperimentDesignerPageProps) {
try {
const experiment = await api.experiments.get({ id: params.id });
const resolvedParams = await params;
const experiment = await api.experiments.get({ id: resolvedParams.id });
if (!experiment) {
notFound();

View File

@@ -52,10 +52,15 @@ const statusConfig = {
},
};
export default async function StudyDetailPage({ params }: StudyDetailPageProps) {
export default async function StudyDetailPage({
params,
}: StudyDetailPageProps) {
try {
const study = await api.studies.get({ id: params.id });
const members = await api.studies.getMembers({ studyId: params.id });
const resolvedParams = await params;
const study = await api.studies.get({ id: resolvedParams.id });
const members = await api.studies.getMembers({
studyId: resolvedParams.id,
});
if (!study) {
notFound();
@@ -67,7 +72,7 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
<div className="p-8">
{/* Header */}
<div className="mb-8">
<div className="flex items-center space-x-2 text-sm text-slate-600 mb-4">
<div className="mb-4 flex items-center space-x-2 text-sm text-slate-600">
<Link href="/studies" className="hover:text-slate-900">
Studies
</Link>
@@ -76,9 +81,9 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</div>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-3 mb-2">
<h1 className="text-3xl font-bold text-slate-900 truncate">
<div className="min-w-0 flex-1">
<div className="mb-2 flex items-center space-x-3">
<h1 className="truncate text-3xl font-bold text-slate-900">
{study.name}
</h1>
<Badge className={statusInfo.className} variant="secondary">
@@ -86,19 +91,19 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
{statusInfo.label}
</Badge>
</div>
<p className="text-slate-600 text-lg">{study.description}</p>
<p className="text-lg text-slate-600">{study.description}</p>
</div>
<div className="flex items-center space-x-2 ml-4">
<div className="ml-4 flex items-center space-x-2">
<Button asChild variant="outline">
<Link href={`/studies/${study.id}/edit`}>
<Settings className="h-4 w-4 mr-2" />
<Settings className="mr-2 h-4 w-4" />
Edit Study
</Link>
</Button>
<Button asChild>
<Link href={`/studies/${study.id}/experiments/new`}>
<Plus className="h-4 w-4 mr-2" />
<Plus className="mr-2 h-4 w-4" />
New Experiment
</Link>
</Button>
@@ -106,9 +111,9 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
<div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Main Content */}
<div className="lg:col-span-2 space-y-8">
<div className="space-y-8 lg:col-span-2">
{/* Study Information */}
<Card>
<CardHeader>
@@ -118,27 +123,41 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label className="text-sm font-medium text-slate-700">Institution</label>
<label className="text-sm font-medium text-slate-700">
Institution
</label>
<p className="text-slate-900">{study.institution}</p>
</div>
{study.irbProtocolNumber && (
<div>
<label className="text-sm font-medium text-slate-700">IRB Protocol</label>
<p className="text-slate-900">{study.irbProtocolNumber}</p>
<label className="text-sm font-medium text-slate-700">
IRB Protocol
</label>
<p className="text-slate-900">
{study.irbProtocolNumber}
</p>
</div>
)}
<div>
<label className="text-sm font-medium text-slate-700">Created</label>
<label className="text-sm font-medium text-slate-700">
Created
</label>
<p className="text-slate-900">
{formatDistanceToNow(study.createdAt, { addSuffix: true })}
{formatDistanceToNow(study.createdAt, {
addSuffix: true,
})}
</p>
</div>
<div>
<label className="text-sm font-medium text-slate-700">Last Updated</label>
<label className="text-sm font-medium text-slate-700">
Last Updated
</label>
<p className="text-slate-900">
{formatDistanceToNow(study.updatedAt, { addSuffix: true })}
{formatDistanceToNow(study.updatedAt, {
addSuffix: true,
})}
</p>
</div>
</div>
@@ -155,7 +174,7 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</CardTitle>
<Button asChild variant="outline" size="sm">
<Link href={`/studies/${study.id}/experiments/new`}>
<Plus className="h-4 w-4 mr-2" />
<Plus className="mr-2 h-4 w-4" />
Add Experiment
</Link>
</Button>
@@ -166,13 +185,14 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</CardHeader>
<CardContent>
{/* Placeholder for experiments list */}
<div className="text-center py-8">
<FlaskConical className="h-12 w-12 text-slate-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-slate-900 mb-2">
<div className="py-8 text-center">
<FlaskConical className="mx-auto mb-4 h-12 w-12 text-slate-400" />
<h3 className="mb-2 text-lg font-semibold text-slate-900">
No Experiments Yet
</h3>
<p className="text-slate-600 mb-4">
Create your first experiment to start designing research protocols
<p className="mb-4 text-slate-600">
Create your first experiment to start designing research
protocols
</p>
<Button asChild>
<Link href={`/studies/${study.id}/experiments/new`}>
@@ -192,13 +212,14 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center py-8">
<Calendar className="h-12 w-12 text-slate-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-slate-900 mb-2">
<div className="py-8 text-center">
<Calendar className="mx-auto mb-4 h-12 w-12 text-slate-400" />
<h3 className="mb-2 text-lg font-semibold text-slate-900">
No Recent Activity
</h3>
<p className="text-slate-600">
Activity will appear here once you start working on this study
Activity will appear here once you start working on this
study
</p>
</div>
</CardContent>
@@ -216,25 +237,30 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
<span>Team</span>
</CardTitle>
<Button variant="outline" size="sm">
<Plus className="h-4 w-4 mr-2" />
<Plus className="mr-2 h-4 w-4" />
Invite
</Button>
</div>
<CardDescription>
{members.length} team member{members.length !== 1 ? 's' : ''}
{members.length} team member{members.length !== 1 ? "s" : ""}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-3">
{members.map((member) => (
<div key={member.user.id} className="flex items-center space-x-3">
<div
key={member.user.id}
className="flex items-center space-x-3"
>
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-100">
<span className="text-sm font-medium text-blue-600">
{(member.user.name || member.user.email).charAt(0).toUpperCase()}
{(member.user.name || member.user.email)
.charAt(0)
.toUpperCase()}
</span>
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-900 truncate">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-slate-900">
{member.user.name || member.user.email}
</p>
<p className="text-xs text-slate-500 capitalize">
@@ -262,16 +288,22 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
<span className="font-medium">0</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-slate-600">Total Trials:</span>
<span className="text-sm text-slate-600">
Total Trials:
</span>
<span className="font-medium">0</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-slate-600">Participants:</span>
<span className="text-sm text-slate-600">
Participants:
</span>
<span className="font-medium">0</span>
</div>
<Separator />
<div className="flex justify-between">
<span className="text-sm text-slate-600">Completion Rate:</span>
<span className="text-sm text-slate-600">
Completion Rate:
</span>
<span className="font-medium text-green-600"></span>
</div>
</div>
@@ -284,21 +316,33 @@ export default async function StudyDetailPage({ params }: StudyDetailPageProps)
<CardTitle>Quick Actions</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
<Button asChild variant="outline" className="w-full justify-start">
<Button
asChild
variant="outline"
className="w-full justify-start"
>
<Link href={`/studies/${study.id}/participants`}>
<Users className="h-4 w-4 mr-2" />
<Users className="mr-2 h-4 w-4" />
Manage Participants
</Link>
</Button>
<Button asChild variant="outline" className="w-full justify-start">
<Button
asChild
variant="outline"
className="w-full justify-start"
>
<Link href={`/studies/${study.id}/trials`}>
<Calendar className="h-4 w-4 mr-2" />
<Calendar className="mr-2 h-4 w-4" />
Schedule Trials
</Link>
</Button>
<Button asChild variant="outline" className="w-full justify-start">
<Button
asChild
variant="outline"
className="w-full justify-start"
>
<Link href={`/studies/${study.id}/analytics`}>
<BarChart3 className="h-4 w-4 mr-2" />
<BarChart3 className="mr-2 h-4 w-4" />
View Analytics
</Link>
</Button>

View File

@@ -0,0 +1,453 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import Link from "next/link";
import { ArrowLeft, Calendar, Users, FlaskConical, Clock } from "lucide-react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { Textarea } from "~/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import { Separator } from "~/components/ui/separator";
import { api } from "~/trpc/react";
const createTrialSchema = z.object({
experimentId: z.string().uuid("Please select an experiment"),
participantId: z.string().uuid("Please select a participant"),
scheduledAt: z.string().min(1, "Please select a date and time"),
wizardId: z.string().uuid().optional(),
notes: z.string().max(1000, "Notes cannot exceed 1000 characters").optional(),
});
type CreateTrialFormData = z.infer<typeof createTrialSchema>;
export default function NewTrialPage() {
const router = useRouter();
const [isSubmitting, setIsSubmitting] = useState(false);
const {
register,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm<CreateTrialFormData>({
resolver: zodResolver(createTrialSchema),
});
// Fetch available experiments
const { data: experimentsData, isLoading: experimentsLoading } = api.experiments.getUserExperiments.useQuery(
{ page: 1, limit: 100 },
);
// Fetch available participants
const { data: participantsData, isLoading: participantsLoading } = api.participants.list.useQuery(
{ page: 1, limit: 100 },
);
// Fetch potential wizards (users with wizard or researcher roles)
const { data: wizardsData, isLoading: wizardsLoading } = api.users.getWizards.useQuery();
const createTrialMutation = api.trials.create.useMutation({
onSuccess: (trial) => {
router.push(`/trials/${trial.id}`);
},
onError: (error) => {
console.error("Failed to create trial:", error);
setIsSubmitting(false);
},
});
const onSubmit = async (data: CreateTrialFormData) => {
setIsSubmitting(true);
try {
await createTrialMutation.mutateAsync({
...data,
scheduledAt: new Date(data.scheduledAt),
wizardId: data.wizardId || null,
notes: data.notes || null,
});
} catch (error) {
// Error handling is done in the mutation's onError callback
}
};
const watchedExperimentId = watch("experimentId");
const watchedParticipantId = watch("participantId");
const watchedWizardId = watch("wizardId");
const selectedExperiment = experimentsData?.experiments?.find(
exp => exp.id === watchedExperimentId
);
const selectedParticipant = participantsData?.participants?.find(
p => p.id === watchedParticipantId
);
// Generate datetime-local input min value (current time)
const now = new Date();
const minDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
.toISOString()
.slice(0, 16);
return (
<div className="p-8">
{/* Header */}
<div className="mb-8">
<div className="flex items-center space-x-2 text-sm text-slate-600 mb-4">
<Link href="/trials" className="hover:text-slate-900 flex items-center">
<ArrowLeft className="h-4 w-4 mr-1" />
Trials
</Link>
<span>/</span>
<span className="text-slate-900">Schedule New Trial</span>
</div>
<div className="flex items-center space-x-3">
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-green-100">
<Calendar className="h-6 w-6 text-green-600" />
</div>
<div>
<h1 className="text-3xl font-bold text-slate-900">Schedule New Trial</h1>
<p className="text-slate-600">Set up a research trial with a participant and experiment</p>
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Main Form */}
<div className="lg:col-span-2">
<Card>
<CardHeader>
<CardTitle>Trial Details</CardTitle>
<CardDescription>
Configure the experiment, participant, and scheduling for this trial session.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
{/* Experiment Selection */}
<div className="space-y-2">
<Label htmlFor="experimentId">Experiment *</Label>
<Select
value={watchedExperimentId}
onValueChange={(value) => setValue("experimentId", value)}
disabled={experimentsLoading}
>
<SelectTrigger className={errors.experimentId ? "border-red-500" : ""}>
<SelectValue placeholder={experimentsLoading ? "Loading experiments..." : "Select an experiment"} />
</SelectTrigger>
<SelectContent>
{experimentsData?.experiments?.map((experiment) => (
<SelectItem key={experiment.id} value={experiment.id}>
<div className="flex flex-col">
<span className="font-medium">{experiment.name}</span>
<span className="text-xs text-slate-500">{experiment.study.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
{errors.experimentId && (
<p className="text-sm text-red-600">{errors.experimentId.message}</p>
)}
{selectedExperiment && (
<div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
<p className="text-sm text-blue-800">
<strong>Study:</strong> {selectedExperiment.study.name}
</p>
<p className="text-sm text-blue-700 mt-1">
{selectedExperiment.description}
</p>
{selectedExperiment.estimatedDuration && (
<p className="text-sm text-blue-700 mt-1">
<strong>Estimated Duration:</strong> {selectedExperiment.estimatedDuration} minutes
</p>
)}
</div>
)}
</div>
{/* Participant Selection */}
<div className="space-y-2">
<Label htmlFor="participantId">Participant *</Label>
<Select
value={watchedParticipantId}
onValueChange={(value) => setValue("participantId", value)}
disabled={participantsLoading}
>
<SelectTrigger className={errors.participantId ? "border-red-500" : ""}>
<SelectValue placeholder={participantsLoading ? "Loading participants..." : "Select a participant"} />
</SelectTrigger>
<SelectContent>
{participantsData?.participants?.map((participant) => (
<SelectItem key={participant.id} value={participant.id}>
<div className="flex flex-col">
<span className="font-medium">{participant.participantCode}</span>
{participant.name && (
<span className="text-xs text-slate-500">{participant.name}</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
{errors.participantId && (
<p className="text-sm text-red-600">{errors.participantId.message}</p>
)}
{selectedParticipant && (
<div className="p-3 bg-green-50 rounded-lg border border-green-200">
<p className="text-sm text-green-800">
<strong>Code:</strong> {selectedParticipant.participantCode}
</p>
{selectedParticipant.name && (
<p className="text-sm text-green-700 mt-1">
<strong>Name:</strong> {selectedParticipant.name}
</p>
)}
{selectedParticipant.email && (
<p className="text-sm text-green-700 mt-1">
<strong>Email:</strong> {selectedParticipant.email}
</p>
)}
</div>
)}
</div>
{/* Scheduled Date & Time */}
<div className="space-y-2">
<Label htmlFor="scheduledAt">Scheduled Date & Time *</Label>
<Input
id="scheduledAt"
type="datetime-local"
min={minDateTime}
{...register("scheduledAt")}
className={errors.scheduledAt ? "border-red-500" : ""}
/>
{errors.scheduledAt && (
<p className="text-sm text-red-600">{errors.scheduledAt.message}</p>
)}
<p className="text-xs text-muted-foreground">
Select when this trial session should take place
</p>
</div>
{/* Wizard Assignment */}
<div className="space-y-2">
<Label htmlFor="wizardId">Assigned Wizard (Optional)</Label>
<Select
value={watchedWizardId}
onValueChange={(value) => setValue("wizardId", value)}
disabled={wizardsLoading}
>
<SelectTrigger>
<SelectValue placeholder={wizardsLoading ? "Loading wizards..." : "Select a wizard (optional)"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">No wizard assigned</SelectItem>
{wizardsData?.map((wizard) => (
<SelectItem key={wizard.id} value={wizard.id}>
<div className="flex flex-col">
<span className="font-medium">{wizard.name || wizard.email}</span>
<span className="text-xs text-slate-500 capitalize">{wizard.role}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Assign a specific team member to operate the wizard interface
</p>
</div>
{/* Notes */}
<div className="space-y-2">
<Label htmlFor="notes">Notes (Optional)</Label>
<Textarea
id="notes"
{...register("notes")}
placeholder="Add any special instructions, participant details, or setup notes..."
rows={3}
className={errors.notes ? "border-red-500" : ""}
/>
{errors.notes && (
<p className="text-sm text-red-600">{errors.notes.message}</p>
)}
</div>
{/* Error Message */}
{createTrialMutation.error && (
<div className="rounded-md bg-red-50 p-3">
<p className="text-sm text-red-800">
Failed to create trial: {createTrialMutation.error.message}
</p>
</div>
)}
{/* Form Actions */}
<Separator />
<div className="flex justify-end space-x-3">
<Button
type="button"
variant="outline"
onClick={() => router.back()}
disabled={isSubmitting}
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || experimentsLoading || participantsLoading}
className="min-w-[140px]"
>
{isSubmitting ? (
<div className="flex items-center space-x-2">
<svg className="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
<span>Scheduling...</span>
</div>
) : (
"Schedule Trial"
)}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
{/* Sidebar */}
<div className="space-y-6">
{/* Quick Stats */}
<Card>
<CardHeader>
<CardTitle className="flex items-center space-x-2">
<FlaskConical className="h-5 w-5" />
<span>Available Resources</span>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3 text-sm">
<div className="flex justify-between">
<span className="text-slate-600">Experiments:</span>
<span className="font-medium">
{experimentsLoading ? "..." : experimentsData?.experiments?.length || 0}
</span>
</div>
<div className="flex justify-between">
<span className="text-slate-600">Participants:</span>
<span className="font-medium">
{participantsLoading ? "..." : participantsData?.participants?.length || 0}
</span>
</div>
<div className="flex justify-between">
<span className="text-slate-600">Available Wizards:</span>
<span className="font-medium">
{wizardsLoading ? "..." : wizardsData?.length || 0}
</span>
</div>
</div>
</CardContent>
</Card>
{/* Trial Process */}
<Card>
<CardHeader>
<CardTitle className="flex items-center space-x-2">
<Clock className="h-5 w-5" />
<span>Trial Process</span>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-3 text-sm">
<div className="flex items-start space-x-3">
<div className="mt-1 h-2 w-2 rounded-full bg-blue-600"></div>
<div>
<p className="font-medium">Schedule Trial</p>
<p className="text-slate-600">Set up experiment and participant</p>
</div>
</div>
<div className="flex items-start space-x-3">
<div className="mt-1 h-2 w-2 rounded-full bg-slate-300"></div>
<div>
<p className="font-medium">Check-in Participant</p>
<p className="text-slate-600">Verify consent and prepare setup</p>
</div>
</div>
<div className="flex items-start space-x-3">
<div className="mt-1 h-2 w-2 rounded-full bg-slate-300"></div>
<div>
<p className="font-medium">Start Trial</p>
<p className="text-slate-600">Begin experiment execution</p>
</div>
</div>
<div className="flex items-start space-x-3">
<div className="mt-1 h-2 w-2 rounded-full bg-slate-300"></div>
<div>
<p className="font-medium">Wizard Control</p>
<p className="text-slate-600">Real-time robot operation</p>
</div>
</div>
<div className="flex items-start space-x-3">
<div className="mt-1 h-2 w-2 rounded-full bg-slate-300"></div>
<div>
<p className="font-medium">Complete & Analyze</p>
<p className="text-slate-600">Review data and results</p>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Tips */}
<Card>
<CardHeader>
<CardTitle>💡 Tips</CardTitle>
</CardHeader>
<CardContent className="space-y-3 text-sm text-slate-600">
<p>
<strong>Preparation:</strong> Ensure all equipment is ready before the scheduled time.
</p>
<p>
<strong>Participant Code:</strong> Use anonymous codes to protect participant privacy.
</p>
<p>
<strong>Wizard Assignment:</strong> You can assign a wizard now or during the trial.
</p>
</CardContent>
</Card>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,18 @@
import { TrialsGrid } from "~/components/trials/TrialsGrid";
export default function TrialsPage() {
return (
<div className="p-8">
{/* Header */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-slate-900">Trials</h1>
<p className="mt-2 text-slate-600">
Schedule, execute, and monitor HRI experiment trials with real-time wizard control
</p>
</div>
{/* Trials Grid */}
<TrialsGrid />
</div>
);
}