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.
This commit is contained in:
parent
67650698bf
commit
8ba936baae
|
|
@ -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 <Platform dataSource={makeDs} />;
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
73
packages/data/src/api.check.ts
Normal file
73
packages/data/src/api.check.ts
Normal file
|
|
@ -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');
|
||||
356
packages/data/src/api.ts
Normal file
356
packages/data/src/api.ts
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
// ApiDataSource: the DataSource over the Rezina Go API. Live spec: <base>/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<string, unknown> }
|
||||
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<string, LessonProgress>, 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<string, LessonProgress> = { ...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<boolean> | 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<string, LessonProgress> = {};
|
||||
|
||||
readonly base: string;
|
||||
constructor(base: string) { this.base = base; }
|
||||
|
||||
// ---- transport
|
||||
|
||||
private async request<T>(method: string, path: string, body?: unknown, auth = true): Promise<T> {
|
||||
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<boolean> {
|
||||
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<void> => {
|
||||
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<string, unknown>) {
|
||||
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<Viewer> {
|
||||
const none: Viewer = { id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false };
|
||||
if (!this.tokens) return none;
|
||||
try {
|
||||
const p = await this.request<RawProfile>('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<Course[]> {
|
||||
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<RawOutline>('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<Student | null> {
|
||||
if (!this.tokens) return null;
|
||||
const [p, summary, issues] = await Promise.all([
|
||||
this.request<RawProfile>('GET', '/user/user-profile'),
|
||||
this.request<RawSummary>('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<InboxItem[]> {
|
||||
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<string, unknown>) {
|
||||
const jobs: Promise<unknown>[] = [];
|
||||
if (patch.orders) throw notConnected('Buying a course');
|
||||
const progress = patch.progress as Record<string, LessonProgress> | 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<string, Partial<Issue>>)) {
|
||||
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<string, unknown> = {};
|
||||
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<InboxItem>) {
|
||||
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; }
|
||||
}
|
||||
1
packages/data/src/fixtures-catalog.json
Normal file
1
packages/data/src/fixtures-catalog.json
Normal file
|
|
@ -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}
|
||||
1
packages/data/src/fixtures-outline-12.json
Normal file
1
packages/data/src/fixtures-outline-12.json
Normal file
|
|
@ -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}
|
||||
|
|
@ -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<void>;
|
||||
signOut(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Everything a screen may ask of the backend. */
|
||||
export interface DataSource {
|
||||
readonly kind: 'claude-db' | 'api';
|
||||
readonly auth?: AuthApi;
|
||||
viewer(): Promise<Viewer>;
|
||||
/** Display names for stored user ids (never store names). */
|
||||
names(ids: string[]): Promise<Record<string, string>>;
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ interface Ctx {
|
|||
/** Serialized writes: the db wants one write at a time per document. */
|
||||
write(fn: () => Promise<void>, okMsg?: string): Promise<boolean>;
|
||||
signIn(): void; signOut(): void;
|
||||
/** Re-reads who is signed in, after a real (API) sign-in. */
|
||||
reloadViewer(): Promise<void>;
|
||||
notify(studentId: string, item: Omit<InboxItem, 'id' | 'createdAt'>): Promise<void>;
|
||||
msg(loc: Locale, key: string, vars?: Record<string, string | number>): 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,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<button className={`ccard${tall ? ' ccard-tall' : ''}`} onClick={() => nav(`/${locale}/course/${c.slug}`)}>
|
||||
<Cover course={c} locale={locale} badge={<><span className="pill">{catName(c.categoryId)}</span>{!mine && <span className="ccard-tag">{tag}</span>}</>} />
|
||||
<Cover course={c} locale={locale} badge={<>{catName(c.categoryId) && <span className="pill">{catName(c.categoryId)}</span>}{!mine && <span className="ccard-tag">{tag}</span>}</>} />
|
||||
<div className="ccard-body">
|
||||
<h3>{ct(c, locale).title}</h3>
|
||||
<span className="meta num">{t('course.lessons', { n: p.total })} · {formatDuration(courseDuration(c))}</span>
|
||||
<span className="ccard-by">{t('course.by', { name: c.instructorName })}</span>
|
||||
<div className="ccard-foot">
|
||||
<span className="meta num">{t('course.lessons', { n: p.total })}{withDur(courseDuration(c))}</span>
|
||||
{c.instructorName && <span className="ccard-by">{t('course.by', { name: c.instructorName })}</span>}
|
||||
{(mine || c.prices.ETB != null) && <div className="ccard-foot">
|
||||
{mine ? <>
|
||||
{r && <span className="ccard-next">{p.pct === 100 ? <b>{t('course.completed')}</b> : <><b>{t('player.upNext')}</b> {r.index + 1}. {lessonTitle(r.lesson, locale)} · <span className="num">{formatDuration(r.lesson.durationSec)}</span></>}</span>}
|
||||
{r && <span className="ccard-next">{p.pct === 100 ? <b>{t('course.completed')}</b> : <><b>{t('player.upNext')}</b> {r.index + 1}. {lessonTitle(r.lesson, locale)}<span className="num">{withDur(r.lesson.durationSec)}</span></>}</span>}
|
||||
<span className="ccard-prog"><span className="bar grow" aria-label={`${p.pct}%`}><i style={{ width: `${p.pct}%` }} /></span><span className="small num">{p.pct}%</span></span>
|
||||
</> : c.prices.ETB != null && <strong className="num">{formatMoney(c.prices.ETB, 'ETB')}</strong>}
|
||||
</div>
|
||||
</> : <strong className="num">{formatMoney(c.prices.ETB!, 'ETB')}</strong>}
|
||||
</div>}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
|
|
@ -505,7 +508,7 @@ function ContinueCard({ c }: { c: Course }) {
|
|||
{r && <p className="continue-next">
|
||||
<span>{finished ? t('course.completed') : t('player.upNext')}</span>
|
||||
<strong>{r.index + 1}. {lessonTitle(r.lesson, locale)}</strong>
|
||||
<span className="num">{formatDuration(r.lesson.durationSec)} · {t('my.lessonsDone', { done: p.done, total: p.total })}</span>
|
||||
<span className="num">{[dur(r.lesson.durationSec), t('my.lessonsDone', { done: p.done, total: p.total })].filter(Boolean).join(' · ')}</span>
|
||||
</p>}
|
||||
{r && <button className="btn btn-accent btn-lg" onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}><Icon name="play" size={16} />{finished ? t('course.watchAgain') : t('course.continue', { n: r.index + 1 })}</button>}
|
||||
</div>
|
||||
|
|
@ -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 }) {
|
|||
<h1>{text.title}</h1>
|
||||
<div className="cd-stats">
|
||||
<span className="cd-pill"><Icon name="video" size={14} /><strong className="num">{lessons.length}</strong>{t('course.lessonsLabel')}</span>
|
||||
<span className="cd-pill"><Icon name="clock" size={14} /><strong className="num">{formatDuration(courseDuration(c))}</strong></span>
|
||||
{courseDuration(c) > 0 && <span className="cd-pill"><Icon name="clock" size={14} /><strong className="num">{formatDuration(courseDuration(c))}</strong></span>}
|
||||
{mine && <span className="cd-pill cd-pill-own"><Icon name="check" size={14} /><strong>{done ? t('course.completed') : t('course.owned')}</strong></span>}
|
||||
</div>
|
||||
{(text.subtitle || text.description) && <p className="cd-lead">{text.subtitle || text.description}</p>}
|
||||
{play && <button className="cd-hero-play" onClick={() => nav(play)}><span className="play-dot"><Icon name="play" size={12} /></span>{playLabel}</button>}
|
||||
<div className="cd-by">
|
||||
{c.instructorName && <div className="cd-by">
|
||||
<span className="avatar" aria-hidden>{initials(c.instructorName)}</span>
|
||||
<span className="cd-by-txt"><em>{t('course.createdBy')}</em><strong>{c.instructorName}</strong><span className="cd-by-n">{t('course.teaches', { n: teaches })}</span></span>
|
||||
</div>
|
||||
</div>}
|
||||
</section>
|
||||
|
||||
<aside className="cd-side">
|
||||
|
|
@ -653,13 +657,15 @@ function CoursePage({ slug }: { slug?: string }) {
|
|||
<div className="bar"><i style={{ width: `${p.pct}%` }} /></div>
|
||||
<span className="small muted num">{t('my.lessonsDone', { done: p.done, total: p.total })}</span>
|
||||
{pre && !preDone && <p className="cd-prereq"><Icon name="lock" size={14} /><span>{t('course.prereq', { title: ct(pre, locale).title })} <button className="link" onClick={() => nav(`/${locale}/course/${pre.slug}`)}>{t('course.prereqLink', { title: ct(pre, locale).title })}</button></span></p>}
|
||||
{r && !done && <p className="cd-next"><span>{t('player.upNext')}</span><strong>{r.index + 1}. {lessonTitle(r.lesson, locale)}</strong><span className="num">{clock(r.lesson.durationSec)}</span></p>}
|
||||
{r && !done && <p className="cd-next"><span>{t('player.upNext')}</span><strong>{r.index + 1}. {lessonTitle(r.lesson, locale)}</strong>{r.lesson.durationSec > 0 && <span className="num">{clock(r.lesson.durationSec)}</span>}</p>}
|
||||
{r && <div className="cd-cta" ref={setCtaEl}><button className={`btn btn-lg ${done ? 'btn-ghost' : 'btn-accent'}`} onClick={() => nav(`/${locale}/learn/${c.slug}/${r.lesson.id}`)}>{playLabel}</button></div>}
|
||||
</> : <>
|
||||
{c.prices.ETB != null && <div className="cd-price"><span className="num">{formatMoney(c.prices.ETB, 'ETB')}</span><span>{t('checkout.lifetime')}</span></div>}
|
||||
{pre && !preDone && <p className="cd-prereq"><Icon name="lock" size={14} /><span>{t('course.prereq', { title: ct(pre, locale).title })} <button className="link" onClick={() => nav(`/${locale}/course/${pre.slug}`)}>{t('course.prereqLink', { title: ct(pre, locale).title })}</button></span></p>}
|
||||
<div className="cd-cta" ref={setCtaEl}>
|
||||
<button className="btn btn-accent btn-lg" disabled={c.status !== 'PUBLISHED' || c.prices.ETB == null} onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('course.buyShort')}</button>
|
||||
{/* a course whose every lesson is free (the API's FREE tier) has nothing to buy: it starts instead */}
|
||||
{free ? <button className="btn btn-accent btn-lg" onClick={() => nav(`/${locale}/learn/${c.slug}/${lessons[0].id}`)}><Icon name="play" size={16} />{t('checkout.start')}</button>
|
||||
: <button className="btn btn-accent btn-lg" disabled={c.status !== 'PUBLISHED' || c.prices.ETB == null} onClick={() => nav(`/${locale}/checkout/${c.slug}`)}>{t('course.buyShort')}</button>}
|
||||
</div>
|
||||
<div className="cd-includes">
|
||||
<h2>{t('course.includes')}</h2>
|
||||
|
|
@ -688,14 +694,14 @@ function CoursePage({ slug }: { slug?: string }) {
|
|||
</div>}
|
||||
<div className="cd-pane cd-content" data-tab="content" data-active={active === 'content'}>
|
||||
<h2 className="cd-pane-h">{t('course.content')}</h2>
|
||||
<p className="small muted num">{t('course.lessons', { n: lessons.length })} · {formatDuration(courseDuration(c))}</p>
|
||||
<p className="small muted num">{t('course.lessons', { n: lessons.length })}{withDur(courseDuration(c))}</p>
|
||||
{chapters.map((ch, i) => {
|
||||
const ls = [...ch.lessons].sort((a, b) => a.sortOrder - b.sortOrder).filter((l) => l.isPublished);
|
||||
if (!ls.length) return null;
|
||||
const d = ls.filter((l) => isCompleted(me, l.id)).length;
|
||||
return (
|
||||
<details key={ch.id} className="ch" open={nextChapter ? ch.id === nextChapter : i === 0}>
|
||||
<summary><span className="grow"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{d}/{ls.length} · {formatDuration(ls.reduce((s, l) => s + l.durationSec, 0))}</span></span><Icon name="down" size={18} /></summary>
|
||||
<summary><span className="grow"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{d}/{ls.length}{withDur(ls.reduce((s, l) => s + l.durationSec, 0))}</span></span><Icon name="down" size={18} /></summary>
|
||||
{ls.map((l) => <LessonRow key={l.id} c={c} l={l} />)}
|
||||
{quizzes.filter((a) => a.chapterId === ch.id).map((a) => <AssessmentRow key={a.id} c={c} a={a} inline />)}
|
||||
</details>
|
||||
|
|
@ -729,7 +735,7 @@ function LessonRow({ c, l, current }: { c: Course; l: Lesson; current?: boolean
|
|||
<span className="lr-ic" aria-hidden>{current && !done ? <span className="eq"><i /><i /><i /></span> : done ? <Icon name="check" size={14} /> : access.ok ? <Icon name="play" size={12} /> : <Icon name="lock" size={14} />}</span>
|
||||
<span className="lr-txt">
|
||||
<span className="lr-title">{n}. {lessonTitle(l, locale)}</span>
|
||||
<span className="lr-meta num">{clock(l.durationSec)}{l.isPreview && !owns(me, c.id) && <span className="lr-tag">{t('course.preview')}</span>}{!access.ok && access.reason === 'COMING_SOON' && <span className="lr-tag">{t('course.comingSoon')}</span>}</span>
|
||||
<span className="lr-meta num">{l.durationSec > 0 && clock(l.durationSec)}{l.isPreview && !owns(me, c.id) && <span className="lr-tag">{t('course.preview')}</span>}{!access.ok && access.reason === 'COMING_SOON' && <span className="lr-tag">{t('course.comingSoon')}</span>}</span>
|
||||
{seen > 0 && <span className="lr-seen" aria-hidden><i style={{ width: `${seen}%` }} /></span>}
|
||||
</span>
|
||||
{current ? <span className="lr-now">{t('player.nowPlaying')}</span> : <Icon name="chevron" size={16} />}
|
||||
|
|
@ -928,7 +934,7 @@ function CourseContents({ c, lesson }: { c: Course; lesson: Lesson }) {
|
|||
return <details key={ch.id} className={`ps-ch${doneN === ls.length ? ' is-done' : ''}`} open={ls.some((l) => l.id === lesson.id) || undefined}>
|
||||
<summary>
|
||||
<span className="ps-ch-n num">{doneN === ls.length ? <Icon name="check" size={14} /> : String(ci + 1).padStart(2, '0')}</span>
|
||||
<span className="ps-ch-txt"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{doneN}/{ls.length} · {clock(ls.reduce((a, l) => a + l.durationSec, 0))}</span></span>
|
||||
<span className="ps-ch-txt"><strong>{tr(ch.translations, locale)?.title}</strong><span className="small muted num">{doneN}/{ls.length}{ls.some((l) => l.durationSec) ? ` · ${clock(ls.reduce((a, l) => a + l.durationSec, 0))}` : ''}</span></span>
|
||||
<Icon name="down" size={16} />
|
||||
</summary>
|
||||
<div className="ps-ch-list">{ls.map((l) => <LessonRow key={l.id} c={c} l={l} current={l.id === lesson.id} />)}</div>
|
||||
|
|
@ -939,10 +945,21 @@ function CourseContents({ c, lesson }: { c: Course; lesson: Lesson }) {
|
|||
|
||||
const AUTO_NEXT_SEC = 5;
|
||||
|
||||
/** vimeo.com/123, vimeo.com/123/abcdef (unlisted) or player.vimeo.com/video/123 → embeddable player URL; null otherwise. */
|
||||
export function vimeoPlayerUrl(url: string): string | null {
|
||||
const m = /vimeo\.com\/(?:video\/)?(\d+)(?:\/([0-9a-f]+))?/.exec(url);
|
||||
if (!m) return null;
|
||||
const hash = m[2] ?? new URL(url, 'https://x').searchParams.get('h');
|
||||
return `${VIMEO_ORIGIN}/video/${m[1]}?${hash ? `h=${hash}&` : ''}dnt=1&title=0&byline=0&portrait=0`;
|
||||
}
|
||||
|
||||
function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next?: Lesson; head?: ReactNode }) {
|
||||
const t = useTranslations();
|
||||
const { me, locale, nav, ds, write, signedIn, viewer } = useApp();
|
||||
const vimeo = !lesson.videoAssetId; // no upload yet: play the Vimeo placeholder instead
|
||||
// A Vimeo link (what the API's lessons carry) plays in Vimeo's player; no video yet plays the sample clip.
|
||||
const placeholder = !lesson.videoAssetId;
|
||||
const vimeoSrc = placeholder ? VIMEO_PLACEHOLDER : vimeoPlayerUrl(lesson.videoAssetId!);
|
||||
const vimeo = !!vimeoSrc;
|
||||
const [vdur, setVdur] = useState(0);
|
||||
const dur = (vimeo && vdur) || lesson.durationSec || 1;
|
||||
const saved = me?.progress?.[lesson.id];
|
||||
|
|
@ -1038,7 +1055,7 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
onLoadedMetadata={(e) => { if (pos) e.currentTarget.currentTime = pos; }}
|
||||
onTimeUpdate={(e) => setPos(e.currentTarget.currentTime)} onPlay={() => { setPlaying(true); setEnded(false); setAuto(null); }} onPause={() => setPlaying(false)} onEnded={() => { setPlaying(false); setEnded(true); }} />
|
||||
) : (
|
||||
<iframe ref={frameRef} src={VIMEO_PLACEHOLDER} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen />
|
||||
<iframe ref={frameRef} src={vimeoSrc!} onLoad={vlisten} title={lessonTitle(lesson, locale)} allow="autoplay; fullscreen; picture-in-picture" allowFullScreen />
|
||||
)}
|
||||
{canSave && <span className="wm" aria-hidden>{mark}</span>}
|
||||
{auto != null && next && <div className="p-upnext" role="status">
|
||||
|
|
@ -1070,7 +1087,7 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next
|
|||
</div>}
|
||||
</div>
|
||||
{head}
|
||||
{vimeo && <p className="small muted">{t('player.demoVideo')}{canSave && !done && <> · <button className="link" onClick={() => { setPos(dur); posRef.current = dur; heartbeat(); setEnded(true); }}>{t('player.markWatched')}</button></>}</p>}
|
||||
{placeholder && <p className="small muted">{t('player.demoVideo')}{canSave && !done && <> · <button className="link" onClick={() => { setPos(dur); posRef.current = dur; heartbeat(); setEnded(true); }}>{t('player.markWatched')}</button></>}</p>}
|
||||
{done && pct === 100 && (
|
||||
<div className="course-done" role="status">
|
||||
<div className="confetti" aria-hidden>{Array.from({ length: 18 }, (_, k) => <i key={k} style={{ '--k': k } as React.CSSProperties} />)}</div>
|
||||
|
|
@ -1134,7 +1151,7 @@ function Checkout({ slug }: { slug?: string }) {
|
|||
<aside className="cd-side">
|
||||
<div className="cd-buy">
|
||||
<div className="cd-preview" aria-hidden><img src={c.coverAssetId ? ds.assetUrl(c.coverAssetId) : coursePhoto(c, categories.map((k) => k.id))} alt="" /></div>
|
||||
<div className="stack-sm"><strong className="co-title">{ct(c, locale).title}</strong><span className="small muted">{t('course.by', { name: c.instructorName })}</span></div>
|
||||
<div className="stack-sm"><strong className="co-title">{ct(c, locale).title}</strong>{c.instructorName && <span className="small muted">{t('course.by', { name: c.instructorName })}</span>}</div>
|
||||
<div className="row-between co-total"><span>{t('checkout.total')}</span><strong className="num">{formatMoney(c.prices.ETB ?? 0, 'ETB')}</strong></div>
|
||||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<div className="cd-cta"><button className="btn btn-accent btn-lg" disabled={busy} onClick={start}>{t('checkout.pay', { method: methodName(method) })}</button></div>
|
||||
|
|
@ -1373,7 +1390,9 @@ function Help() {
|
|||
|
||||
function SignIn() {
|
||||
const t = useTranslations();
|
||||
const { viewer, account: me, ready, signIn, nav, locale } = useApp();
|
||||
const { viewer, account: me, ready, signIn, nav, locale, ds, reloadViewer } = useApp();
|
||||
const auth = ds.auth; // real sign-in (API); without it the code is simulated and shown on screen
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [mode, setMode] = useState<'phone' | 'email'>('phone');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [dial, setDial] = useState(() => { const r = (typeof navigator !== 'undefined' ? navigator.language : '').split('-')[1]?.toUpperCase(); return r && DIALS[r] ? r : 'ET'; });
|
||||
|
|
@ -1395,10 +1414,33 @@ function SignIn() {
|
|||
if (mode === 'phone' && !(dial === 'ET' ? /^[79]\d{8}$/.test(local) : local.length >= 4 && e164.length <= 16)) { setErr(t('auth.phoneInvalid')); return; }
|
||||
if (mode === 'email' && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr(t('auth.emailInvalid')); return; }
|
||||
if (mode === 'email' && !validPassword(pw)) { setErr(t('auth.passwordShort')); return; }
|
||||
if (auth) { void startReal(); return; }
|
||||
setCode(String(Math.floor(100000 + Math.random() * 900000))); setTries(5); setEntered(''); setWait(60); setStep('code');
|
||||
};
|
||||
const verify = (e: React.FormEvent) => {
|
||||
const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw });
|
||||
// After a real sign-in: a learner without a name yet goes to profile setup, everyone else home.
|
||||
const finish = async () => {
|
||||
await reloadViewer(); signIn();
|
||||
const v = await ds.viewer();
|
||||
if (v.name.trim()) nav(`/${locale}`); else setStep('setup');
|
||||
};
|
||||
const startReal = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const next = await auth!.start(contact());
|
||||
if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); }
|
||||
} catch (e) { setErr((e as Error).message || t('common.saveFailed')); }
|
||||
setBusy(false);
|
||||
};
|
||||
const verify = async (e: React.FormEvent) => {
|
||||
e.preventDefault(); setErr('');
|
||||
if (auth) {
|
||||
setBusy(true);
|
||||
try { await auth.verify(contact(), entered); await finish(); }
|
||||
catch (x) { setErr((x as Error).message || t('auth.wrongCode', { n: '' })); }
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
if (tries <= 0) { setErr(t('auth.locked')); return; }
|
||||
if (entered !== code) { const left = tries - 1; setTries(left); setErr(left ? t('auth.wrongCode', { n: left }) : t('auth.locked')); return; }
|
||||
if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup');
|
||||
|
|
@ -1414,11 +1456,12 @@ function SignIn() {
|
|||
<ul className="facts">{['fact2', 'fact3'].map((k) => <li key={k}><Icon name="check" size={16} />{t(`landing.${k}`)}</li>)}</ul>
|
||||
</div>
|
||||
<div className="auth-main">
|
||||
{!viewer?.id ? <Empty>{t('auth.noIdentity')}</Empty> : step === 'start' ? <form className="stack" onSubmit={(e) => { e.preventDefault(); send(); }}>
|
||||
{!auth && !viewer?.id ? <Empty>{t('auth.noIdentity')}</Empty> : step === 'start' ? <form className="stack" onSubmit={(e) => { e.preventDefault(); send(); }}>
|
||||
<div className="stack-sm"><h1>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
|
||||
{me && !me.deletedAt && <button type="button" className="btn btn-accent btn-block btn-lg" onClick={() => { signIn(); nav(`/${locale}`); }}>{t('auth.continueAs', { name: me.name.split(' ')[0] })}</button>}
|
||||
<SocialLogins onPick={() => { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} />
|
||||
<div className="or"><span>{t('auth.or')}</span></div>
|
||||
{/* Google / Apple need the providers' own sign-in SDKs before they can run against the API */}
|
||||
{!auth && <><SocialLogins onPick={() => { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} />
|
||||
<div className="or"><span>{t('auth.or')}</span></div></>}
|
||||
<h2 className="auth-h2">{mode === 'phone' ? t('auth.phoneTitle') : t('auth.emailTitle')}</h2>
|
||||
{mode === 'phone' ? (
|
||||
<label className="field"><span>{t('auth.phoneLabel')}</span>
|
||||
|
|
@ -1429,15 +1472,15 @@ function SignIn() {
|
|||
<label className="field"><span>{t('auth.passwordLabel')}</span><input id="pw" className="input" type="password" autoComplete="new-password" value={pw} onChange={(e) => setPw(e.target.value)} /><span className="hint">{t('auth.passwordHint')}</span></label>
|
||||
</>}
|
||||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<button className="btn btn-block">{t('auth.sendCode')}</button>
|
||||
<button className="btn btn-block" disabled={busy}>{t('auth.sendCode')}</button>
|
||||
<button type="button" className="link" onClick={() => { setMode(mode === 'phone' ? 'email' : 'phone'); setErr(''); }}>{mode === 'phone' ? t('auth.useEmail') : t('auth.usePhone')}</button>
|
||||
</form> : <form className="stack" onSubmit={verify}>
|
||||
<h1>{t('auth.codeTitle')}</h1>
|
||||
<p>{t('auth.codeSent', { target })}</p>
|
||||
<p className="banner"><strong>{t('auth.demoCode', { code })}</strong></p>
|
||||
{!auth && <p className="banner"><strong>{t('auth.demoCode', { code })}</strong></p>}
|
||||
<label className="field"><span className="sr-only">{t('auth.codeTitle')}</span><input id="otp" className="input otp" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={entered} onChange={(e) => setEntered(e.target.value.replace(/\D/g, ''))} /></label>
|
||||
{err && <p className="err" role="alert">{err}</p>}
|
||||
<button className="btn btn-accent btn-block" disabled={entered.length !== 6 || tries <= 0}>{t('auth.verify')}</button>
|
||||
<button className="btn btn-accent btn-block" disabled={busy || entered.length < 4 || (!auth && (entered.length !== 6 || tries <= 0))}>{t('auth.verify')}</button>
|
||||
<button type="button" className="btn btn-ghost btn-block" disabled={wait > 0} onClick={send}>{wait > 0 ? t('auth.resendIn', { s: wait }) : t('auth.resend')}</button>
|
||||
<button type="button" className="link" onClick={() => setStep('start')}>{t('common.back')}</button>
|
||||
</form>}
|
||||
|
|
|
|||
|
|
@ -54,6 +54,9 @@ importers:
|
|||
|
||||
packages/data:
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22
|
||||
version: 22.20.5
|
||||
'@types/react':
|
||||
specifier: ^19
|
||||
version: 19.3.0
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user