From 8ba936baaee42a580879b87bf44b52581b861414 Mon Sep 17 00:00:00 2001 From: n3p-tun3 Date: Mon, 2 Nov 2026 14:23:47 +0300 Subject: [PATCH] feat(api): connect the student app to the Rezina API ApiDataSource maps the Go API onto the existing DataSource, so the screens are unchanged. Build with NEXT_PUBLIC_LMS_API=https://api.rezina.yaltopia.com to use it; without it the demo keeps its own data. Verified against the live API (public, no sign-in): - catalog and course outlines: courses, chapters, lessons, lesson notes, covers - FREE lessons (and every lesson of a FREE course) play for anyone; a free course offers "Start lesson 1" instead of a disabled buy button Built from the spec, not yet tested with a real account: - sign-in: phone code (login or register) and email + password, token refresh, sign-out - profile, progress summary (owned courses, completed lessons), lesson video URLs - video heartbeat, notifications (list, read/unread), issue reports, profile updates Not on the API yet, so left on hold: per-course prices and purchases (buying shows the "not connected" message), translations, categories, teacher, durations, prerequisites, chapter quizzes, Google/Apple sign-in. Screens now hide what a course doesn't have instead of showing it empty: category pill, teacher line and creator row, "0 min" durations, an empty card footer. Lessons with a Vimeo link play that video; the sample clip and "mark as watched" stay for lessons without one. Mapping checks (packages/data/src/api.check.ts) run in `pnpm test` against saved live responses. --- apps/demo/app/page.tsx | 7 +- package.json | 2 +- packages/data/package.json | 6 +- packages/data/src/api.check.ts | 73 +++++ packages/data/src/api.ts | 356 +++++++++++++++++++++ packages/data/src/fixtures-catalog.json | 1 + packages/data/src/fixtures-outline-12.json | 1 + packages/data/src/index.ts | 12 + packages/features/src/store.tsx | 6 +- packages/features/src/student.tsx | 105 ++++-- pnpm-lock.yaml | 3 + 11 files changed, 535 insertions(+), 37 deletions(-) create mode 100644 packages/data/src/api.check.ts create mode 100644 packages/data/src/api.ts create mode 100644 packages/data/src/fixtures-catalog.json create mode 100644 packages/data/src/fixtures-outline-12.json diff --git a/apps/demo/app/page.tsx b/apps/demo/app/page.tsx index 7bbfd4d..9ba8d72 100644 --- a/apps/demo/app/page.tsx +++ b/apps/demo/app/page.tsx @@ -1,8 +1,11 @@ 'use client'; -import { ClaudeDbDataSource } from '@lms/data'; +import { ApiDataSource, ClaudeDbDataSource } from '@lms/data'; import { Platform } from '@lms/features'; -const makeDs = () => new ClaudeDbDataSource(); +// Build with NEXT_PUBLIC_LMS_API=https://api.rezina.yaltopia.com to run the screens against the real API; +// without it the demo keeps its own data (Claude db, or the in-memory mock on Vercel). +const API = process.env.NEXT_PUBLIC_LMS_API; +const makeDs = () => (API ? new ApiDataSource(API) : new ClaudeDbDataSource()); export default function Page() { return ; diff --git a/package.json b/package.json index 9b5cbfe..3038e48 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "packageManager": "pnpm@9.15.9", "scripts": { "demo:build": "pnpm --filter demo build && node tools/artifact-inline.mjs apps/demo/out dist/demo.html && node tools/artifact-check.mjs dist/demo.html", - "test": "node packages/features/src/domain.check.ts", + "test": "node packages/features/src/domain.check.ts && node packages/data/src/api.check.ts", "typecheck": "pnpm -r exec tsc --noEmit", "i18n:check": "node tools/i18n-check.mjs" }, diff --git a/packages/data/package.json b/packages/data/package.json index 84f1e66..5475d13 100644 --- a/packages/data/package.json +++ b/packages/data/package.json @@ -2,9 +2,11 @@ "name": "@lms/data", "version": "0.0.0", "private": true, + "type": "module", "main": "src/index.ts", "types": "src/index.ts", "devDependencies": { - "@types/react": "^19" + "@types/react": "^19", + "@types/node": "^22" } -} \ No newline at end of file +} diff --git a/packages/data/src/api.check.ts b/packages/data/src/api.check.ts new file mode 100644 index 0000000..08f02e1 --- /dev/null +++ b/packages/data/src/api.check.ts @@ -0,0 +1,73 @@ +// Runnable check for the API → domain mapping: `pnpm test`. The fixtures are real responses from +// https://api.rezina.yaltopia.com (2026-11-02): GET /catalog/courses and GET /catalog/courses/12. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { absolute, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts'; + +const BASE = 'https://api.rezina.yaltopia.com'; +const fixture = (f: string) => JSON.parse(readFileSync(new URL(f, import.meta.url), 'utf8')).data; + +// ids and urls +assert.equal(ids.course(12), 'c12'); +assert.equal(ids.num('ch19'), 19); +assert.equal(ids.num('l38'), 38); +assert.equal(slugify('Everyday English', 12), 'everyday-english-12'); +assert.equal(slugify('የሜካፕ መሠረታዊ', 5), 'የሜካፕ-መሠረታዊ-5', 'Ge’ez titles keep their letters'); +assert.equal(slugify('!!!', 7), '7'); +assert.equal(absolute(BASE, '/static/demo/course-cover.svg'), `${BASE}/static/demo/course-cover.svg`); +assert.equal(absolute(BASE + '/', 'static/x.png'), `${BASE}/static/x.png`); +assert.equal(absolute(BASE, 'https://cdn.example/x.png'), 'https://cdn.example/x.png'); +assert.equal(absolute(BASE, ''), null); + +// catalog list has what the outline calls need +const catalog = fixture('./fixtures-catalog.json'); +assert.ok(catalog.courses.length > 0); +for (const c of catalog.courses) assert.ok(Number.isInteger(c.id) && typeof c.name === 'string'); + +// outline → Course +const outline: RawOutline = fixture('./fixtures-outline-12.json'); +const c = mapOutline(outline, BASE); +assert.equal(c.id, 'c12'); +assert.equal(c.slug, 'everyday-english-12'); +assert.equal(c.translations.en?.title, 'Everyday English'); +assert.equal(c.status, 'PUBLISHED'); +assert.equal(c.coverAssetId, `${BASE}/static/demo/course-cover.svg`); +assert.deepEqual(c.prices, {}, 'no per-course price on the API'); +assert.equal(c.chapters.length, outline.chapters.length); +assert.equal(c.chapters[0].id, 'ch19'); +assert.equal(c.chapters[0].translations.en?.title, 'Meet and greet'); +assert.equal(c.chapters.flatMap((ch) => ch.lessons).length, outline.lesson_count, 'every lesson in the outline is mapped'); +assert.deepEqual(c.chapters[0].lessons.map((l) => l.sortOrder), [1, 2, 3]); +assert.ok(c.chapters[0].lessons.every((l) => l.isPreview), 'a FREE course plays for anyone'); +const premium = mapOutline({ ...outline, access_tier: 'PREMIUM', chapters: [{ ...outline.chapters[0], lessons: outline.chapters[0].lessons.map((l, i) => ({ ...l, access_tier: i ? 'PREMIUM' : 'FREE' })) }] }, BASE); +assert.deepEqual(premium.chapters[0].lessons.map((l) => l.isPreview), [true, false, false], 'in a PREMIUM course only FREE lessons preview'); + +// issues and notifications +const issue = mapIssue({ id: 4, issue_type: 'video', subject: 'Stops', description: 'd', status: 'in_progress', created_at: 'a', updated_at: 'b' }); +assert.deepEqual([issue.id, issue.type, issue.status], ['4', 'VIDEO', 'IN_PROGRESS']); +assert.equal(mapIssue({ id: 5, issue_type: 'weird', subject: '', description: '', status: '???', created_at: '', updated_at: '' }).type, 'OTHER'); +const n = mapNotification({ id: 'n1', is_read: true, timestamp: 't', type: 'payment_verified', payload: { headline: 'Paid', message: 'Thanks' }, metadata: { link: '/en/my' } }); +assert.deepEqual([n.type, n.title, n.body, n.readAt, n.link], ['PAYMENT_VERIFIED', 'Paid', 'Thanks', 't', '/en/my']); +assert.equal(mapNotification({ id: 'n2', is_read: false, timestamp: 't', type: 'x' }).readAt, null); + +// profile + progress summary → Student +const now = '2026-11-02T00:00:00.000Z'; +const access = (x: Partial<{ is_accessible: boolean; is_completed: boolean }>) => ({ is_accessible: false, is_completed: false, progress_percent: 0, ...x }); +const s = mapStudent( + { id: 9, first_name: 'Meron', last_name: 'T', phone_number: '+251911000000', preferred_language: 'am', status: 'SUSPENDED', region: 'Adama', country: 'ET' }, + { courses: [ + { id: 12, access: access({ is_accessible: true }), chapters: [{ id: 19, lessons: [{ id: 38, access: access({ is_completed: true }) }, { id: 39, access: access({}) }] }] }, + { id: 13, access: access({ is_accessible: false }), chapters: [] }, + ] }, + [{ id: 1, issue_type: 'payment', subject: 's', description: 'd', status: 'open', created_at: 'a', updated_at: 'b' }], + { l39: { courseId: 'c12', positionSec: 40, maxPositionSec: 60, updatedAt: now } }, + now, +); +assert.deepEqual([s.id, s.name, s.locale, s.status, s.city], ['9', 'Meron T', 'am', 'DEACTIVATED', 'Adama']); +assert.deepEqual(Object.keys(s.enrollments), ['c12'], 'accessible courses count as owned'); +assert.equal(s.progress.l38?.completedAt, now, 'server completion becomes a completed lesson'); +assert.equal(s.progress.l39?.positionSec, 40, 'this session’s resume point survives a refresh'); +assert.equal(s.issues['1']?.type, 'PAYMENT'); +assert.equal(mapStudent({ id: 1, preferred_language: 'fr' }, null, [], {}, now).locale, 'en', 'unknown language falls back to English'); + +console.log('api checks: all passed'); diff --git a/packages/data/src/api.ts b/packages/data/src/api.ts new file mode 100644 index 0000000..64425c0 --- /dev/null +++ b/packages/data/src/api.ts @@ -0,0 +1,356 @@ +// ApiDataSource: the DataSource over the Rezina Go API. Live spec: /swagger/doc.json. +// +// What is wired, and how sure we are of it: +// verified against the live API public catalog + course outline (GET /catalog/courses, /catalog/courses/{id}) +// built from the spec, untested sign-in, profile, progress summary, lesson video URLs, video heartbeat, +// notifications, issue reports (all need a signed-in learner) +// not on the API yet per-course prices/purchases, translations, categories, teacher, lesson +// durations, prerequisites; quizzes are left out until their question shape is known +// Screens never see the API's shapes: everything is mapped onto the domain types in ./index. +import type { + Campaign, Category, Course, DataSource, InboxItem, Issue, IssueStatus, IssueType, LessonProgress, Locale, Settings, + Student, Unsub, UserStatus, Viewer, AuditEntry, +} from './index'; + +// ---------------------------------------------------------------- API shapes (the subset we read) + +type Tier = 'FREE' | 'PREMIUM'; +export interface RawCourse { id: number; name: string; description: string; thumbnail: string; access_tier: Tier; chapter_count: number; lesson_count: number; quiz_count: number } +export interface RawLesson { id: number; title: string; description: string; thumbnail: string; access_tier: Tier; video_url?: string; sort_order?: number } +export interface RawChapter { id: number; name: string; description: string; lessons: RawLesson[]; quizzes: { id: number; title: string; question_count: number }[] } +export interface RawOutline extends RawCourse { chapters: RawChapter[] } +interface RawAccess { is_accessible: boolean; is_completed: boolean; progress_percent: number } +interface RawSummary { courses: { id: number; access: RawAccess; chapters: { id: number; lessons: { id: number; access: RawAccess }[] }[] }[] } +interface RawProfile { id: number; first_name?: string; last_name?: string; nick_name?: string; email?: string; phone_number?: string; country?: string; region?: string; preferred_language?: string; status?: string; created_at?: string; updated_at?: string; last_login?: string } +interface RawIssue { id: number; issue_type: string; subject: string; description: string; status: string; created_at: string; updated_at: string } +interface RawNotification { id: string; is_read: boolean; timestamp: string; type: string; payload?: { headline?: string; message?: string }; metadata?: Record } +interface Tokens { access: string; refresh: string; userId: number } + +// ---------------------------------------------------------------- ids and mapping (pure: covered by api.check.ts) + +/** Domain ids are strings with a kind prefix, so ids from different API tables can't collide in one record. */ +export const ids = { + course: (n: number) => `c${n}`, chapter: (n: number) => `ch${n}`, lesson: (n: number) => `l${n}`, quiz: (n: number) => `q${n}`, + num: (id: string) => Number(id.replace(/^[a-z]+/, '')), +}; + +/** URL slug: readable name plus the API id, so renaming a course never breaks a shared link (the id wins). */ +export function slugify(name: string, id: number): string { + const s = name.toLowerCase().normalize('NFKD').replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, ''); + return s ? `${s}-${id}` : String(id); +} + +export const absolute = (base: string, url: string | null | undefined) => + !url ? null : /^https?:\/\//.test(url) ? url : base.replace(/\/+$/, '') + (url.startsWith('/') ? url : `/${url}`); + +/** Course outline → domain Course. Text is English-only until the API carries translations. */ +export function mapOutline(o: RawOutline, base: string): Course { + return { + id: ids.course(o.id), slug: slugify(o.name, o.id), categoryId: '', instructorName: '', instructionLocale: 'en', + coverAssetId: absolute(base, o.thumbnail), status: 'PUBLISHED', isFeatured: false, isTest: false, sequentialLessons: false, + prerequisiteCourseId: null, publishedAt: null, createdAt: '', updatedAt: '', + translations: { en: { title: o.name, description: o.description } }, + prices: {}, // the API sells subscription plans, not courses: no per-course price yet + chapters: o.chapters.map((ch, i) => ({ + id: ids.chapter(ch.id), sortOrder: i + 1, + translations: { en: { title: ch.name, summary: ch.description || undefined } }, + lessons: ch.lessons.map((l, j) => ({ + id: ids.lesson(l.id), sortOrder: l.sort_order ?? j + 1, + // a FREE lesson (or a lesson in a FREE course) plays for anyone, like our preview lessons + isPreview: o.access_tier === 'FREE' || l.access_tier === 'FREE', isPublished: true, + durationSec: 0, // not on the API yet + videoAssetId: l.video_url || null, videoStatus: 'READY' as const, + translations: { en: { title: l.title, description: l.description || undefined } }, + })), + })), + assessments: [], // chapter quizzes exist on the API; their question shape isn't mapped yet + }; +} + +const ISSUE_TYPES: IssueType[] = ['BUG', 'PAYMENT', 'VIDEO', 'ACCOUNT', 'CONTENT', 'OTHER']; +const ISSUE_STATUSES: IssueStatus[] = ['OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED']; +const USER_STATUSES: UserStatus[] = ['PENDING', 'ACTIVE', 'DEACTIVATED']; +const LOCALES: Locale[] = ['am', 'en', 'om', 'ti']; +const upper = (s: string | undefined) => (s ?? '').toUpperCase().replace(/[\s-]+/g, '_'); + +export function mapIssue(i: RawIssue): Issue { + const type = upper(i.issue_type) as IssueType, status = upper(i.status) as IssueStatus; + return { + id: String(i.id), type: ISSUE_TYPES.includes(type) ? type : 'OTHER', subject: i.subject, description: i.description, + status: ISSUE_STATUSES.includes(status) ? status : 'OPEN', createdAt: i.created_at, updatedAt: i.updated_at, + }; +} + +export function mapNotification(n: RawNotification): InboxItem { + const link = typeof n.metadata?.link === 'string' ? n.metadata.link : null; + return { id: n.id, type: upper(n.type), title: n.payload?.headline ?? '', body: n.payload?.message ?? '', link, readAt: n.is_read ? n.timestamp : null, createdAt: n.timestamp }; +} + +/** Profile + progress summary + issues → the domain Student the screens read. */ +export function mapStudent(p: RawProfile, summary: RawSummary | null, issues: RawIssue[], local: Record, now: string): Student { + const name = [p.first_name, p.last_name].filter(Boolean).join(' ') || p.nick_name || p.phone_number || p.email || ''; + const status = upper(p.status) === 'SUSPENDED' ? 'DEACTIVATED' : (upper(p.status) as UserStatus); + const locale = (p.preferred_language ?? '').slice(0, 2) as Locale; + const enrollments: Student['enrollments'] = {}; + const progress: Record = { ...local }; + for (const c of summary?.courses ?? []) { + const courseId = ids.course(c.id); + if (c.access?.is_accessible) enrollments[courseId] = { courseId, source: 'FREE', createdAt: p.created_at ?? now }; + for (const ch of c.chapters ?? []) for (const l of ch.lessons ?? []) { + if (!l.access?.is_completed) continue; + const id = ids.lesson(l.id); + const seen = progress[id]; + progress[id] = { positionSec: seen?.positionSec ?? 0, maxPositionSec: seen?.maxPositionSec ?? 0, updatedAt: seen?.updatedAt ?? now, courseId, completedAt: seen?.completedAt ?? now }; + } + } + return { + id: String(p.id), name, phone: p.phone_number || undefined, email: p.email || undefined, country: p.country ?? '', city: p.region ?? '', + locale: LOCALES.includes(locale) ? locale : 'en', status: USER_STATUSES.includes(status) ? status : 'ACTIVE', + createdAt: p.created_at ?? now, updatedAt: p.updated_at ?? now, lastActiveAt: p.last_login, + enrollments, orders: {}, progress, issues: Object.fromEntries(issues.map((i) => [String(i.id), mapIssue(i)])), assessments: {}, watchSec: {}, + }; +} + +// ---------------------------------------------------------------- HTTP + +export class ApiError extends Error { + readonly status: number; readonly code: string; + constructor(status: number, message: string) { + super(message); + this.status = status; + this.code = status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error'; + } +} +const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' }); + +const TOKENS_KEY = 'lms.api.tokens'; +const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } }; +const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } }; + +// ---------------------------------------------------------------- data source + +type Contact = { phone?: string; email?: string; password?: string }; + +export class ApiDataSource implements DataSource { + readonly kind = 'api' as const; + private tokens: Tokens | null = readTokens(); + private refreshing: Promise | null = null; + private courseCbs = new Set<(c: Course[]) => void>(); + private studentCbs = new Map<(s: Student | null) => void, string>(); + private inboxCbs = new Set<(i: InboxItem[]) => void>(); + /** Positions reported this session; the API only tells us completion, so resume points live here until reload. */ + private localProgress: Record = {}; + + readonly base: string; + constructor(base: string) { this.base = base; } + + // ---- transport + + private async request(method: string, path: string, body?: unknown, auth = true): Promise { + const send = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, { + method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + let res = await send(); + if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send(); + const json = await res.json().catch(() => null); + // Some endpoints answer `success: false` on a 200, so the HTTP status is what counts. + if (!res.ok) throw new ApiError(res.status, json?.message || json?.error || res.statusText); + return (json && 'data' in json ? json.data : json) as T; + } + + private refresh(): Promise { + if (!this.tokens) return Promise.resolve(false); + this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ access_token: this.tokens.access, refresh_token: this.tokens.refresh }), + }).then(async (r) => { + const j = await r.json().catch(() => null); + if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; } + this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id }); + return true; + }, () => false).finally(() => { this.refreshing = null; }); + return this.refreshing; + } + + private setTokens(t: Tokens | null) { this.tokens = t; writeTokens(t); } + + // ---- auth (the screens reach this through `ds.auth` when it exists; the demo has none) + + /** + * Phone: existing learners get a login code (resend-otp → customer-login with otp_code); new ones get a register + * code (sendRegisterCode → verify-otp). Email: password login; an unknown email registers and confirms by code. + * The exact endpoint pairing is our reading of the spec and still needs confirming with the backend. + */ + readonly auth = { + signedIn: () => !!this.tokens, + /** 'code' when the learner must enter a one-time code next; 'done' when they're signed in already. */ + start: async (c: Contact): Promise<'code' | 'done'> => { + const who = c.phone ? { phone_number: c.phone } : { email: c.email }; + const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false); + const known = c.phone ? exists.phone_number_exist : exists.email_exist; + if (c.email && known) { await this.login({ email: c.email, password: c.password }); return 'done'; } + if (c.phone && known) { await this.request('POST', '/user/resend-otp', who, false); return 'code'; } + if (c.phone) await this.request('POST', '/user/sendRegisterCode', who, false); + else await this.request('POST', '/user/register', { email: c.email, password: c.password }, false); + return 'code'; + }, + verify: async (c: Contact, code: string): Promise => { + const who = c.phone ? { phone_number: c.phone } : { email: c.email }; + const exists = await this.request<{ email_exist: boolean; phone_number_exist: boolean }>('POST', '/user/checkPhoneEmailExist', who, false); + if (c.phone && exists.phone_number_exist) { await this.login({ phone_number: c.phone, otp_code: code }); return; } + const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/user/verify-otp', { ...who, otp: code }, false); + this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); + this.refreshAll(); + }, + signOut: async () => { + const t = this.tokens; + this.setTokens(null); + if (t) await this.request('POST', '/auth/logout', { refresh_token: t.refresh }, false).catch(() => { /* already gone server-side */ }); + this.localProgress = {}; + this.refreshAll(); + }, + }; + + private async login(body: Record) { + const t = await this.request<{ access_token: string; refresh_token: string; user_id: number }>('POST', '/auth/customer-login', body, false); + this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id }); + this.refreshAll(); + } + + // ---- reads + + async viewer(): Promise { + const none: Viewer = { id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false }; + if (!this.tokens) return none; + try { + const p = await this.request('GET', '/user/user-profile'); + return { id: String(p.id), name: [p.first_name, p.last_name].filter(Boolean).join(' '), avatarUrl: '', isOwner: false, canEdit: true }; + } catch { return none; } + } + async names() { return {}; } + + private async loadCourses(): Promise { + const page = await this.request<{ courses: RawCourse[]; total_count: number }>('GET', '/catalog/courses?limit=100', undefined, false); + const outlines = await Promise.all(page.courses.map((c) => this.request('GET', `/catalog/courses/${c.id}`, undefined, false).catch(() => null))); + const courses = outlines.filter((o): o is RawOutline => !!o).map((o) => mapOutline(o, this.base)); + if (this.tokens) await Promise.all(courses.flatMap((c) => c.chapters.map(async (ch) => { + // Signed in: lesson video URLs (and sort order) only come from the authenticated lesson list. + const r = await this.request<{ lessons: RawLesson[] }>('GET', `/chapters/${ids.num(ch.id)}/lessons?limit=200`).catch(() => null); + for (const l of r?.lessons ?? []) { + const m = ch.lessons.find((x) => x.id === ids.lesson(l.id)); + if (m) { m.videoAssetId = l.video_url || m.videoAssetId; if (l.sort_order != null) m.sortOrder = l.sort_order; } + } + }))); + return courses; + } + + private async loadStudent(): Promise { + if (!this.tokens) return null; + const [p, summary, issues] = await Promise.all([ + this.request('GET', '/user/user-profile'), + this.request('GET', '/progress-summary').catch(() => null), + this.request<{ issues: RawIssue[] }>('GET', '/issues/me?limit=100').catch(() => ({ issues: [] })), + ]); + return mapStudent(p, summary, issues.issues ?? [], this.localProgress, new Date().toISOString()); + } + + private async loadInbox(): Promise { + if (!this.tokens) return []; + const r = await this.request<{ notifications: RawNotification[] }>('GET', '/notifications?limit=100'); + return (r.notifications ?? []).map(mapNotification); + } + + /** Re-runs every watcher, e.g. after sign-in, sign-out or a write the server changes state for. */ + refreshAll() { + if (this.courseCbs.size) this.loadCourses().then((c) => this.courseCbs.forEach((cb) => cb(c)), (e) => console.warn('courses', e)); + this.refreshStudent(); + if (this.inboxCbs.size) this.loadInbox().then((i) => this.inboxCbs.forEach((cb) => cb(i)), () => this.inboxCbs.forEach((cb) => cb([]))); + } + private refreshStudent() { + if (!this.studentCbs.size) return; + this.loadStudent().then((s) => this.studentCbs.forEach((_, cb) => cb(s)), (e) => { console.warn('student', e); this.studentCbs.forEach((_, cb) => cb(null)); }); + } + + watchCourses(cb: (c: Course[]) => void): Unsub { + this.courseCbs.add(cb); + this.loadCourses().then((c) => { if (this.courseCbs.has(cb)) cb(c); }, (e) => { console.warn('courses', e); if (this.courseCbs.has(cb)) cb([]); }); + return () => { this.courseCbs.delete(cb); }; + } + watchStudent(id: string, cb: (s: Student | null) => void): Unsub { + this.studentCbs.set(cb, id); + this.loadStudent().then((s) => { if (this.studentCbs.has(cb)) cb(s); }, () => { if (this.studentCbs.has(cb)) cb(null); }); + return () => { this.studentCbs.delete(cb); }; + } + watchInbox(_studentId: string, cb: (i: InboxItem[]) => void): Unsub { + this.inboxCbs.add(cb); + this.loadInbox().then((i) => { if (this.inboxCbs.has(cb)) cb(i); }, () => { if (this.inboxCbs.has(cb)) cb([]); }); + return () => { this.inboxCbs.delete(cb); }; + } + // Not on the API: categories, app settings (the screens fall back to their defaults) and the admin collections. + watchCategories(cb: (c: Category[]) => void): Unsub { cb([]); return () => {}; } + watchSettings(cb: (s: Settings | null) => void): Unsub { cb(null); return () => {}; } + watchStudents(cb: (s: Student[]) => void): Unsub { cb([]); return () => {}; } + watchCampaigns(cb: (c: Campaign[]) => void): Unsub { cb([]); return () => {}; } + watchAudit(cb: (a: AuditEntry[]) => void): Unsub { cb([]); return () => {}; } + + // ---- writes + + /** Profile setup after a first sign-in. */ + async saveStudent(s: Student) { + const [first_name, ...rest] = s.name.trim().split(/\s+/); + await this.request('PUT', '/user', { first_name, last_name: rest.join(' '), country: s.country, region: s.city, preferred_language: s.locale }); + this.refreshStudent(); + } + + /** + * The screens write partial student records; each key maps to the endpoint that owns it. + * Keys the API has no home for (watch time, notification prefs, last active) stay local. + */ + async patchStudent(_id: string, patch: Record) { + const jobs: Promise[] = []; + if (patch.orders) throw notConnected('Buying a course'); + const progress = patch.progress as Record | undefined; + for (const [lessonId, p] of Object.entries(progress ?? {})) { + this.localProgress[lessonId] = { ...this.localProgress[lessonId], ...p }; + jobs.push(this.request('POST', '/videos/engagement/heartbeat', { + content_id: ids.num(lessonId), content_kind: 'lms_lesson', position_sec: Math.floor(p.positionSec), + // durations aren't on the API, so the furthest point reached stands in for the length + duration_sec: Math.max(1, Math.floor(p.maxPositionSec ?? p.positionSec)), ended: !!p.completedAt, + })); + } + for (const i of Object.values((patch.issues ?? {}) as Record>)) { + if (!i.subject) continue; // status changes are the support team's, not the learner's + jobs.push(this.request('POST', '/issues', { subject: i.subject, description: i.description ?? '', issue_type: (i.type ?? 'OTHER').toLowerCase() })); + } + const profile: Record = {}; + if (typeof patch.locale === 'string') profile.preferred_language = patch.locale; + if (typeof patch.name === 'string') { const [f, ...r] = patch.name.trim().split(/\s+/); profile.first_name = f; profile.last_name = r.join(' '); } + if (typeof patch.country === 'string') profile.country = patch.country; + if (typeof patch.city === 'string') profile.region = patch.city; + if (Object.keys(profile).length) jobs.push(this.request('PUT', '/user', profile)); + await Promise.all(jobs); + this.refreshStudent(); + } + + async patchInbox(_studentId: string, id: string, patch: Partial) { + if (patch.readAt !== undefined) await this.request('PATCH', `/notifications/${id}/${patch.readAt ? 'read' : 'unread'}`); + if (this.inboxCbs.size) this.loadInbox().then((i) => this.inboxCbs.forEach((cb) => cb(i)), () => {}); + } + /** The server writes its own notifications (payment, issue updates); the client never adds to a learner's inbox. */ + async addInbox() {} + + async saveCourse() { throw notConnected('Course editing'); } + async deleteCourse() { throw notConnected('Course editing'); } + async saveCategory() { throw notConnected('Categories'); } + async deleteCategory() { throw notConnected('Categories'); } + async saveSettings() { throw notConnected('Settings'); } + async saveCampaign() { throw notConnected('Campaigns'); } + async addAudit() {} + + async uploads() { return null; } + assetUrl(id: string) { return absolute(this.base, id) ?? ''; } + async download() { return false; } + async feedback() { return false; } + async feedbackAvailable() { return false; } +} diff --git a/packages/data/src/fixtures-catalog.json b/packages/data/src/fixtures-catalog.json new file mode 100644 index 0000000..9d8ba67 --- /dev/null +++ b/packages/data/src/fixtures-catalog.json @@ -0,0 +1 @@ +{"message":"Course highlights retrieved","data":{"courses":[{"id":2,"name":"Intermediate","description":"Default program for the intermediate level.","thumbnail":"","access_tier":"PREMIUM","chapter_count":2,"lesson_count":0,"quiz_count":0},{"id":1,"name":"Beginner","description":"Default program for the beginner level.","thumbnail":"","access_tier":"PREMIUM","chapter_count":2,"lesson_count":0,"quiz_count":0},{"id":3,"name":"Advanced","description":"Default program for the advanced level.","thumbnail":"","access_tier":"PREMIUM","chapter_count":2,"lesson_count":0,"quiz_count":0},{"id":12,"name":"Everyday English","description":"Build confidence with introductions, daily conversations, and practical vocabulary.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE","chapter_count":2,"lesson_count":6,"quiz_count":2},{"id":13,"name":"Workplace Communication","description":"Communicate clearly in meetings, write effective messages, and present your ideas.","thumbnail":"/static/demo/course-cover.svg","access_tier":"PREMIUM","chapter_count":2,"lesson_count":6,"quiz_count":2},{"id":14,"name":"Digital Skills Essentials","description":"Learn practical habits for working online, organizing information, and collaborating safely.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE","chapter_count":2,"lesson_count":6,"quiz_count":2}],"total_count":6,"limit":50,"offset":0},"success":true,"status_code":200,"metadata":null} \ No newline at end of file diff --git a/packages/data/src/fixtures-outline-12.json b/packages/data/src/fixtures-outline-12.json new file mode 100644 index 0000000..3887806 --- /dev/null +++ b/packages/data/src/fixtures-outline-12.json @@ -0,0 +1 @@ +{"message":"Course outline retrieved","data":{"id":12,"name":"Everyday English","description":"Build confidence with introductions, daily conversations, and practical vocabulary.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE","chapter_count":2,"lesson_count":6,"quiz_count":2,"chapters":[{"id":19,"name":"Meet and greet","description":"Practice the key ideas through short lessons and a chapter review quiz.","lessons":[{"id":38,"title":"Introduce yourself","description":"In this demo lesson, explore how to introduce yourself. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"},{"id":39,"title":"Ask friendly questions","description":"In this demo lesson, explore how to ask friendly questions. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"},{"id":40,"title":"Start a conversation","description":"In this demo lesson, explore how to start a conversation. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"}],"quizzes":[{"id":14,"title":"Meet and greet review","question_count":3}]},{"id":20,"name":"Everyday situations","description":"Practice the key ideas through short lessons and a chapter review quiz.","lessons":[{"id":41,"title":"Order food and drinks","description":"In this demo lesson, explore how to order food and drinks. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"},{"id":42,"title":"Ask for directions","description":"In this demo lesson, explore how to ask for directions. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"},{"id":43,"title":"Make simple plans","description":"In this demo lesson, explore how to make simple plans. Review the examples, try it yourself, and complete the chapter quiz. The video is sample media for testing playback.","thumbnail":"/static/demo/course-cover.svg","access_tier":"FREE"}],"quizzes":[{"id":15,"title":"Everyday situations review","question_count":3}]}]},"success":true,"status_code":200,"metadata":null} \ No newline at end of file diff --git a/packages/data/src/index.ts b/packages/data/src/index.ts index 615f9ef..202d665 100644 --- a/packages/data/src/index.ts +++ b/packages/data/src/index.ts @@ -109,9 +109,19 @@ export interface Viewer { id: string | null; name: string; avatarUrl: string; is export type Unsub = () => void; +/** Real sign-in, present only on data sources backed by an account system (the API); the demo simulates it. */ +export interface AuthApi { + signedIn(): boolean; + /** Starts sign-in or sign-up for a phone, or an email with password: 'code' means a one-time code was sent. */ + start(c: { phone?: string; email?: string; password?: string }): Promise<'code' | 'done'>; + verify(c: { phone?: string; email?: string; password?: string }, code: string): Promise; + signOut(): Promise; +} + /** Everything a screen may ask of the backend. */ export interface DataSource { readonly kind: 'claude-db' | 'api'; + readonly auth?: AuthApi; viewer(): Promise; /** Display names for stored user ids (never store names). */ names(ids: string[]): Promise>; @@ -227,3 +237,5 @@ export class ClaudeDbDataSource implements DataSource { } export const newId = (prefix = '') => prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 8); + +export { ApiDataSource, ApiError } from './api'; diff --git a/packages/features/src/store.tsx b/packages/features/src/store.tsx index e389a46..6a18e85 100644 --- a/packages/features/src/store.tsx +++ b/packages/features/src/store.tsx @@ -33,6 +33,8 @@ interface Ctx { /** Serialized writes: the db wants one write at a time per document. */ write(fn: () => Promise, okMsg?: string): Promise; signIn(): void; signOut(): void; + /** Re-reads who is signed in, after a real (API) sign-in. */ + reloadViewer(): Promise; notify(studentId: string, item: Omit): Promise; msg(loc: Locale, key: string, vars?: Record): string; } @@ -140,7 +142,9 @@ export function AppProvider({ ds, children }: { ds: DataSource; children: ReactN me: me && !me.deletedAt && !signedOut ? me : null, account: me, meLoaded, signedIn: !!me && !me.deletedAt && !signedOut, inbox, locale, setLocale, route, nav, toast, write, signIn: () => { store.set('signedOut', null); setSignedOut(false); }, - signOut: () => { store.set('signedOut', '1'); setSignedOut(true); }, + // With a real account system, signing out also ends the server session and forgets the user. + signOut: () => { store.set('signedOut', '1'); setSignedOut(true); if (ds.auth) ds.auth.signOut().then(() => ds.viewer()).then(setViewer, () => {}); }, + reloadViewer: async () => { setViewer(await ds.viewer()); }, notify, msg, }; diff --git a/packages/features/src/student.tsx b/packages/features/src/student.tsx index bab0400..a69b071 100644 --- a/packages/features/src/student.tsx +++ b/packages/features/src/student.tsx @@ -33,6 +33,9 @@ function useCatalog() { const ct = (c: Course, l: Locale) => tr(c.translations, l) ?? { title: c.slug, description: '' }; const lessonTitle = (l: Lesson, loc: Locale) => tr(l.translations, loc)?.title ?? ''; +/** Length as text, or '' when unknown (the API carries no durations yet), so no screen shows "0 min". */ +const dur = (sec: number) => (sec > 0 ? formatDuration(sec) : ''); +const withDur = (sec: number, before = ' · ') => (sec > 0 ? `${before}${formatDuration(sec)}` : ''); const lessonNumber = (c: Course, id: string) => publishedLessons(c).findIndex((l) => l.id === id) + 1; // C1: one quiet "lessons · length" line, with "new course" / student count as a tag on the photo. @@ -48,17 +51,17 @@ function CourseCard({ c, tall }: { c: Course; tall?: boolean }) { const tag = c.enrolledCount ? t('course.enrolled', { n: c.enrolledCount }) : t('course.newCourse'); return ( ); @@ -505,7 +508,7 @@ function ContinueCard({ c }: { c: Course }) { {r &&

{finished ? t('course.completed') : t('player.upNext')} {r.index + 1}. {lessonTitle(r.lesson, locale)} - {formatDuration(r.lesson.durationSec)} · {t('my.lessonsDone', { done: p.done, total: p.total })} + {[dur(r.lesson.durationSec), t('my.lessonsDone', { done: p.done, total: p.total })].filter(Boolean).join(' · ')}

} {r && } @@ -595,7 +598,7 @@ function CoursePage({ slug }: { slug?: string }) { const cat = categories.find((k) => k.id === c.categoryId); const chapters = [...c.chapters].sort((a, b) => a.sortOrder - b.sortOrder); // The hero only offers the free preview; once owned, the progress card below carries the one "continue" button (P2). - const play = !mine && preview ? `/${locale}/learn/${c.slug}/${preview.id}` : null; + const play = !mine && preview && !(c.prices.ETB == null && lessons.every((l) => l.isPreview)) ? `/${locale}/learn/${c.slug}/${preview.id}` : null; const playLabel = mine && r ? (done ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })) : t('course.watchPreview'); const share = () => { navigator.clipboard?.writeText(location.href).then(() => toast(t('course.linkCopied')), () => { /* clipboard blocked */ }); }; const teaches = courses.filter((x) => x.instructorName === c.instructorName && isStudentVisible(x, me)).length; @@ -611,10 +614,11 @@ function CoursePage({ slug }: { slug?: string }) { const includes: [string, ReactNode][] = [ ['globe', LOCALE_NAMES[c.instructionLocale]], ['video', t('course.lessons', { n: lessons.length })], - ['clock', formatDuration(courseDuration(c))], + ...(courseDuration(c) ? [['clock', formatDuration(courseDuration(c))] as [string, ReactNode]] : []), ...(previews ? [['play', t('course.previewLessons', { n: previews })] as [string, ReactNode]] : []), ...(c.assessments?.length ? [['quiz', t('assess.title')] as [string, ReactNode]] : []), ]; + const free = !mine && c.prices.ETB == null && lessons.length > 0 && lessons.every((l) => l.isPreview); const showBar = !!(mine ? r : c.prices.ETB != null && c.status === 'PUBLISHED'); const barHidden = showBar && ctaInView; return ( @@ -635,15 +639,15 @@ function CoursePage({ slug }: { slug?: string }) {

{text.title}

{lessons.length}{t('course.lessonsLabel')} - {formatDuration(courseDuration(c))} + {courseDuration(c) > 0 && {formatDuration(courseDuration(c))}} {mine && {done ? t('course.completed') : t('course.owned')}}
{(text.subtitle || text.description) &&

{text.subtitle || text.description}

} {play && } -
+ {c.instructorName &&
{initials(c.instructorName)} {t('course.createdBy')}{c.instructorName}{t('course.teaches', { n: teaches })} -
+
}