File size: 5,802 Bytes
65d68f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { TuitionLessonStepId } from "./classSessionData";
import { tuitionLessonSteps } from "./classSessionData";
import type { TuitionSessionData } from "./sessionData";

/**
 * Tuition class session progress.
 *
 * The 11-step guided class (TuitionClassSessionView) held all progress in
 * ephemeral React state, so a refresh lost everything. This persists the
 * resumable parts keyed by the class session, so /tuition restores where the
 * student left off. localStorage is the offline source of truth; the backend
 * (classSessionProgressApi) syncs it across devices.
 */

const VALID_STEP_IDS = new Set(tuitionLessonSteps.map((step) => step.id));

/** Map legacy step ids (e.g. "recap") onto the current continuous flow. */
export function normalizeLessonStepId(stepId: string | undefined | null): TuitionLessonStepId {
  if (stepId === "recap") return "save-revision";
  if (stepId && VALID_STEP_IDS.has(stepId as TuitionLessonStepId)) {
    return stepId as TuitionLessonStepId;
  }
  return tuitionLessonSteps[0].id;
}

export type ClassSessionProgressState = {
  started: boolean;
  activeStepId: TuitionLessonStepId;
  maxUnlockedIndex: number;
  recallAnswer: string;
  recallSubmitted: boolean;
  practiceAnswer: string;
  practiceSubmitted: boolean;
  quizAnswers: Record<string, string>;
  quizSubmitted: boolean;
  revisionSaved: boolean;
  trickSaved: boolean;
  assessmentAttemptId?: string | null;
  lessonProgressId?: string | null;
  /** Steps the student explicitly completed in the class flow (not mastery). */
  completedStepIds?: TuitionLessonStepId[];
  /** Authoritative session id/revision when this is an authenticated class. */
  tuitionSessionId?: string | null;
  tuitionSessionRevision?: number | null;
  writtenAttemptId?: string | null;
  /** Number of authoritative written submissions for this class. */
  writtenAttemptCount?: number;
  /** Adaptive checkpoint loop state (runId keeps replays idempotent). */
  checkpointState?: {
    runId: string;
    questions: Record<
      string,
      {
        phase: "answering" | "hint_retry" | "explained" | "transfer" | "done";
        attempt: number;
        correct: boolean | null;
        transferCorrect: boolean | null;
        errorCategory: string | null;
      }
    >;
  } | null;
};

export type ClassSessionProgress = ClassSessionProgressState & {
  classSessionId: string;
  updatedAt: string;
};

export const CLASS_SESSION_PROGRESS_PREFIX = "docdoe:tuition-class-progress:";

type SessionIdParts = Pick<TuitionSessionData, "board" | "subject" | "chapterId" | "missionId">;

/** Stable id for a class session, used as the persistence key. */
export function classSessionId(session: SessionIdParts): string {
  return [session.board ?? "", session.subject ?? "", session.chapterId ?? "chapter", session.missionId ?? "mission"]
    .map((part) => part.trim())
    .join("|");
}

export function readClassSessionProgress(id: string): ClassSessionProgress | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = window.localStorage.getItem(CLASS_SESSION_PROGRESS_PREFIX + id);
    return raw ? (JSON.parse(raw) as ClassSessionProgress) : null;
  } catch {
    return null;
  }
}

export function writeClassSessionProgress(id: string, state: ClassSessionProgressState): ClassSessionProgress {
  const payload: ClassSessionProgress = { ...state, classSessionId: id, updatedAt: new Date().toISOString() };
  if (typeof window !== "undefined") {
    try {
      window.localStorage.setItem(CLASS_SESSION_PROGRESS_PREFIX + id, JSON.stringify(payload));
    } catch {
      // Storage is a convenience layer; the backend copy remains authoritative.
    }
  }
  return payload;
}

/** Merge a stored snapshot into the default state (used to seed React state). */
export function applyClassSessionProgress(
  defaults: ClassSessionProgressState,
  saved: ClassSessionProgress | null,
): ClassSessionProgressState {
  if (!saved) return defaults;
  const activeStepId = normalizeLessonStepId(saved.activeStepId ?? defaults.activeStepId);
  const maxStepIndex = Math.max(0, tuitionLessonSteps.length - 1);
  const maxUnlockedIndex = Math.max(
    0,
    Math.min(maxStepIndex, saved.maxUnlockedIndex ?? defaults.maxUnlockedIndex),
  );
  // Empty practice answers are never treated as submitted after refresh.
  const practiceAnswer = saved.practiceAnswer ?? defaults.practiceAnswer;
  const practiceSubmitted =
    Boolean(saved.practiceSubmitted ?? defaults.practiceSubmitted) && practiceAnswer.trim().length > 0;

  return {
    started: saved.started ?? defaults.started,
    activeStepId,
    maxUnlockedIndex,
    recallAnswer: saved.recallAnswer ?? defaults.recallAnswer,
    recallSubmitted: saved.recallSubmitted ?? defaults.recallSubmitted,
    practiceAnswer,
    practiceSubmitted,
    quizAnswers: saved.quizAnswers ?? defaults.quizAnswers,
    quizSubmitted: saved.quizSubmitted ?? defaults.quizSubmitted,
    revisionSaved: saved.revisionSaved ?? defaults.revisionSaved,
    trickSaved: saved.trickSaved ?? defaults.trickSaved,
    assessmentAttemptId:
      saved.assessmentAttemptId ?? defaults.assessmentAttemptId ?? null,
    lessonProgressId:
      saved.lessonProgressId ?? defaults.lessonProgressId ?? null,
    completedStepIds:
      saved.completedStepIds ?? defaults.completedStepIds ?? [],
    tuitionSessionId:
      saved.tuitionSessionId ?? defaults.tuitionSessionId ?? null,
    tuitionSessionRevision:
      saved.tuitionSessionRevision ?? defaults.tuitionSessionRevision ?? null,
    writtenAttemptId:
      saved.writtenAttemptId ?? defaults.writtenAttemptId ?? null,
    writtenAttemptCount:
      saved.writtenAttemptCount ?? defaults.writtenAttemptCount ?? 0,
    checkpointState: saved.checkpointState ?? defaults.checkpointState ?? null,
  };
}