mirror of
https://github.com/soconnor0919/hristudio.git
synced 2025-12-11 14:44:44 -05:00
Add experiment management system
This commit is contained in:
@@ -55,15 +55,28 @@ All major tRPC routers implemented and schema-aligned:
|
||||
- **Admin interface** for user and role management
|
||||
- **Authorization utilities** for client and server-side use
|
||||
|
||||
#### 4. User Interface Components (60%) 🚧
|
||||
#### 4. User Interface Components (85%) ✅
|
||||
- **Authentication pages** complete (signin, signup, signout)
|
||||
- **User profile management** interface complete
|
||||
- **Admin dashboard** with user/role management complete
|
||||
- **Dashboard layout** with sidebar navigation and role-based access
|
||||
- **Study management interface** complete with CRUD operations
|
||||
- **Visual Experiment Designer** complete with drag-and-drop functionality
|
||||
- **Role-based navigation** and access control
|
||||
- **Responsive UI components** using shadcn/ui
|
||||
- **Protected route displays** and unauthorized handling
|
||||
|
||||
#### 5. Project Structure (100%)
|
||||
#### 5. Visual Experiment Designer (100%) ✅
|
||||
- **Drag-and-Drop Canvas** - Professional drag-and-drop interface using @dnd-kit
|
||||
- **Step Library** - 4 step types: Wizard Action, Robot Action, Parallel Steps, Conditional Branch
|
||||
- **Visual Step Cards** - Rich information display with reordering capabilities
|
||||
- **Real-time Saving** - Auto-save with version control and conflict resolution
|
||||
- **API Integration** - Complete tRPC integration for design persistence
|
||||
- **Professional UI/UX** - Loading states, error handling, empty states
|
||||
- **Step Configuration** - Framework for parameter editing (expandable)
|
||||
- **Access Control** - Role-based permissions throughout designer
|
||||
|
||||
#### 6. Project Structure (100%) ✅
|
||||
- T3 stack properly configured
|
||||
- Environment variables setup
|
||||
- Database connection with connection pooling
|
||||
@@ -178,23 +191,25 @@ inArray(studyMembers.role, ["owner", "researcher"] as const) // ✅ Proper typin
|
||||
3. **Test basic CRUD operations** for each entity
|
||||
4. **Set up development database** with sample data
|
||||
|
||||
#### Week 2: UI Foundation
|
||||
1. **Create basic layout** with navigation
|
||||
2. **Implement authentication flow**
|
||||
3. **Build study management interface**
|
||||
4. **Add experiment designer basics**
|
||||
#### Week 2: UI Foundation ✅ (Completed)
|
||||
1. **Create basic layout** with navigation ✅
|
||||
2. **Implement authentication flow** ✅
|
||||
3. **Build study management interface** ✅
|
||||
4. **Add experiment designer basics** ✅
|
||||
|
||||
#### Week 3: Trial Execution
|
||||
1. **Implement wizard interface**
|
||||
2. **Add real-time trial monitoring**
|
||||
3. **Build participant management**
|
||||
4. **Test end-to-end trial flow**
|
||||
#### Week 3: Trial Execution (Current Priority)
|
||||
1. **Implement wizard interface** - Real-time trial control
|
||||
2. **Add real-time trial monitoring** - WebSocket integration
|
||||
3. **Build participant management** - Registration and consent tracking
|
||||
4. **Test end-to-end trial flow** - Complete researcher workflow
|
||||
|
||||
#### Week 4: Advanced Features
|
||||
1. **Media upload/playback**
|
||||
2. **Data analysis tools**
|
||||
3. **Export functionality**
|
||||
4. **Collaboration features**
|
||||
1. **Step Configuration Modals** - Detailed parameter editing for experiment steps
|
||||
2. **Robot Action Library** - Plugin-based action definitions
|
||||
3. **Media upload/playback** - Trial recording and analysis
|
||||
4. **Data analysis tools** - Statistics and visualization
|
||||
5. **Export functionality** - Data export in multiple formats
|
||||
6. **Collaboration features** - Comments and real-time collaboration
|
||||
|
||||
### 🔧 Development Commands
|
||||
|
||||
@@ -248,9 +263,10 @@ src/
|
||||
| Database Schema | 100% | ✅ Complete | - |
|
||||
| API Routers | 100% | ✅ Complete | - |
|
||||
| Authentication | 100% | ✅ Complete | - |
|
||||
| UI Components | 60% | 🚧 Auth & admin interfaces done | Medium |
|
||||
| Trial Execution | 80% | 🚧 Integration needed | High |
|
||||
| Real-time Features | 20% | ❌ WebSocket setup needed | Medium |
|
||||
| UI Components | 85% | ✅ Studies & experiments management done | Low |
|
||||
| Experiment Designer | 100% | ✅ Complete | - |
|
||||
| Trial Execution | 80% | 🚧 Wizard interface needed | High |
|
||||
| Real-time Features | 30% | 🚧 WebSocket setup needed | High |
|
||||
| File Upload | 70% | 🚧 R2 integration needed | Medium |
|
||||
| Documentation | 85% | 🚧 API docs needed | Low |
|
||||
|
||||
@@ -271,4 +287,23 @@ src/
|
||||
- ✅ **Error Handling**: Comprehensive validation and error responses
|
||||
- ✅ **Authorization**: Proper role-based access control throughout all endpoints
|
||||
|
||||
The backend foundation is robust and production-ready. Next priorities are building study/experiment management interfaces and real-time trial execution features.
|
||||
The backend foundation is robust and production-ready. **Study and experiment management interfaces are now complete with a fully functional Visual Experiment Designer.** Next priorities are real-time trial execution features and the wizard interface for live trial control.
|
||||
|
||||
## 🎯 Recent Completions
|
||||
|
||||
### Visual Experiment Designer ✅
|
||||
- **Complete drag-and-drop interface** for designing experiment protocols
|
||||
- **4 step types implemented**: Wizard Action, Robot Action, Parallel Steps, Conditional Branch
|
||||
- **Professional UI/UX** with loading states, error handling, and responsive design
|
||||
- **Real-time saving** with version control and conflict resolution
|
||||
- **Full API integration** with proper authorization and data persistence
|
||||
- **Accessible at** `/experiments/[id]/designer` with complete workflow from creation to design
|
||||
|
||||
### Study Management System ✅
|
||||
- **Complete CRUD operations** for studies with team collaboration
|
||||
- **Role-based access control** throughout the interface
|
||||
- **Professional dashboard** with sidebar navigation
|
||||
- **Study detail pages** with team management and quick actions
|
||||
- **Responsive design** working across all screen sizes
|
||||
|
||||
**The platform now provides a complete research workflow from study creation through experiment design, ready for trial execution implementation.**
|
||||
@@ -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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
453
src/app/(dashboard)/trials/new/page.tsx
Normal file
453
src/app/(dashboard)/trials/new/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
18
src/app/(dashboard)/trials/page.tsx
Normal file
18
src/app/(dashboard)/trials/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
486
src/components/trials/TrialsGrid.tsx
Normal file
486
src/components/trials/TrialsGrid.tsx
Normal file
@@ -0,0 +1,486 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Plus, Play, Pause, Square, Clock, Users, Eye, Settings } from "lucide-react";
|
||||
import { formatDistanceToNow, format } from "date-fns";
|
||||
import Link from "next/link";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "~/components/ui/card";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { api } from "~/trpc/react";
|
||||
|
||||
type TrialWithRelations = {
|
||||
id: string;
|
||||
experimentId: string;
|
||||
participantId: string;
|
||||
scheduledAt: Date;
|
||||
startedAt: Date | null;
|
||||
completedAt: Date | null;
|
||||
status: "scheduled" | "in_progress" | "completed" | "cancelled";
|
||||
duration: number | null;
|
||||
notes: string | null;
|
||||
wizardId: string | null;
|
||||
createdAt: Date;
|
||||
experiment: {
|
||||
id: string;
|
||||
name: string;
|
||||
study: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
participant: {
|
||||
id: string;
|
||||
participantCode: string;
|
||||
email: string | null;
|
||||
name: string | null;
|
||||
};
|
||||
wizard: {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string;
|
||||
} | null;
|
||||
_count?: {
|
||||
events: number;
|
||||
mediaCaptures: number;
|
||||
};
|
||||
};
|
||||
|
||||
const statusConfig = {
|
||||
scheduled: {
|
||||
label: "Scheduled",
|
||||
className: "bg-blue-100 text-blue-800 hover:bg-blue-200",
|
||||
icon: Clock,
|
||||
action: "Start Trial",
|
||||
actionIcon: Play,
|
||||
},
|
||||
in_progress: {
|
||||
label: "In Progress",
|
||||
className: "bg-green-100 text-green-800 hover:bg-green-200",
|
||||
icon: Play,
|
||||
action: "Monitor",
|
||||
actionIcon: Eye,
|
||||
},
|
||||
completed: {
|
||||
label: "Completed",
|
||||
className: "bg-gray-100 text-gray-800 hover:bg-gray-200",
|
||||
icon: Square,
|
||||
action: "Review",
|
||||
actionIcon: Eye,
|
||||
},
|
||||
cancelled: {
|
||||
label: "Cancelled",
|
||||
className: "bg-red-100 text-red-800 hover:bg-red-200",
|
||||
icon: Square,
|
||||
action: "View",
|
||||
actionIcon: Eye,
|
||||
},
|
||||
};
|
||||
|
||||
interface TrialCardProps {
|
||||
trial: TrialWithRelations;
|
||||
userRole: string;
|
||||
onTrialAction: (trialId: string, action: string) => void;
|
||||
}
|
||||
|
||||
function TrialCard({ trial, userRole, onTrialAction }: TrialCardProps) {
|
||||
const statusInfo = statusConfig[trial.status];
|
||||
const StatusIcon = statusInfo.icon;
|
||||
const ActionIcon = statusInfo.actionIcon;
|
||||
|
||||
const isScheduledSoon = trial.status === "scheduled" &&
|
||||
new Date(trial.scheduledAt).getTime() - Date.now() < 60 * 60 * 1000; // Within 1 hour
|
||||
|
||||
const canControl = userRole === "wizard" || userRole === "researcher" || userRole === "administrator";
|
||||
|
||||
return (
|
||||
<Card className={`group transition-all duration-200 hover:border-slate-300 hover:shadow-md ${
|
||||
trial.status === "in_progress" ? "ring-2 ring-green-500 shadow-md" : ""
|
||||
}`}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CardTitle className="truncate text-lg font-semibold text-slate-900 transition-colors group-hover:text-blue-600">
|
||||
<Link
|
||||
href={`/trials/${trial.id}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{trial.experiment.name}
|
||||
</Link>
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1 text-sm text-slate-600">
|
||||
Participant: {trial.participant.participantCode}
|
||||
</CardDescription>
|
||||
<div className="mt-2 flex items-center space-x-4 text-xs text-slate-500">
|
||||
<Link
|
||||
href={`/studies/${trial.experiment.study.id}`}
|
||||
className="font-medium text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
{trial.experiment.study.name}
|
||||
</Link>
|
||||
{trial.wizard && (
|
||||
<span>Wizard: {trial.wizard.name || trial.wizard.email}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-end space-y-2">
|
||||
<Badge className={statusInfo.className} variant="secondary">
|
||||
<StatusIcon className="mr-1 h-3 w-3" />
|
||||
{statusInfo.label}
|
||||
</Badge>
|
||||
{isScheduledSoon && (
|
||||
<Badge variant="outline" className="text-orange-600 border-orange-600">
|
||||
Starting Soon
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
{/* Schedule Information */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-slate-600">Scheduled:</span>
|
||||
<span className="font-medium">
|
||||
{format(trial.scheduledAt, "MMM d, yyyy 'at' h:mm a")}
|
||||
</span>
|
||||
</div>
|
||||
{trial.startedAt && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-slate-600">Started:</span>
|
||||
<span className="font-medium">
|
||||
{formatDistanceToNow(trial.startedAt, { addSuffix: true })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{trial.completedAt && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-slate-600">Completed:</span>
|
||||
<span className="font-medium">
|
||||
{formatDistanceToNow(trial.completedAt, { addSuffix: true })}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{trial.duration && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-slate-600">Duration:</span>
|
||||
<span className="font-medium">{Math.round(trial.duration / 60)} minutes</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Statistics */}
|
||||
{trial._count && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-600">Events:</span>
|
||||
<span className="font-medium">{trial._count.events}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-600">Media:</span>
|
||||
<span className="font-medium">{trial._count.mediaCaptures}</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Notes Preview */}
|
||||
{trial.notes && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-sm">
|
||||
<span className="text-slate-600">Notes: </span>
|
||||
<span className="text-slate-900">{trial.notes.substring(0, 100)}...</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 pt-2">
|
||||
{trial.status === "scheduled" && canControl && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={() => onTrialAction(trial.id, "start")}
|
||||
>
|
||||
<ActionIcon className="mr-1 h-3 w-3" />
|
||||
{statusInfo.action}
|
||||
</Button>
|
||||
)}
|
||||
{trial.status === "in_progress" && (
|
||||
<Button asChild size="sm" className="flex-1">
|
||||
<Link href={`/trials/${trial.id}/wizard`}>
|
||||
<Eye className="mr-1 h-3 w-3" />
|
||||
Wizard Interface
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{trial.status === "completed" && (
|
||||
<Button asChild size="sm" variant="outline" className="flex-1">
|
||||
<Link href={`/trials/${trial.id}/analysis`}>
|
||||
<Eye className="mr-1 h-3 w-3" />
|
||||
View Analysis
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link href={`/trials/${trial.id}`}>
|
||||
<Settings className="mr-1 h-3 w-3" />
|
||||
Details
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function TrialsGrid() {
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const [statusFilter, setStatusFilter] = useState<string>("all");
|
||||
|
||||
const { data: userSession } = api.auth.me.useQuery();
|
||||
|
||||
const {
|
||||
data: trialsData,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = api.trials.getUserTrials.useQuery(
|
||||
{
|
||||
page: 1,
|
||||
limit: 50,
|
||||
status: statusFilter === "all" ? undefined : statusFilter as any,
|
||||
},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
refetchInterval: 30000, // Refetch every 30 seconds for real-time updates
|
||||
},
|
||||
);
|
||||
|
||||
const startTrialMutation = api.trials.start.useMutation({
|
||||
onSuccess: () => {
|
||||
void refetch();
|
||||
},
|
||||
});
|
||||
|
||||
const trials = trialsData?.trials ?? [];
|
||||
const userRole = userSession?.roles?.[0]?.role || "observer";
|
||||
|
||||
const handleTrialAction = async (trialId: string, action: string) => {
|
||||
if (action === "start") {
|
||||
try {
|
||||
await startTrialMutation.mutateAsync({ id: trialId });
|
||||
} catch (error) {
|
||||
console.error("Failed to start trial:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTrialCreated = () => {
|
||||
setRefreshKey((prev) => prev + 1);
|
||||
void refetch();
|
||||
};
|
||||
|
||||
// Group trials by status for better organization
|
||||
const upcomingTrials = trials.filter(t => t.status === "scheduled");
|
||||
const activeTrials = trials.filter(t => t.status === "in_progress");
|
||||
const completedTrials = trials.filter(t => t.status === "completed");
|
||||
const cancelledTrials = trials.filter(t => t.status === "cancelled");
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Status Filter Skeleton */}
|
||||
<div className="flex items-center space-x-2">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div key={i} className="h-8 w-20 rounded bg-slate-200 animate-pulse"></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Grid Skeleton */}
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="animate-pulse">
|
||||
<CardHeader>
|
||||
<div className="space-y-2">
|
||||
<div className="h-5 w-3/4 rounded bg-slate-200"></div>
|
||||
<div className="h-4 w-1/2 rounded bg-slate-200"></div>
|
||||
<div className="h-3 w-2/3 rounded bg-slate-200"></div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 w-full rounded bg-slate-200"></div>
|
||||
<div className="h-4 w-full rounded bg-slate-200"></div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="h-8 flex-1 rounded bg-slate-200"></div>
|
||||
<div className="h-8 w-16 rounded bg-slate-200"></div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-lg bg-red-100">
|
||||
<svg
|
||||
className="h-8 w-8 text-red-600"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="mb-2 text-lg font-semibold text-slate-900">
|
||||
Failed to Load Trials
|
||||
</h3>
|
||||
<p className="mb-4 text-slate-600">
|
||||
{error.message || "An error occurred while loading your trials."}
|
||||
</p>
|
||||
<Button onClick={() => refetch()} variant="outline">
|
||||
Try Again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Quick Actions Bar */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant={statusFilter === "all" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setStatusFilter("all")}
|
||||
>
|
||||
All ({trials.length})
|
||||
</Button>
|
||||
<Button
|
||||
variant={statusFilter === "scheduled" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setStatusFilter("scheduled")}
|
||||
>
|
||||
Scheduled ({upcomingTrials.length})
|
||||
</Button>
|
||||
<Button
|
||||
variant={statusFilter === "in_progress" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setStatusFilter("in_progress")}
|
||||
>
|
||||
Active ({activeTrials.length})
|
||||
</Button>
|
||||
<Button
|
||||
variant={statusFilter === "completed" ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setStatusFilter("completed")}
|
||||
>
|
||||
Completed ({completedTrials.length})
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Button asChild>
|
||||
<Link href="/trials/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Schedule Trial
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Active Trials Section (Priority) */}
|
||||
{activeTrials.length > 0 && (statusFilter === "all" || statusFilter === "in_progress") && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="h-2 w-2 rounded-full bg-green-500 animate-pulse"></div>
|
||||
<h2 className="text-xl font-semibold text-slate-900">Active Trials</h2>
|
||||
<Badge className="bg-green-100 text-green-800">
|
||||
{activeTrials.length} running
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{activeTrials.map((trial) => (
|
||||
<TrialCard
|
||||
key={trial.id}
|
||||
trial={trial}
|
||||
userRole={userRole}
|
||||
onTrialAction={handleTrialAction}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Trials Grid */}
|
||||
<div className="space-y-4">
|
||||
{statusFilter !== "in_progress" && (
|
||||
<h2 className="text-xl font-semibold text-slate-900">
|
||||
{statusFilter === "all" ? "All Trials" :
|
||||
statusFilter === "scheduled" ? "Scheduled Trials" :
|
||||
statusFilter === "completed" ? "Completed Trials" :
|
||||
"Cancelled Trials"}
|
||||
</h2>
|
||||
)}
|
||||
|
||||
{trials.length === 0 ? (
|
||||
<Card className="text-center py-12">
|
||||
<CardContent>
|
||||
<div className="mx-auto mb-4 flex h-24 w-24 items-center justify-center rounded-lg bg-slate-100">
|
||||
<Play className="h-12 w-12 text-slate-400" />
|
||||
</div>
|
||||
<h3 className="mb-2 text-lg font-semibold text-slate-900">
|
||||
No Trials Yet
|
||||
</h3>
|
||||
<p className="mb-4 text-slate-600">
|
||||
Schedule your first trial to start collecting data with real participants.
|
||||
Trials let you execute your designed experiments with wizard control.
|
||||
</p>
|
||||
<Button asChild>
|
||||
<Link href="/trials/new">Schedule Your First Trial</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{trials
|
||||
.filter(trial =>
|
||||
statusFilter === "all" ||
|
||||
trial.status === statusFilter ||
|
||||
(statusFilter === "in_progress" && trial.status === "in_progress")
|
||||
)
|
||||
.map((trial) => (
|
||||
<TrialCard
|
||||
key={trial.id}
|
||||
trial={trial}
|
||||
userRole={userRole}
|
||||
onTrialAction={handleTrialAction}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, count, eq, desc, ilike, or } from "drizzle-orm";
|
||||
import { and, count, eq, desc, ilike, or, inArray } from "drizzle-orm";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import type { db } from "~/server/db";
|
||||
@@ -633,4 +633,89 @@ export const participantsRouter = createTRPCRouter({
|
||||
|
||||
return forms;
|
||||
}),
|
||||
|
||||
getUserParticipants: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
page: z.number().min(1).default(1),
|
||||
limit: z.number().min(1).max(100).default(20),
|
||||
search: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { page, limit, search } = input;
|
||||
const offset = (page - 1) * limit;
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Get all studies user is a member of
|
||||
const userStudies = await ctx.db.query.studyMembers.findMany({
|
||||
where: eq(studyMembers.userId, userId),
|
||||
columns: {
|
||||
studyId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const studyIds = userStudies.map((membership) => membership.studyId);
|
||||
|
||||
if (studyIds.length === 0) {
|
||||
return {
|
||||
participants: [],
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: 0,
|
||||
pages: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Build where conditions
|
||||
const conditions = [inArray(participants.studyId, studyIds)];
|
||||
|
||||
if (search) {
|
||||
conditions.push(
|
||||
or(
|
||||
ilike(participants.participantCode, `%${search}%`),
|
||||
ilike(participants.name, `%${search}%`),
|
||||
ilike(participants.email, `%${search}%`),
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
const whereClause = and(...conditions);
|
||||
|
||||
// Get participants
|
||||
const userParticipants = await ctx.db.query.participants.findMany({
|
||||
where: whereClause,
|
||||
with: {
|
||||
study: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
limit,
|
||||
offset,
|
||||
orderBy: [desc(participants.createdAt)],
|
||||
});
|
||||
|
||||
// Get total count
|
||||
const totalCountResult = await ctx.db
|
||||
.select({ count: count() })
|
||||
.from(participants)
|
||||
.where(whereClause);
|
||||
|
||||
const totalCount = totalCountResult[0]?.count ?? 0;
|
||||
|
||||
return {
|
||||
participants: userParticipants,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: totalCount,
|
||||
pages: Math.ceil(totalCount / limit),
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { z } from "zod";
|
||||
import { eq, and, desc, asc, gte, lte, inArray, type SQL } from "drizzle-orm";
|
||||
import {
|
||||
eq,
|
||||
and,
|
||||
desc,
|
||||
asc,
|
||||
gte,
|
||||
lte,
|
||||
inArray,
|
||||
count,
|
||||
type SQL,
|
||||
} from "drizzle-orm";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import {
|
||||
@@ -10,6 +20,7 @@ import {
|
||||
experiments,
|
||||
studyMembers,
|
||||
trialStatusEnum,
|
||||
mediaCaptures,
|
||||
} from "~/server/db/schema";
|
||||
import type { db } from "~/server/db";
|
||||
|
||||
@@ -534,4 +545,137 @@ export const trialsRouter = createTRPCRouter({
|
||||
|
||||
return events;
|
||||
}),
|
||||
|
||||
getUserTrials: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
page: z.number().min(1).default(1),
|
||||
limit: z.number().min(1).max(100).default(20),
|
||||
status: z.enum(trialStatusEnum.enumValues).optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { page, limit, status } = input;
|
||||
const offset = (page - 1) * limit;
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Get all studies user is a member of
|
||||
const userStudies = await ctx.db.query.studyMembers.findMany({
|
||||
where: eq(studyMembers.userId, userId),
|
||||
columns: {
|
||||
studyId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const studyIds = userStudies.map((membership) => membership.studyId);
|
||||
|
||||
if (studyIds.length === 0) {
|
||||
return {
|
||||
trials: [],
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: 0,
|
||||
pages: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Build where conditions
|
||||
const conditions = [];
|
||||
|
||||
if (status) {
|
||||
conditions.push(eq(trials.status, status));
|
||||
}
|
||||
|
||||
// Get trials from experiments in user's studies
|
||||
const userTrials = await ctx.db.query.trials.findMany({
|
||||
where: status ? and(...conditions) : undefined,
|
||||
with: {
|
||||
experiment: {
|
||||
where: inArray(experiments.studyId, studyIds),
|
||||
with: {
|
||||
study: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
studyId: true,
|
||||
},
|
||||
},
|
||||
participant: {
|
||||
columns: {
|
||||
id: true,
|
||||
participantCode: true,
|
||||
email: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
wizard: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
events: {
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
mediaCaptures: {
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
limit,
|
||||
offset,
|
||||
orderBy: [desc(trials.scheduledAt)],
|
||||
});
|
||||
|
||||
// Filter out trials from experiments not in user's studies
|
||||
const filteredTrials = userTrials.filter(
|
||||
(trial) =>
|
||||
trial.experiment && studyIds.includes(trial.experiment.studyId),
|
||||
);
|
||||
|
||||
// Get total count
|
||||
const totalCountResult = await ctx.db
|
||||
.select({ count: count() })
|
||||
.from(trials)
|
||||
.innerJoin(experiments, eq(trials.experimentId, experiments.id))
|
||||
.where(
|
||||
and(
|
||||
inArray(experiments.studyId, studyIds),
|
||||
status ? eq(trials.status, status) : undefined,
|
||||
).filter(Boolean),
|
||||
);
|
||||
|
||||
const totalCount = totalCountResult[0]?.count ?? 0;
|
||||
|
||||
// Transform data to include counts
|
||||
const transformedTrials = filteredTrials.map((trial) => ({
|
||||
...trial,
|
||||
_count: {
|
||||
events: trial.events.length,
|
||||
mediaCaptures: trial.mediaCaptures.length,
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
trials: transformedTrials,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: totalCount,
|
||||
pages: Math.ceil(totalCount / limit),
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -414,4 +414,69 @@ export const usersRouter = createTRPCRouter({
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
getWizards: protectedProcedure.query(async ({ ctx }) => {
|
||||
const userId = ctx.session.user.id;
|
||||
|
||||
// Get all studies user is a member of
|
||||
const userStudies = await ctx.db.query.studyMembers.findMany({
|
||||
where: eq(studyMembers.userId, userId),
|
||||
columns: {
|
||||
studyId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const studyIds = userStudies.map((membership) => membership.studyId);
|
||||
|
||||
if (studyIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get all users who are members of the same studies and have wizard/researcher roles
|
||||
const studyMembersWithUsers = await ctx.db.query.studyMembers.findMany({
|
||||
where: inArray(studyMembers.studyId, studyIds),
|
||||
with: {
|
||||
user: {
|
||||
with: {
|
||||
systemRoles: true,
|
||||
},
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Filter for users with wizard or researcher roles and deduplicate
|
||||
const wizardUsers = new Map();
|
||||
|
||||
studyMembersWithUsers.forEach((member) => {
|
||||
const user = member.user;
|
||||
const hasWizardRole = user.systemRoles.some(
|
||||
(role) =>
|
||||
role.role === "wizard" ||
|
||||
role.role === "researcher" ||
|
||||
role.role === "administrator",
|
||||
);
|
||||
|
||||
if (hasWizardRole && !wizardUsers.has(user.id)) {
|
||||
wizardUsers.set(user.id, {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role:
|
||||
user.systemRoles.find(
|
||||
(role) =>
|
||||
role.role === "wizard" ||
|
||||
role.role === "researcher" ||
|
||||
role.role === "administrator",
|
||||
)?.role || "wizard",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(wizardUsers.values());
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user