feat(admin-v2): Major SDK/Compliance overhaul and new modules
SDK modules added/enhanced: - compliance-hub, compliance-scope, consent-management, notfallplan - audit-report, workflow, source-policy, dsms - advisory-board documentation section - TOM dashboard components, TOM generator SDM mapping - DSFA: mitigation library, risk catalog, threshold analysis, source attribution - VVT: baseline catalog, profiling engine, types - Loeschfristen: baseline catalog, compliance engine, export, profiling, types - Compliance scope: engine, profiling, golden tests, types Existing SDK pages updated: - dsfa/[id], tom, vvt, loeschfristen, advisory-board — expanded functionality - SDKSidebar, StepHeader — new navigation items and layout - SDK layout, context, types — expanded type system Other admin-v2 changes: - AI agents page, RAG pipeline DSFA integration - GridOverlay component updates - Companion feature (development + education) - Compliance advisor SOUL definition Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
3
admin-v2/hooks/companion/index.ts
Normal file
3
admin-v2/hooks/companion/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { useCompanionData } from './useCompanionData'
|
||||
export { useLessonSession } from './useLessonSession'
|
||||
export { useKeyboardShortcuts, useKeyboardShortcutHints } from './useKeyboardShortcuts'
|
||||
156
admin-v2/hooks/companion/useCompanionData.ts
Normal file
156
admin-v2/hooks/companion/useCompanionData.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { CompanionData } from '@/lib/companion/types'
|
||||
import { createDefaultPhases } from '@/lib/companion/constants'
|
||||
|
||||
interface UseCompanionDataOptions {
|
||||
pollingInterval?: number // ms, default 30000
|
||||
autoRefresh?: boolean
|
||||
}
|
||||
|
||||
interface UseCompanionDataReturn {
|
||||
data: CompanionData | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
refresh: () => Promise<void>
|
||||
lastUpdated: Date | null
|
||||
}
|
||||
|
||||
// Mock data for development - will be replaced with actual API calls
|
||||
function getMockData(): CompanionData {
|
||||
return {
|
||||
context: {
|
||||
currentPhase: 'erarbeitung',
|
||||
phaseDisplayName: 'Erarbeitung',
|
||||
},
|
||||
stats: {
|
||||
classesCount: 4,
|
||||
studentsCount: 96,
|
||||
learningUnitsCreated: 23,
|
||||
gradesEntered: 156,
|
||||
},
|
||||
phases: createDefaultPhases(),
|
||||
progress: {
|
||||
percentage: 65,
|
||||
completed: 13,
|
||||
total: 20,
|
||||
},
|
||||
suggestions: [
|
||||
{
|
||||
id: '1',
|
||||
title: 'Klausuren korrigieren',
|
||||
description: 'Deutsch LK - 12 unkorrigierte Arbeiten warten',
|
||||
priority: 'urgent',
|
||||
icon: 'ClipboardCheck',
|
||||
actionTarget: '/ai/klausur-korrektur',
|
||||
estimatedTime: 120,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
title: 'Elternsprechtag vorbereiten',
|
||||
description: 'Notenuebersicht fuer 8b erstellen',
|
||||
priority: 'high',
|
||||
icon: 'Users',
|
||||
actionTarget: '/education/grades',
|
||||
estimatedTime: 30,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
title: 'Material hochladen',
|
||||
description: 'Arbeitsblatt fuer naechste Woche bereitstellen',
|
||||
priority: 'medium',
|
||||
icon: 'FileText',
|
||||
actionTarget: '/development/content',
|
||||
estimatedTime: 15,
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
title: 'Lernstandserhebung planen',
|
||||
description: 'Mathe 7a - Naechster Test in 2 Wochen',
|
||||
priority: 'low',
|
||||
icon: 'Calendar',
|
||||
actionTarget: '/education/planning',
|
||||
estimatedTime: 45,
|
||||
},
|
||||
],
|
||||
upcomingEvents: [
|
||||
{
|
||||
id: 'e1',
|
||||
title: 'Mathe-Test 9b',
|
||||
date: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
type: 'exam',
|
||||
inDays: 2,
|
||||
},
|
||||
{
|
||||
id: 'e2',
|
||||
title: 'Elternsprechtag',
|
||||
date: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
type: 'parent_meeting',
|
||||
inDays: 5,
|
||||
},
|
||||
{
|
||||
id: 'e3',
|
||||
title: 'Notenschluss Q1',
|
||||
date: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
type: 'deadline',
|
||||
inDays: 14,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function useCompanionData(options: UseCompanionDataOptions = {}): UseCompanionDataReturn {
|
||||
const { pollingInterval = 30000, autoRefresh = true } = options
|
||||
|
||||
const [data, setData] = useState<CompanionData | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
// TODO: Replace with actual API call
|
||||
// const response = await fetch('/api/admin/companion')
|
||||
// if (!response.ok) throw new Error('Failed to fetch companion data')
|
||||
// const result = await response.json()
|
||||
// setData(result.data)
|
||||
|
||||
// For now, use mock data with a small delay to simulate network
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
setData(getMockData())
|
||||
setLastUpdated(new Date())
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true)
|
||||
await fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
// Initial fetch
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
// Polling
|
||||
useEffect(() => {
|
||||
if (!autoRefresh || pollingInterval <= 0) return
|
||||
|
||||
const interval = setInterval(fetchData, pollingInterval)
|
||||
return () => clearInterval(interval)
|
||||
}, [autoRefresh, pollingInterval, fetchData])
|
||||
|
||||
return {
|
||||
data,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
lastUpdated,
|
||||
}
|
||||
}
|
||||
113
admin-v2/hooks/companion/useKeyboardShortcuts.ts
Normal file
113
admin-v2/hooks/companion/useKeyboardShortcuts.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useCallback, useRef } from 'react'
|
||||
import { KEYBOARD_SHORTCUTS } from '@/lib/companion/constants'
|
||||
|
||||
interface UseKeyboardShortcutsOptions {
|
||||
onPauseResume?: () => void
|
||||
onExtend?: () => void
|
||||
onNextPhase?: () => void
|
||||
onCloseModal?: () => void
|
||||
onShowHelp?: () => void
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export function useKeyboardShortcuts({
|
||||
onPauseResume,
|
||||
onExtend,
|
||||
onNextPhase,
|
||||
onCloseModal,
|
||||
onShowHelp,
|
||||
enabled = true,
|
||||
}: UseKeyboardShortcutsOptions) {
|
||||
// Track if we're in an input field
|
||||
const isInputFocused = useRef(false)
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (!enabled) return
|
||||
|
||||
// Don't trigger shortcuts when typing in inputs
|
||||
const target = event.target as HTMLElement
|
||||
const isInput =
|
||||
target.tagName === 'INPUT' ||
|
||||
target.tagName === 'TEXTAREA' ||
|
||||
target.tagName === 'SELECT' ||
|
||||
target.isContentEditable
|
||||
|
||||
if (isInput) {
|
||||
isInputFocused.current = true
|
||||
// Only allow Escape in inputs
|
||||
if (event.key !== 'Escape') return
|
||||
} else {
|
||||
isInputFocused.current = false
|
||||
}
|
||||
|
||||
// Handle shortcuts
|
||||
switch (event.key) {
|
||||
case KEYBOARD_SHORTCUTS.PAUSE_RESUME:
|
||||
if (!isInput) {
|
||||
event.preventDefault()
|
||||
onPauseResume?.()
|
||||
}
|
||||
break
|
||||
|
||||
case KEYBOARD_SHORTCUTS.EXTEND_5MIN:
|
||||
case KEYBOARD_SHORTCUTS.EXTEND_5MIN.toUpperCase():
|
||||
if (!isInput) {
|
||||
event.preventDefault()
|
||||
onExtend?.()
|
||||
}
|
||||
break
|
||||
|
||||
case KEYBOARD_SHORTCUTS.NEXT_PHASE:
|
||||
case KEYBOARD_SHORTCUTS.NEXT_PHASE.toUpperCase():
|
||||
if (!isInput) {
|
||||
event.preventDefault()
|
||||
onNextPhase?.()
|
||||
}
|
||||
break
|
||||
|
||||
case KEYBOARD_SHORTCUTS.CLOSE_MODAL:
|
||||
event.preventDefault()
|
||||
onCloseModal?.()
|
||||
break
|
||||
|
||||
case KEYBOARD_SHORTCUTS.SHOW_HELP:
|
||||
if (!isInput) {
|
||||
event.preventDefault()
|
||||
onShowHelp?.()
|
||||
}
|
||||
break
|
||||
}
|
||||
},
|
||||
[enabled, onPauseResume, onExtend, onNextPhase, onCloseModal, onShowHelp]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [enabled, handleKeyDown])
|
||||
|
||||
return {
|
||||
isInputFocused: isInputFocused.current,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to display keyboard shortcut hints
|
||||
*/
|
||||
export function useKeyboardShortcutHints(show: boolean) {
|
||||
const shortcuts = [
|
||||
{ key: 'Leertaste', action: 'Pause/Fortsetzen', code: 'space' },
|
||||
{ key: 'E', action: '+5 Minuten', code: 'e' },
|
||||
{ key: 'N', action: 'Naechste Phase', code: 'n' },
|
||||
{ key: 'Esc', action: 'Modal schliessen', code: 'escape' },
|
||||
]
|
||||
|
||||
if (!show) return null
|
||||
|
||||
return shortcuts
|
||||
}
|
||||
446
admin-v2/hooks/companion/useLessonSession.ts
Normal file
446
admin-v2/hooks/companion/useLessonSession.ts
Normal file
@@ -0,0 +1,446 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { LessonSession, LessonPhase, TimerState, PhaseDurations } from '@/lib/companion/types'
|
||||
import {
|
||||
PHASE_ORDER,
|
||||
PHASE_DISPLAY_NAMES,
|
||||
PHASE_COLORS,
|
||||
DEFAULT_PHASE_DURATIONS,
|
||||
SYSTEM_TEMPLATES,
|
||||
getTimerColorStatus,
|
||||
STORAGE_KEYS,
|
||||
} from '@/lib/companion/constants'
|
||||
|
||||
interface UseLessonSessionOptions {
|
||||
onPhaseComplete?: (phaseIndex: number) => void
|
||||
onLessonComplete?: (session: LessonSession) => void
|
||||
onOvertimeStart?: () => void
|
||||
}
|
||||
|
||||
interface UseLessonSessionReturn {
|
||||
session: LessonSession | null
|
||||
timerState: TimerState | null
|
||||
startLesson: (data: {
|
||||
classId: string
|
||||
className?: string
|
||||
subject: string
|
||||
topic?: string
|
||||
templateId?: string
|
||||
}) => void
|
||||
endLesson: () => void
|
||||
pauseLesson: () => void
|
||||
resumeLesson: () => void
|
||||
extendTime: (minutes: number) => void
|
||||
skipPhase: () => void
|
||||
saveReflection: (rating: number, notes: string, nextSteps: string) => void
|
||||
addHomework: (title: string, dueDate: string) => void
|
||||
removeHomework: (id: string) => void
|
||||
isRunning: boolean
|
||||
isPaused: boolean
|
||||
}
|
||||
|
||||
function createInitialPhases(durations: PhaseDurations): LessonPhase[] {
|
||||
return PHASE_ORDER.map((phaseId) => ({
|
||||
phase: phaseId,
|
||||
duration: durations[phaseId],
|
||||
status: 'planned',
|
||||
actualTime: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
function generateSessionId(): string {
|
||||
return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
|
||||
}
|
||||
|
||||
export function useLessonSession(
|
||||
options: UseLessonSessionOptions = {}
|
||||
): UseLessonSessionReturn {
|
||||
const { onPhaseComplete, onLessonComplete, onOvertimeStart } = options
|
||||
|
||||
const [session, setSession] = useState<LessonSession | null>(null)
|
||||
const [timerState, setTimerState] = useState<TimerState | null>(null)
|
||||
|
||||
const timerRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const lastTickRef = useRef<number>(Date.now())
|
||||
const hasTriggeredOvertimeRef = useRef(false)
|
||||
|
||||
// Calculate timer state from session
|
||||
const calculateTimerState = useCallback((sess: LessonSession): TimerState | null => {
|
||||
if (!sess || sess.status === 'completed') return null
|
||||
|
||||
const currentPhase = sess.phases[sess.currentPhaseIndex]
|
||||
if (!currentPhase) return null
|
||||
|
||||
const phaseDurationSeconds = currentPhase.duration * 60
|
||||
const elapsedInPhase = currentPhase.actualTime
|
||||
const remainingSeconds = phaseDurationSeconds - elapsedInPhase
|
||||
const progress = Math.min(elapsedInPhase / phaseDurationSeconds, 1)
|
||||
const isOvertime = remainingSeconds < 0
|
||||
|
||||
return {
|
||||
isRunning: sess.status === 'in_progress' && !sess.isPaused,
|
||||
isPaused: sess.isPaused,
|
||||
elapsedSeconds: elapsedInPhase,
|
||||
remainingSeconds: Math.max(remainingSeconds, -999),
|
||||
totalSeconds: phaseDurationSeconds,
|
||||
progress,
|
||||
colorStatus: getTimerColorStatus(remainingSeconds, isOvertime),
|
||||
currentPhase,
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Timer tick function
|
||||
const tick = useCallback(() => {
|
||||
if (!session || session.isPaused || session.status !== 'in_progress') return
|
||||
|
||||
const now = Date.now()
|
||||
const delta = Math.floor((now - lastTickRef.current) / 1000)
|
||||
lastTickRef.current = now
|
||||
|
||||
if (delta <= 0) return
|
||||
|
||||
setSession((prev) => {
|
||||
if (!prev) return null
|
||||
|
||||
const updatedPhases = [...prev.phases]
|
||||
const currentPhase = updatedPhases[prev.currentPhaseIndex]
|
||||
if (!currentPhase) return prev
|
||||
|
||||
currentPhase.actualTime += delta
|
||||
|
||||
// Check for overtime
|
||||
const phaseDurationSeconds = currentPhase.duration * 60
|
||||
if (
|
||||
currentPhase.actualTime > phaseDurationSeconds &&
|
||||
!hasTriggeredOvertimeRef.current
|
||||
) {
|
||||
hasTriggeredOvertimeRef.current = true
|
||||
onOvertimeStart?.()
|
||||
}
|
||||
|
||||
// Update total elapsed time
|
||||
const totalElapsed = prev.elapsedTime + delta
|
||||
|
||||
return {
|
||||
...prev,
|
||||
phases: updatedPhases,
|
||||
elapsedTime: totalElapsed,
|
||||
overtimeMinutes: Math.max(
|
||||
0,
|
||||
Math.floor((currentPhase.actualTime - phaseDurationSeconds) / 60)
|
||||
),
|
||||
}
|
||||
})
|
||||
}, [session, onOvertimeStart])
|
||||
|
||||
// Start/stop timer based on session state
|
||||
useEffect(() => {
|
||||
if (session?.status === 'in_progress' && !session.isPaused) {
|
||||
lastTickRef.current = Date.now()
|
||||
timerRef.current = setInterval(tick, 100) // Update every 100ms for smooth animation
|
||||
} else {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current)
|
||||
timerRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current)
|
||||
}
|
||||
}
|
||||
}, [session?.status, session?.isPaused, tick])
|
||||
|
||||
// Update timer state when session changes
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
setTimerState(calculateTimerState(session))
|
||||
} else {
|
||||
setTimerState(null)
|
||||
}
|
||||
}, [session, calculateTimerState])
|
||||
|
||||
// Persist session to localStorage
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
localStorage.setItem(STORAGE_KEYS.CURRENT_SESSION, JSON.stringify(session))
|
||||
}
|
||||
}, [session])
|
||||
|
||||
// Restore session from localStorage on mount
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEYS.CURRENT_SESSION)
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored) as LessonSession
|
||||
// Only restore if session is not completed and not too old (< 24h)
|
||||
const sessionTime = new Date(parsed.startTime).getTime()
|
||||
const isRecent = Date.now() - sessionTime < 24 * 60 * 60 * 1000
|
||||
|
||||
if (parsed.status !== 'completed' && isRecent) {
|
||||
// Pause the restored session
|
||||
setSession({ ...parsed, isPaused: true })
|
||||
}
|
||||
} catch {
|
||||
// Invalid stored session, ignore
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const startLesson = useCallback(
|
||||
(data: {
|
||||
classId: string
|
||||
className?: string
|
||||
subject: string
|
||||
topic?: string
|
||||
templateId?: string
|
||||
}) => {
|
||||
// Find template durations
|
||||
let durations = DEFAULT_PHASE_DURATIONS
|
||||
if (data.templateId) {
|
||||
const template = SYSTEM_TEMPLATES.find((t) => t.templateId === data.templateId)
|
||||
if (template) {
|
||||
durations = template.durations as PhaseDurations
|
||||
}
|
||||
}
|
||||
|
||||
const phases = createInitialPhases(durations)
|
||||
phases[0].status = 'active'
|
||||
phases[0].startedAt = new Date().toISOString()
|
||||
|
||||
const newSession: LessonSession = {
|
||||
sessionId: generateSessionId(),
|
||||
classId: data.classId,
|
||||
className: data.className || data.classId,
|
||||
subject: data.subject,
|
||||
topic: data.topic,
|
||||
startTime: new Date().toISOString(),
|
||||
phases,
|
||||
totalPlannedDuration: Object.values(durations).reduce((a, b) => a + b, 0),
|
||||
currentPhaseIndex: 0,
|
||||
elapsedTime: 0,
|
||||
isPaused: false,
|
||||
pauseDuration: 0,
|
||||
overtimeMinutes: 0,
|
||||
status: 'in_progress',
|
||||
homeworkList: [],
|
||||
materials: [],
|
||||
}
|
||||
|
||||
hasTriggeredOvertimeRef.current = false
|
||||
setSession(newSession)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const endLesson = useCallback(() => {
|
||||
if (!session) return
|
||||
|
||||
const completedSession: LessonSession = {
|
||||
...session,
|
||||
status: 'completed',
|
||||
endTime: new Date().toISOString(),
|
||||
phases: session.phases.map((p, i) => ({
|
||||
...p,
|
||||
status: i <= session.currentPhaseIndex ? 'completed' : 'skipped',
|
||||
completedAt: i <= session.currentPhaseIndex ? new Date().toISOString() : undefined,
|
||||
})),
|
||||
}
|
||||
|
||||
setSession(completedSession)
|
||||
onLessonComplete?.(completedSession)
|
||||
}, [session, onLessonComplete])
|
||||
|
||||
const pauseLesson = useCallback(() => {
|
||||
if (!session || session.isPaused) return
|
||||
|
||||
setSession((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
isPaused: true,
|
||||
pausedAt: new Date().toISOString(),
|
||||
status: 'paused',
|
||||
}
|
||||
: null
|
||||
)
|
||||
}, [session])
|
||||
|
||||
const resumeLesson = useCallback(() => {
|
||||
if (!session || !session.isPaused) return
|
||||
|
||||
const pausedAt = session.pausedAt ? new Date(session.pausedAt).getTime() : Date.now()
|
||||
const pauseDelta = Math.floor((Date.now() - pausedAt) / 1000)
|
||||
|
||||
setSession((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
isPaused: false,
|
||||
pausedAt: undefined,
|
||||
pauseDuration: prev.pauseDuration + pauseDelta,
|
||||
status: 'in_progress',
|
||||
}
|
||||
: null
|
||||
)
|
||||
|
||||
lastTickRef.current = Date.now()
|
||||
}, [session])
|
||||
|
||||
const extendTime = useCallback(
|
||||
(minutes: number) => {
|
||||
if (!session) return
|
||||
|
||||
setSession((prev) => {
|
||||
if (!prev) return null
|
||||
|
||||
const updatedPhases = [...prev.phases]
|
||||
const currentPhase = updatedPhases[prev.currentPhaseIndex]
|
||||
if (!currentPhase) return prev
|
||||
|
||||
currentPhase.duration += minutes
|
||||
|
||||
// Reset overtime trigger if we've added time
|
||||
if (hasTriggeredOvertimeRef.current) {
|
||||
const phaseDurationSeconds = currentPhase.duration * 60
|
||||
if (currentPhase.actualTime < phaseDurationSeconds) {
|
||||
hasTriggeredOvertimeRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...prev,
|
||||
phases: updatedPhases,
|
||||
totalPlannedDuration: prev.totalPlannedDuration + minutes,
|
||||
}
|
||||
})
|
||||
},
|
||||
[session]
|
||||
)
|
||||
|
||||
const skipPhase = useCallback(() => {
|
||||
if (!session) return
|
||||
|
||||
const nextPhaseIndex = session.currentPhaseIndex + 1
|
||||
|
||||
// Check if this was the last phase
|
||||
if (nextPhaseIndex >= session.phases.length) {
|
||||
endLesson()
|
||||
return
|
||||
}
|
||||
|
||||
setSession((prev) => {
|
||||
if (!prev) return null
|
||||
|
||||
const updatedPhases = [...prev.phases]
|
||||
|
||||
// Complete current phase
|
||||
updatedPhases[prev.currentPhaseIndex] = {
|
||||
...updatedPhases[prev.currentPhaseIndex],
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
// Start next phase
|
||||
updatedPhases[nextPhaseIndex] = {
|
||||
...updatedPhases[nextPhaseIndex],
|
||||
status: 'active',
|
||||
startedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
return {
|
||||
...prev,
|
||||
phases: updatedPhases,
|
||||
currentPhaseIndex: nextPhaseIndex,
|
||||
overtimeMinutes: 0,
|
||||
}
|
||||
})
|
||||
|
||||
hasTriggeredOvertimeRef.current = false
|
||||
onPhaseComplete?.(session.currentPhaseIndex)
|
||||
}, [session, endLesson, onPhaseComplete])
|
||||
|
||||
const saveReflection = useCallback(
|
||||
(rating: number, notes: string, nextSteps: string) => {
|
||||
if (!session) return
|
||||
|
||||
setSession((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
reflection: {
|
||||
rating,
|
||||
notes,
|
||||
nextSteps,
|
||||
savedAt: new Date().toISOString(),
|
||||
},
|
||||
}
|
||||
: null
|
||||
)
|
||||
},
|
||||
[session]
|
||||
)
|
||||
|
||||
const addHomework = useCallback(
|
||||
(title: string, dueDate: string) => {
|
||||
if (!session) return
|
||||
|
||||
const newHomework = {
|
||||
id: `hw-${Date.now()}`,
|
||||
title,
|
||||
dueDate,
|
||||
completed: false,
|
||||
}
|
||||
|
||||
setSession((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
homeworkList: [...prev.homeworkList, newHomework],
|
||||
}
|
||||
: null
|
||||
)
|
||||
},
|
||||
[session]
|
||||
)
|
||||
|
||||
const removeHomework = useCallback(
|
||||
(id: string) => {
|
||||
if (!session) return
|
||||
|
||||
setSession((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
homeworkList: prev.homeworkList.filter((hw) => hw.id !== id),
|
||||
}
|
||||
: null
|
||||
)
|
||||
},
|
||||
[session]
|
||||
)
|
||||
|
||||
// Clear session (for starting new)
|
||||
const clearSession = useCallback(() => {
|
||||
setSession(null)
|
||||
localStorage.removeItem(STORAGE_KEYS.CURRENT_SESSION)
|
||||
}, [])
|
||||
|
||||
return {
|
||||
session,
|
||||
timerState,
|
||||
startLesson,
|
||||
endLesson: session?.status === 'completed' ? clearSession : endLesson,
|
||||
pauseLesson,
|
||||
resumeLesson,
|
||||
extendTime,
|
||||
skipPhase,
|
||||
saveReflection,
|
||||
addHomework,
|
||||
removeHomework,
|
||||
isRunning: session?.status === 'in_progress' && !session?.isPaused,
|
||||
isPaused: session?.isPaused ?? false,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user