All files / web/src/lib/curriculum trends.ts

94.21% Statements 163/173
97.77% Branches 44/45
83.33% Functions 5/6
94.21% Lines 163/173

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 1741x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 12x 12x 12x 1x 1x 1x 1x 25x 25x 25x 25x 1x 1x 1x 1x                     1x 1x 1x 1x 18x 18x 18x 8x 8x 8x 8x 1x 1x 1x 1x 11x 11x 10x 10x 10x 10x 10x 4x 4x 4x 10x 10x 11x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 11x 3x 3x 3x 3x 3x 11x 7x 7x 7x 7x 3x 11x 8x 8x 5x 5x 8x 3x 3x 8x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 11x 11x 11x 11x 12x 12x 12x 12x 12x 12x 12x 7x 7x 12x 12x 12x 12x 12x 12x 18x 18x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x  
/**
 * Session Trend Calculations
 *
 * Calculates historical trends from session data for display in the session summary.
 */
 
import type { SessionPlan, SlotResult } from '@/db/schema/session-plans'
 
export interface SessionTrends {
  /** Comparison to last session */
  accuracyDelta: number | null // e.g., 0.05 for +5%
  previousAccuracy: number | null
 
  /** This week stats */
  weekSessions: number
  weekProblems: number
  weekAccuracy: number
 
  /** All-time stats */
  totalSessions: number
  totalProblems: number
  avgAccuracy: number
 
  /** Streak (consecutive days with practice) */
  currentStreak: number
}
 
/**
 * Calculate accuracy from a session's results
 */
function getSessionAccuracy(session: SessionPlan): number {
  const results = (session.results ?? []) as SlotResult[]
  if (results.length === 0) return 0
  const correct = results.filter((r) => r.isCorrect).length
  return correct / results.length
}
 
/**
 * Get problem count from a session
 */
function getSessionProblemCount(session: SessionPlan): number {
  const results = (session.results ?? []) as SlotResult[]
  return results.length
}
 
/**
 * Check if a session was completed on a specific date
 */
function isSessionOnDate(session: SessionPlan, date: Date): boolean {
  const completedAt = session.completedAt as unknown as number
  if (!completedAt) return false
  const sessionDate = new Date(completedAt)
  return (
    sessionDate.getFullYear() === date.getFullYear() &&
    sessionDate.getMonth() === date.getMonth() &&
    sessionDate.getDate() === date.getDate()
  )
}
 
/**
 * Check if a session was completed within the last N days
 */
function isSessionWithinDays(session: SessionPlan, days: number): boolean {
  const completedAt = session.completedAt as unknown as number
  if (!completedAt) return false
  const now = Date.now()
  const cutoff = now - days * 24 * 60 * 60 * 1000
  return completedAt >= cutoff
}
 
/**
 * Calculate current practice streak (consecutive days)
 */
function calculateStreak(allSessions: SessionPlan[]): number {
  if (allSessions.length === 0) return 0
 
  // Sort by completion date descending
  const sorted = [...allSessions]
    .filter((s) => s.completedAt)
    .sort((a, b) => {
      const aTime = a.completedAt as unknown as number
      const bTime = b.completedAt as unknown as number
      return bTime - aTime
    })
 
  if (sorted.length === 0) return 0
 
  let streak = 0
  const today = new Date()
  today.setHours(0, 0, 0, 0)
 
  // Check if there's a session today or yesterday (streak must be active)
  const mostRecent = new Date(sorted[0].completedAt as unknown as number)
  mostRecent.setHours(0, 0, 0, 0)
 
  const daysDiff = Math.floor((today.getTime() - mostRecent.getTime()) / (24 * 60 * 60 * 1000))
  if (daysDiff > 1) return 0 // Streak broken
 
  // Count consecutive days backwards
  const checkDate = new Date(mostRecent)
  const sessionDates = new Set<string>()
 
  for (const session of sorted) {
    const date = new Date(session.completedAt as unknown as number)
    date.setHours(0, 0, 0, 0)
    sessionDates.add(date.toISOString().split('T')[0])
  }
 
  while (true) {
    const dateStr = checkDate.toISOString().split('T')[0]
    if (sessionDates.has(dateStr)) {
      streak++
      checkDate.setDate(checkDate.getDate() - 1)
    } else {
      break
    }
  }
 
  return streak
}
 
/**
 * Calculate session trends from historical data
 *
 * @param current - The current session being viewed
 * @param previous - The session before current (for delta calculation)
 * @param allSessions - All completed sessions (ordered newest first)
 */
export function calculateSessionTrends(
  current: SessionPlan | null,
  previous: SessionPlan | null,
  allSessions: SessionPlan[]
): SessionTrends | null {
  if (!current) return null
 
  const currentAccuracy = getSessionAccuracy(current)
 
  // Accuracy delta from previous session
  const previousAccuracy = previous ? getSessionAccuracy(previous) : null
  const accuracyDelta = previousAccuracy !== null ? currentAccuracy - previousAccuracy : null
 
  // This week stats (last 7 days)
  const weekSessions = allSessions.filter((s) => isSessionWithinDays(s, 7))
  const weekProblems = weekSessions.reduce((sum, s) => sum + getSessionProblemCount(s), 0)
  const weekCorrect = weekSessions.reduce((sum, s) => {
    const results = (s.results ?? []) as SlotResult[]
    return sum + results.filter((r) => r.isCorrect).length
  }, 0)
  const weekAccuracy = weekProblems > 0 ? weekCorrect / weekProblems : 0
 
  // All-time stats
  const totalProblems = allSessions.reduce((sum, s) => sum + getSessionProblemCount(s), 0)
  const totalCorrect = allSessions.reduce((sum, s) => {
    const results = (s.results ?? []) as SlotResult[]
    return sum + results.filter((r) => r.isCorrect).length
  }, 0)
  const avgAccuracy = totalProblems > 0 ? totalCorrect / totalProblems : 0
 
  // Streak
  const currentStreak = calculateStreak(allSessions)
 
  return {
    accuracyDelta,
    previousAccuracy,
    weekSessions: weekSessions.length,
    weekProblems,
    weekAccuracy,
    totalSessions: allSessions.length,
    totalProblems,
    avgAccuracy,
    currentStreak,
  }
}