Add lessons module, rate cycles, EC2 deploy scripts, and help content
- Lessons module: lesson types, instructors, schedule slots, enrollments, sessions (list + week grid view), lesson plans, grading scales, templates - Rate cycles: replace monthly_rate with billing_interval + billing_unit on enrollments; add weekly/monthly/quarterly rate presets to lesson types and schedule slots with auto-fill on enrollment form - Member detail page: tabbed layout for details, identity documents, enrollments - Sessions week view: custom 7-column grid replacing react-big-calendar - Music store seed: instructors, lesson types, slots, enrollments, sessions, grading scale, lesson plan template - Scrollbar styling: themed to match sidebar/app palette - deploy/: EC2 setup and redeploy scripts, nginx config, systemd service - Help: add Lessons category (overview, types, instructors, slots, enrollments, sessions, plans/grading); collapsible sidebar with independent scroll; remove POS/accounting references from docs
This commit is contained in:
@@ -0,0 +1,450 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute, useNavigate, Link } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
enrollmentDetailOptions, enrollmentMutations, enrollmentKeys,
|
||||
sessionListOptions,
|
||||
lessonPlanListOptions, lessonPlanMutations, lessonPlanKeys,
|
||||
lessonPlanTemplateListOptions, lessonPlanTemplateMutations,
|
||||
instructorDetailOptions,
|
||||
scheduleSlotListOptions,
|
||||
lessonTypeListOptions,
|
||||
} from '@/api/lessons'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
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 { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { ArrowLeft, RefreshCw } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { LessonSession, LessonPlan, LessonPlanTemplate } from '@/types/lesson'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/enrollments/$enrollmentId')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
tab: (search.tab as string) || 'details',
|
||||
}),
|
||||
component: EnrollmentDetailPage,
|
||||
})
|
||||
|
||||
const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||
|
||||
function formatTime(t: string) {
|
||||
const [h, m] = t.split(':').map(Number)
|
||||
const ampm = h >= 12 ? 'PM' : 'AM'
|
||||
const hour = h % 12 || 12
|
||||
return `${hour}:${String(m).padStart(2, '0')} ${ampm}`
|
||||
}
|
||||
|
||||
function statusBadge(status: string) {
|
||||
const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
|
||||
active: 'default', paused: 'secondary', cancelled: 'destructive', completed: 'outline',
|
||||
}
|
||||
return <Badge variant={variants[status] ?? 'outline'}>{status}</Badge>
|
||||
}
|
||||
|
||||
function sessionStatusBadge(status: string) {
|
||||
const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
|
||||
scheduled: 'outline', attended: 'default', missed: 'destructive', makeup: 'secondary', cancelled: 'secondary',
|
||||
}
|
||||
return <Badge variant={variants[status] ?? 'outline'}>{status}</Badge>
|
||||
}
|
||||
|
||||
const sessionColumns: Column<LessonSession>[] = [
|
||||
{ key: 'scheduled_date', header: 'Date', sortable: true, render: (s) => <>{new Date(s.scheduledDate + 'T00:00:00').toLocaleDateString()}</> },
|
||||
{ key: 'scheduled_time', header: 'Time', render: (s) => <>{formatTime(s.scheduledTime)}</> },
|
||||
{ key: 'status', header: 'Status', sortable: true, render: (s) => sessionStatusBadge(s.status) },
|
||||
{
|
||||
key: 'substitute', header: 'Sub', render: (s) => s.substituteInstructorId
|
||||
? <Badge variant="outline" className="text-xs">Sub</Badge>
|
||||
: null,
|
||||
},
|
||||
{ key: 'notes', header: 'Notes', render: (s) => s.notesCompletedAt ? <Badge variant="outline" className="text-xs">Notes</Badge> : null },
|
||||
]
|
||||
|
||||
const TABS = [
|
||||
{ key: 'details', label: 'Details' },
|
||||
{ key: 'sessions', label: 'Sessions' },
|
||||
{ key: 'plan', label: 'Lesson Plan' },
|
||||
]
|
||||
|
||||
function EnrollmentDetailPage() {
|
||||
const { enrollmentId } = Route.useParams()
|
||||
const search = Route.useSearch()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const canEdit = hasPermission('lessons.edit')
|
||||
const tab = search.tab
|
||||
|
||||
function setTab(t: string) {
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId }, search: { tab: t } as any })
|
||||
}
|
||||
|
||||
const { data: enrollment, isLoading } = useQuery(enrollmentDetailOptions(enrollmentId))
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => enrollmentMutations.update(enrollmentId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: enrollmentKeys.detail(enrollmentId) })
|
||||
toast.success('Enrollment updated')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: (status: string) => enrollmentMutations.updateStatus(enrollmentId, status),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: enrollmentKeys.detail(enrollmentId) })
|
||||
toast.success('Status updated')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const generateMutation = useMutation({
|
||||
mutationFn: () => enrollmentMutations.generateSessions(enrollmentId, 4),
|
||||
onSuccess: (res) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['lesson-sessions'] })
|
||||
toast.success(`Generated ${res.generated} sessions`)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const { data: instructorData } = useQuery({
|
||||
...instructorDetailOptions(enrollment?.instructorId ?? ''),
|
||||
enabled: !!enrollment?.instructorId,
|
||||
})
|
||||
|
||||
const { data: slotsData } = useQuery(scheduleSlotListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
const { data: lessonTypesData } = useQuery(lessonTypeListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
|
||||
if (isLoading) return <div className="text-sm text-muted-foreground">Loading...</div>
|
||||
if (!enrollment) return <div className="text-sm text-destructive">Enrollment not found.</div>
|
||||
|
||||
const slot = slotsData?.data?.find((s) => s.id === enrollment.scheduleSlotId)
|
||||
const lessonType = lessonTypesData?.data?.find((lt) => lt.id === slot?.lessonTypeId)
|
||||
const slotLabel = slot ? `${DAYS[slot.dayOfWeek]} ${formatTime(slot.startTime)}${slot.room ? ` — ${slot.room}` : ''}` : '—'
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />Back
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
<h1 className="text-2xl font-bold">Enrollment</h1>
|
||||
<p className="text-sm text-muted-foreground">{instructorData?.displayName ?? enrollment.instructorId} · {slotLabel}</p>
|
||||
</div>
|
||||
{statusBadge(enrollment.status)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 border-b">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
onClick={() => setTab(t.key)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
|
||||
tab === t.key ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'details' && (
|
||||
<DetailsTab
|
||||
enrollment={enrollment}
|
||||
slotLabel={slotLabel}
|
||||
lessonTypeName={lessonType?.name}
|
||||
instructorName={instructorData?.displayName}
|
||||
canEdit={canEdit}
|
||||
onSave={updateMutation.mutate}
|
||||
saving={updateMutation.isPending}
|
||||
onStatusChange={statusMutation.mutate}
|
||||
statusChanging={statusMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
{tab === 'sessions' && (
|
||||
<SessionsTab
|
||||
enrollmentId={enrollmentId}
|
||||
onGenerate={generateMutation.mutate}
|
||||
generating={generateMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
{tab === 'plan' && <LessonPlanTab enrollmentId={enrollmentId} memberId={enrollment.memberId} canEdit={canEdit} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Details Tab ──────────────────────────────────────────────────────────────
|
||||
|
||||
const BILLING_UNITS = [
|
||||
{ value: 'day', label: 'Day(s)' },
|
||||
{ value: 'week', label: 'Week(s)' },
|
||||
{ value: 'month', label: 'Month(s)' },
|
||||
{ value: 'quarter', label: 'Quarter(s)' },
|
||||
{ value: 'year', label: 'Year(s)' },
|
||||
]
|
||||
|
||||
function DetailsTab({
|
||||
enrollment, slotLabel, lessonTypeName, instructorName,
|
||||
canEdit, onSave, saving, onStatusChange, statusChanging,
|
||||
}: any) {
|
||||
const [rate, setRate] = useState(enrollment.rate ?? '')
|
||||
const [billingInterval, setBillingInterval] = useState(String(enrollment.billingInterval ?? 1))
|
||||
const [billingUnit, setBillingUnit] = useState(enrollment.billingUnit ?? 'month')
|
||||
const [notes, setNotes] = useState(enrollment.notes ?? '')
|
||||
const [endDate, setEndDate] = useState(enrollment.endDate ?? '')
|
||||
|
||||
const NEXT_STATUSES: Record<string, string[]> = {
|
||||
active: ['paused', 'cancelled', 'completed'],
|
||||
paused: ['active', 'cancelled'],
|
||||
cancelled: [],
|
||||
completed: [],
|
||||
}
|
||||
|
||||
const nextStatuses = NEXT_STATUSES[enrollment.status] ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-lg">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<p className="text-muted-foreground">Instructor</p>
|
||||
<p className="font-medium">{instructorName ?? enrollment.instructorId}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Slot</p>
|
||||
<p className="font-medium">{slotLabel}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Lesson Type</p>
|
||||
<p className="font-medium">{lessonTypeName ?? '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Start Date</p>
|
||||
<p className="font-medium">{new Date(enrollment.startDate + 'T00:00:00').toLocaleDateString()}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Billing Cycle</p>
|
||||
<p className="font-medium">{enrollment.billingInterval ? `${enrollment.billingInterval} ${enrollment.billingUnit}(s)` : '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Rate</p>
|
||||
<p className="font-medium">{enrollment.rate ? `$${enrollment.rate}` : '—'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">Makeup Credits</p>
|
||||
<p className="font-medium">{enrollment.makeupCredits}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label className="block mb-2">Billing Cycle</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={billingInterval}
|
||||
onChange={(e) => setBillingInterval(e.target.value)}
|
||||
className="w-20"
|
||||
/>
|
||||
<Select value={billingUnit} onValueChange={setBillingUnit}>
|
||||
<SelectTrigger className="w-36"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILLING_UNITS.map((u) => (
|
||||
<SelectItem key={u.value} value={u.value}>{u.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Rate</Label>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground">$</span>
|
||||
<Input type="number" step="0.01" value={rate} onChange={(e) => setRate(e.target.value)} placeholder="Optional" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>End Date</Label>
|
||||
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Notes</Label>
|
||||
<Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} />
|
||||
</div>
|
||||
<Button onClick={() => onSave({
|
||||
rate: rate || undefined,
|
||||
billingInterval: billingInterval ? Number(billingInterval) : undefined,
|
||||
billingUnit: billingUnit || undefined,
|
||||
notes: notes || undefined,
|
||||
endDate: endDate || undefined,
|
||||
})} disabled={saving}>
|
||||
{saving ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{nextStatuses.length > 0 && (
|
||||
<div className="border-t pt-4 space-y-2">
|
||||
<p className="text-sm font-medium">Change Status</p>
|
||||
<div className="flex gap-2">
|
||||
{nextStatuses.map((s) => (
|
||||
<Button key={s} variant={s === 'cancelled' ? 'destructive' : 'outline'} size="sm" onClick={() => onStatusChange(s)} disabled={statusChanging}>
|
||||
{s.charAt(0).toUpperCase() + s.slice(1)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Sessions Tab ─────────────────────────────────────────────────────────────
|
||||
|
||||
function SessionsTab({ enrollmentId, onGenerate, generating }: { enrollmentId: string; onGenerate: () => void; generating: boolean }) {
|
||||
const navigate = useNavigate()
|
||||
const { data, isLoading } = useQuery(sessionListOptions({ enrollmentId, page: 1, limit: 100, sort: 'scheduled_date', order: 'asc' }))
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button variant="outline" size="sm" onClick={onGenerate} disabled={generating}>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${generating ? 'animate-spin' : ''}`} />
|
||||
Generate Sessions
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={sessionColumns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={1}
|
||||
totalPages={1}
|
||||
total={data?.data?.length ?? 0}
|
||||
onPageChange={() => {}}
|
||||
onSort={() => {}}
|
||||
onRowClick={(s) => navigate({ to: '/lessons/sessions/$sessionId', params: { sessionId: s.id }, search: {} as any })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Lesson Plan Tab ──────────────────────────────────────────────────────────
|
||||
|
||||
function LessonPlanTab({ enrollmentId, memberId, canEdit }: { enrollmentId: string; memberId: string; canEdit: boolean }) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const [templatePickerOpen, setTemplatePickerOpen] = useState(false)
|
||||
const [selectedTemplateId, setSelectedTemplateId] = useState('')
|
||||
const [customTitle, setCustomTitle] = useState('')
|
||||
|
||||
const { data: plansData } = useQuery(lessonPlanListOptions({ enrollmentId, isActive: true }))
|
||||
const activePlan: LessonPlan | undefined = plansData?.data?.[0]
|
||||
|
||||
const { data: templatesData } = useQuery(lessonPlanTemplateListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
|
||||
const createPlanMutation = useMutation({
|
||||
mutationFn: () => lessonPlanMutations.create({ memberId, enrollmentId, title: `Lesson Plan — ${new Date().toLocaleDateString()}` }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: lessonPlanKeys.all })
|
||||
toast.success('Lesson plan created')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const instantiateMutation = useMutation({
|
||||
mutationFn: () => lessonPlanTemplateMutations.createPlan(selectedTemplateId, {
|
||||
memberId,
|
||||
enrollmentId,
|
||||
title: customTitle || undefined,
|
||||
}),
|
||||
onSuccess: (plan) => {
|
||||
queryClient.invalidateQueries({ queryKey: lessonPlanKeys.all })
|
||||
toast.success('Plan created from template')
|
||||
setTemplatePickerOpen(false)
|
||||
navigate({ to: '/lessons/plans/$planId', params: { planId: plan.id }, search: {} as any })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const templates: LessonPlanTemplate[] = templatesData?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{activePlan ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium">{activePlan.title}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{Math.round(activePlan.progress)}% complete
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => navigate({ to: '/lessons/plans/$planId', params: { planId: activePlan.id }, search: {} as any })}>
|
||||
View Plan
|
||||
</Button>
|
||||
</div>
|
||||
<div className="w-full bg-muted rounded-full h-2">
|
||||
<div className="bg-primary h-2 rounded-full transition-all" style={{ width: `${activePlan.progress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground py-4">No active lesson plan.</div>
|
||||
)}
|
||||
|
||||
{canEdit && (
|
||||
<div className="flex gap-2 pt-2 border-t">
|
||||
<Button variant="outline" size="sm" onClick={() => createPlanMutation.mutate()} disabled={createPlanMutation.isPending}>
|
||||
{createPlanMutation.isPending ? 'Creating...' : 'New Blank Plan'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setTemplatePickerOpen(true)}>
|
||||
Use Template
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={templatePickerOpen} onOpenChange={setTemplatePickerOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>Create Plan from Template</DialogTitle></DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Template *</Label>
|
||||
<Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
|
||||
<SelectTrigger><SelectValue placeholder="Choose a template..." /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{templates.map((t) => (
|
||||
<SelectItem key={t.id} value={t.id}>
|
||||
{t.name}{t.instrument ? ` — ${t.instrument}` : ''}{t.skillLevel !== 'all_levels' ? ` (${t.skillLevel})` : ''}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Custom Title</Label>
|
||||
<Input value={customTitle} onChange={(e) => setCustomTitle(e.target.value)} placeholder="Leave blank to use template name" />
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => instantiateMutation.mutate()}
|
||||
disabled={!selectedTemplateId || instantiateMutation.isPending}
|
||||
className="w-full"
|
||||
>
|
||||
{instantiateMutation.isPending ? 'Creating...' : 'Create Plan'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState } from 'react'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { enrollmentListOptions } from '@/api/lessons'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Plus, Search } from 'lucide-react'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { Enrollment } from '@/types/lesson'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/enrollments/')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'desc',
|
||||
status: (search.status as string) || undefined,
|
||||
instructorId: (search.instructorId as string) || undefined,
|
||||
}),
|
||||
component: EnrollmentsListPage,
|
||||
})
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
active: 'Active',
|
||||
paused: 'Paused',
|
||||
cancelled: 'Cancelled',
|
||||
completed: 'Completed',
|
||||
}
|
||||
|
||||
function statusBadge(status: string) {
|
||||
const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
|
||||
active: 'default',
|
||||
paused: 'secondary',
|
||||
cancelled: 'destructive',
|
||||
completed: 'outline',
|
||||
}
|
||||
return <Badge variant={variants[status] ?? 'outline'}>{STATUS_LABELS[status] ?? status}</Badge>
|
||||
}
|
||||
|
||||
const columns: Column<Enrollment & { memberName?: string; instructorName?: string; slotInfo?: string; lessonTypeName?: string }>[] = [
|
||||
{ key: 'member_name', header: 'Member', sortable: true, render: (e) => <span className="font-medium">{(e as any).memberName ?? e.memberId}</span> },
|
||||
{ key: 'instructor_name', header: 'Instructor', render: (e) => <>{(e as any).instructorName ?? e.instructorId}</> },
|
||||
{ key: 'slot_info', header: 'Day / Time', render: (e) => <>{(e as any).slotInfo ?? '—'}</> },
|
||||
{ key: 'status', header: 'Status', sortable: true, render: (e) => statusBadge(e.status) },
|
||||
{ key: 'start_date', header: 'Start', sortable: true, render: (e) => <>{new Date(e.startDate + 'T00:00:00').toLocaleDateString()}</> },
|
||||
{ key: 'rate', header: 'Rate', render: (e) => <>{e.rate ? `$${e.rate}${e.billingInterval ? ` / ${e.billingInterval} ${e.billingUnit}` : ''}` : <span className="text-muted-foreground">—</span>}</> },
|
||||
]
|
||||
|
||||
function EnrollmentsListPage() {
|
||||
const navigate = useNavigate()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const search = Route.useSearch()
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
const [statusFilter, setStatusFilter] = useState(search.status ?? '')
|
||||
|
||||
const queryParams: Record<string, unknown> = { ...params }
|
||||
if (statusFilter) queryParams.status = statusFilter
|
||||
|
||||
const { data, isLoading } = useQuery(enrollmentListOptions(queryParams))
|
||||
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
function handleStatusChange(v: string) {
|
||||
const s = v === 'all' ? '' : v
|
||||
setStatusFilter(s)
|
||||
navigate({ to: '/lessons/enrollments', search: { ...search, status: s || undefined, page: 1 } as any })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Enrollments</h1>
|
||||
{hasPermission('lessons.edit') && (
|
||||
<Button onClick={() => navigate({ to: '/lessons/enrollments/new', search: {} as any })}>
|
||||
<Plus className="mr-2 h-4 w-4" />New Enrollment
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search enrollments..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9 w-64"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<Select value={statusFilter || 'all'} onValueChange={handleStatusChange}>
|
||||
<SelectTrigger className="w-40">
|
||||
<SelectValue placeholder="All Statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Statuses</SelectItem>
|
||||
<SelectItem value="active">Active</SelectItem>
|
||||
<SelectItem value="paused">Paused</SelectItem>
|
||||
<SelectItem value="cancelled">Cancelled</SelectItem>
|
||||
<SelectItem value="completed">Completed</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination.totalPages ?? 1}
|
||||
total={data?.pagination.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
onRowClick={(e) => navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: e.id }, search: {} as any })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||
import { globalMemberListOptions } from '@/api/members'
|
||||
import { scheduleSlotListOptions, enrollmentMutations, instructorListOptions, lessonTypeListOptions } from '@/api/lessons'
|
||||
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, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ArrowLeft, Search, X } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { MemberWithAccount } from '@/api/members'
|
||||
import type { ScheduleSlot, LessonType, Instructor } from '@/types/lesson'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/lessons/enrollments/new')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
memberId: (search.memberId as string) || undefined,
|
||||
accountId: (search.accountId as string) || undefined,
|
||||
}),
|
||||
component: NewEnrollmentPage,
|
||||
})
|
||||
|
||||
const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||
|
||||
const BILLING_UNITS = [
|
||||
{ value: 'day', label: 'Day(s)' },
|
||||
{ value: 'week', label: 'Week(s)' },
|
||||
{ value: 'month', label: 'Month(s)' },
|
||||
{ value: 'quarter', label: 'Quarter(s)' },
|
||||
{ value: 'year', label: 'Year(s)' },
|
||||
] as const
|
||||
|
||||
function formatSlotLabel(slot: ScheduleSlot, instructors: Instructor[], lessonTypes: LessonType[]) {
|
||||
const instructor = instructors.find((i) => i.id === slot.instructorId)
|
||||
const lessonType = lessonTypes.find((lt) => lt.id === slot.lessonTypeId)
|
||||
const [h, m] = slot.startTime.split(':').map(Number)
|
||||
const ampm = h >= 12 ? 'PM' : 'AM'
|
||||
const hour = h % 12 || 12
|
||||
const time = `${hour}:${String(m).padStart(2, '0')} ${ampm}`
|
||||
const day = DAYS[slot.dayOfWeek]
|
||||
return `${day} ${time} — ${lessonType?.name ?? 'Unknown'} (${instructor?.displayName ?? 'Unknown'})`
|
||||
}
|
||||
|
||||
/** Returns the preset rate for a given cycle from slot (falling back to lesson type) */
|
||||
function getPresetRate(
|
||||
billingInterval: string,
|
||||
billingUnit: string,
|
||||
slot: ScheduleSlot | undefined,
|
||||
lessonType: LessonType | undefined,
|
||||
): string {
|
||||
if (!slot) return ''
|
||||
const isPreset = billingInterval === '1'
|
||||
if (!isPreset) return ''
|
||||
if (billingUnit === 'week') return slot.rateWeekly ?? lessonType?.rateWeekly ?? ''
|
||||
if (billingUnit === 'month') return slot.rateMonthly ?? lessonType?.rateMonthly ?? ''
|
||||
if (billingUnit === 'quarter') return slot.rateQuarterly ?? lessonType?.rateQuarterly ?? ''
|
||||
return ''
|
||||
}
|
||||
|
||||
function NewEnrollmentPage() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [memberSearch, setMemberSearch] = useState('')
|
||||
const [showMemberDropdown, setShowMemberDropdown] = useState(false)
|
||||
const [selectedMember, setSelectedMember] = useState<MemberWithAccount | null>(null)
|
||||
|
||||
const [selectedSlotId, setSelectedSlotId] = useState('')
|
||||
const [startDate, setStartDate] = useState('')
|
||||
const [billingInterval, setBillingInterval] = useState('1')
|
||||
const [billingUnit, setBillingUnit] = useState('month')
|
||||
const [rate, setRate] = useState('')
|
||||
const [rateManual, setRateManual] = useState(false)
|
||||
const [notes, setNotes] = useState('')
|
||||
|
||||
const { data: membersData } = useQuery(
|
||||
globalMemberListOptions({ page: 1, limit: 20, q: memberSearch || undefined, order: 'asc', sort: 'first_name' }),
|
||||
)
|
||||
|
||||
const { data: slotsData } = useQuery(scheduleSlotListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
const { data: instructorsData } = useQuery(instructorListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
const { data: lessonTypesData } = useQuery(lessonTypeListOptions({ page: 1, limit: 100, order: 'asc' }))
|
||||
|
||||
const slots = slotsData?.data?.filter((s) => s.isActive) ?? []
|
||||
const instructors = instructorsData?.data ?? []
|
||||
const lessonTypes = lessonTypesData?.data ?? []
|
||||
|
||||
const selectedSlot = slots.find((s) => s.id === selectedSlotId)
|
||||
const selectedLessonType = lessonTypes.find((lt) => lt.id === selectedSlot?.lessonTypeId)
|
||||
|
||||
// Auto-fill rate from slot/lesson-type presets when slot or cycle changes, unless user has manually edited
|
||||
useEffect(() => {
|
||||
if (rateManual) return
|
||||
const preset = getPresetRate(billingInterval, billingUnit, selectedSlot, selectedLessonType)
|
||||
setRate(preset ? String(preset) : '')
|
||||
}, [selectedSlotId, billingInterval, billingUnit, selectedSlot, selectedLessonType, rateManual])
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (data: Record<string, unknown>) => {
|
||||
const enrollment = await enrollmentMutations.create(data)
|
||||
try {
|
||||
await enrollmentMutations.generateSessions(enrollment.id, 4)
|
||||
} catch {
|
||||
// non-fatal — sessions can be generated later
|
||||
}
|
||||
return enrollment
|
||||
},
|
||||
onSuccess: (enrollment) => {
|
||||
toast.success('Enrollment created')
|
||||
navigate({ to: '/lessons/enrollments/$enrollmentId', params: { enrollmentId: enrollment.id }, search: {} as any })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function selectMember(member: MemberWithAccount) {
|
||||
setSelectedMember(member)
|
||||
setShowMemberDropdown(false)
|
||||
setMemberSearch('')
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!selectedMember || !selectedSlotId || !startDate) return
|
||||
|
||||
mutation.mutate({
|
||||
memberId: selectedMember.id,
|
||||
accountId: selectedMember.accountId,
|
||||
scheduleSlotId: selectedSlotId,
|
||||
instructorId: selectedSlot?.instructorId,
|
||||
startDate,
|
||||
rate: rate || undefined,
|
||||
billingInterval: billingInterval ? Number(billingInterval) : undefined,
|
||||
billingUnit: billingUnit || undefined,
|
||||
notes: notes || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const members = membersData?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">New Enrollment</h1>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Student */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-lg">Student</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
{!selectedMember ? (
|
||||
<div className="relative">
|
||||
<Label>Search Member</Label>
|
||||
<div className="relative mt-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Type name to search..."
|
||||
value={memberSearch}
|
||||
onChange={(e) => { setMemberSearch(e.target.value); setShowMemberDropdown(true) }}
|
||||
onFocus={() => setShowMemberDropdown(true)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
{showMemberDropdown && memberSearch.length > 0 && (
|
||||
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-60 overflow-auto">
|
||||
{members.length === 0 ? (
|
||||
<div className="p-3 text-sm text-muted-foreground">No members found</div>
|
||||
) : (
|
||||
members.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
type="button"
|
||||
className="w-full text-left px-3 py-2 text-sm hover:bg-accent"
|
||||
onClick={() => selectMember(m)}
|
||||
>
|
||||
<span className="font-medium">{m.firstName} {m.lastName}</span>
|
||||
{m.accountName && <span className="text-muted-foreground ml-2">— {m.accountName}</span>}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between p-3 rounded-md border bg-muted/30">
|
||||
<div>
|
||||
<p className="font-medium">{selectedMember.firstName} {selectedMember.lastName}</p>
|
||||
{selectedMember.accountName && (
|
||||
<p className="text-sm text-muted-foreground">{selectedMember.accountName}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setSelectedMember(null)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Schedule Slot */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-lg">Schedule Slot</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Label>Select Slot *</Label>
|
||||
<Select value={selectedSlotId} onValueChange={(v) => { setSelectedSlotId(v); setRateManual(false) }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Choose a time slot..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{slots.map((slot) => (
|
||||
<SelectItem key={slot.id} value={slot.id}>
|
||||
{formatSlotLabel(slot, instructors, lessonTypes)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Terms */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle className="text-lg">Terms</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="startDate">Start Date *</Label>
|
||||
<Input id="startDate" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} required className="max-w-xs" />
|
||||
</div>
|
||||
<div>
|
||||
<Label className="block mb-2">Billing Cycle</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={billingInterval}
|
||||
onChange={(e) => { setBillingInterval(e.target.value); setRateManual(false) }}
|
||||
className="w-20"
|
||||
/>
|
||||
<Select value={billingUnit} onValueChange={(v) => { setBillingUnit(v); setRateManual(false) }}>
|
||||
<SelectTrigger className="w-36">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BILLING_UNITS.map((u) => (
|
||||
<SelectItem key={u.value} value={u.value}>{u.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="rate">Rate</Label>
|
||||
<div className="flex items-center gap-2 max-w-xs">
|
||||
<span className="text-muted-foreground">$</span>
|
||||
<Input
|
||||
id="rate"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={rate}
|
||||
onChange={(e) => { setRate(e.target.value); setRateManual(true) }}
|
||||
placeholder="Auto-filled from slot"
|
||||
/>
|
||||
</div>
|
||||
{!rateManual && rate && (
|
||||
<p className="text-xs text-muted-foreground">Auto-filled from slot rates</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Notes</Label>
|
||||
<Textarea id="notes" value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} placeholder="Internal notes..." />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit" disabled={mutation.isPending || !selectedMember || !selectedSlotId || !startDate} size="lg">
|
||||
{mutation.isPending ? 'Creating...' : 'Create Enrollment'}
|
||||
</Button>
|
||||
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/lessons/enrollments', search: {} as any })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user