Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Trale/miniapp-src/src/analytics/lessonEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* в тестах и на стенде ?alphabet-lab. Сервер сам отбрасывает незнакомые события.
*
* Общий для модулей: lessonFlow.open(модуль, урок) → step(позиция, вид) → done()/skip() → end('lesson_complete'|'lesson_fail')
* или exit() (ушёл посреди урока). Размечены алфавит и «Знакомство».
* или exit() (ушёл посреди урока). Размечены алфавит, «Знакомство», «Числа» и «Мой день».
*/

export type StepKind =
Expand Down
56 changes: 56 additions & 0 deletions src/Trale/miniapp-src/src/analytics/useGameLessonEvents.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { describe, it, expect, afterEach } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import { __setLessonEventSender, flushLessonEvents, type LessonEventDto } from './lessonEvents'
import { useMyDayLesson } from '../myday/MyDayInterlude'
import { useNumbersLesson } from '../numbers/NumbersInterlude'
import type { QuizQuestion } from '../types'

const questions = [{ id: 'q1' }] as unknown as QuizQuestion[]
const result = (correct: number) => ({ kind: 'result' as const, moduleId: 'x', lessonId: 1, correct, total: 4, xpEarned: 0, wrongQuestions: [] })

function record() {
const sent: LessonEventDto[] = []
__setLessonEventSender(events => sent.push(...events))
return () => { flushLessonEvents(); return sent.map(e => `${e.moduleId}/${e.lessonId} ${e.step}:${e.stepKind} ${e.event}${e.value != null ? `=${e.value}` : ''}`) }
}

afterEach(() => __setLessonEventSender(null))

describe('уроки «игра → проверка» пишут журнал, как алфавит', () => {
it('«Мой день»: открыл, доиграл, сдал проверку', () => {
const events = record()
const { result: hook } = renderHook(() => useMyDayLesson('my-day', 3, questions))
act(() => hook.current.sceneDone())
act(() => hook.current.finish(result(4), true, () => {}))
expect(events()).toEqual([
'my-day/3 0:lesson lesson_open',
'my-day/3 1:lesson step_start',
'my-day/3 1:lesson step_done',
'my-day/3 2:check step_start',
'my-day/3 2:check step_done=4',
'my-day/3 2:check lesson_complete=4'
])
})

it('«Числа»: не сдал проверку — lesson_fail', () => {
const events = record()
const { result: hook } = renderHook(() => useNumbersLesson('numbers', 2, questions))
act(() => hook.current.sceneDone())
act(() => hook.current.finish(result(1), false, () => {}))
expect(events().slice(-1)[0]).toBe('numbers/2 2:check lesson_fail=1')
})

it('ушёл посреди игры — lesson_exit на шаге игры', () => {
const events = record()
const { unmount } = renderHook(() => useMyDayLesson('my-day', 5, questions))
unmount()
expect(events().slice(-1)[0]).toBe('my-day/5 1:lesson lesson_exit')
})

it('чужой модуль ничего не пишет', () => {
const events = record()
const { unmount } = renderHook(() => useMyDayLesson('alphabet-progressive', 3, questions))
unmount()
expect(events()).toEqual([])
})
})
24 changes: 24 additions & 0 deletions src/Trale/miniapp-src/src/analytics/useGameLessonEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useEffect } from 'react'
import { lessonFlow } from './lessonEvents'

/**
* Журнал урока вида «игра → проверка» («Числа» 1–10, «Мой день»): открытие, шаг 1 — игра, шаг 2 — проверка
* вопросами урока, «ушёл посреди». Конец урока пишет finish хука модуля (lessonFlow.end).
*/
export function useGameLessonEvents(on: boolean, moduleId: string, lessonId: number, loaded: boolean, played: boolean) {
const stage = !on || !loaded ? null : played ? 'check' : 'game'
useEffect(() => {
if (stage === 'game') { lessonFlow.open(moduleId, lessonId, 'lesson'); lessonFlow.step(moduleId, lessonId, 1, 'lesson') }
else if (stage === 'check') lessonFlow.step(moduleId, lessonId, 2, 'check')
}, [stage, moduleId, lessonId])
useEffect(() => () => { if (on) lessonFlow.exit() }, [on])
}

/** Игра доиграна — шаг закрыт. */
export const gameLessonPlayed = () => lessonFlow.done()

/** Проверка пройдена или нет: засчитанный урок — lesson_complete, иначе lesson_fail. */
export function gameLessonFinished(correct: number, passed: boolean) {
lessonFlow.done(correct)
lessonFlow.end(passed ? 'lesson_complete' : 'lesson_fail', correct)
}
9 changes: 7 additions & 2 deletions src/Trale/miniapp-src/src/myday/MyDayInterlude.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react'
import type { QuizQuestion, Screen } from '../types'
import { MY_DAY_LESSONS, mountMyDay } from './engine'
import { gameLessonFinished, gameLessonPlayed, useGameLessonEvents } from '../analytics/useGameLessonEvents'
import './myday.css'

// Модуль «Мой день»: урок — игра (engine.ts), потом короткая проверка вопросами урока с сервера.
Expand All @@ -18,15 +19,19 @@ export function useMyDayLesson(moduleId: string, lessonId: number, questions: Qu
const on = isMyDayLesson(moduleId, lessonId)
const [played, setPlayed] = useState(false)
const scene = on && questions.length && !played ? { kind: 'game' as const } : null
useGameLessonEvents(on, moduleId, lessonId, questions.length > 0, played)

return {
on,
scene,
/** Игра — первые 80% полоски урока, проверка — остальное. */
progress: (index: number, total: number) => (on ? 0.8 + (index / Math.max(1, total)) * 0.2 : index / Math.max(1, total)),
afterQuestion(_n: number) { /* игра — до проверки */ },
finish(result: Result, _perfect: boolean, navigate: (s: Screen) => void) { navigate(result) },
sceneDone() { setPlayed(true) }
finish(result: Result, perfect: boolean, navigate: (s: Screen) => void) {
if (on) gameLessonFinished(result.correct, perfect)
navigate(result)
},
sceneDone() { if (on) gameLessonPlayed(); setPlayed(true) }
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/Trale/miniapp-src/src/numbers/NumbersInterlude.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react'
import type { QuizQuestion, Screen } from '../types'
import { NUMBER_LEVELS, mountLevel } from './engine'
import { gameLessonFinished, gameLessonPlayed, useGameLessonEvents } from '../analytics/useGameLessonEvents'
import './numbers.css'

// Урок «Чисел» 1..10 — уровень с игрой (engine.ts): объяснятор, игра, итог. Потом короткая проверка вопросами
Expand All @@ -18,15 +19,19 @@ export function useNumbersLesson(moduleId: string, lessonId: number, questions:
const on = isNumbersGameLesson(moduleId, lessonId)
const [played, setPlayed] = useState(false)
const scene = on && questions.length && !played ? { kind: 'level' as const } : null
useGameLessonEvents(on, moduleId, lessonId, questions.length > 0, played)

return {
on,
scene,
/** Игра — первые 80% полоски урока, проверка — остальное. */
progress: (index: number, total: number) => (on ? 0.8 + (index / Math.max(1, total)) * 0.2 : index / Math.max(1, total)),
afterQuestion(_n: number) { /* игра — до проверки */ },
finish(result: Result, _perfect: boolean, navigate: (s: Screen) => void) { navigate(result) },
sceneDone() { setPlayed(true) }
finish(result: Result, perfect: boolean, navigate: (s: Screen) => void) {
if (on) gameLessonFinished(result.correct, perfect)
navigate(result)
},
sceneDone() { if (on) gameLessonPlayed(); setPlayed(true) }
}
}

Expand Down
Loading