RezinaLMS-CustomerEnd/packages/features/src/store.tsx
n3p-tun3 8ba936baae 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.
2026-11-02 14:23:47 +03:00

158 lines
7.7 KiB
TypeScript

'use client';
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import type { Category, Course, DataSource, InboxItem, Locale, Settings, Student, Viewer } from '@lms/data';
import { LOCALES, newId } from '@lms/data';
import { messages } from '@lms/i18n';
export const DEFAULT_SETTINGS: Settings = { brandName: 'Sirkul Makeup', supportPhone: '+251 911 000 000', telegramLink: 'https://t.me/', supportEmail: 'support@example.com', sessionLimit: 2, maintenanceBanner: '' };
const store = {
get(k: string) { try { return localStorage.getItem('lms.' + k); } catch { return null; } },
set(k: string, v: string | null) { try { v == null ? localStorage.removeItem('lms.' + k) : localStorage.setItem('lms.' + k, v); } catch { /* per-viewer convenience only */ } },
};
// ---------------------------------------------------------------- hash router
export function parseRoute(hash: string): string[] {
return hash.replace(/^#\/?/, '').split('/').filter(Boolean).map(decodeURIComponent);
}
interface Ctx {
ds: DataSource;
viewer: Viewer | null;
ready: boolean;
categories: Category[]; courses: Course[]; settings: Settings; catalogLoaded: boolean;
/** The signed-in student; null when signed out, so no screen shows a signed-out visitor's courses. */
me: Student | null; meLoaded: boolean; signedIn: boolean;
/** The stored student record even when signed out (sign-in uses it for "Continue as"). */
account: Student | null;
inbox: InboxItem[];
locale: Locale; setLocale(l: Locale): void;
route: string[]; nav(path: string): void;
toast(msg: string): void;
/** 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;
}
const AppCtx = createContext<Ctx | null>(null);
export const useApp = () => { const c = useContext(AppCtx); if (!c) throw new Error('AppProvider missing'); return c; };
/** Message lookup outside React components (system notifications are written in the student's language). */
export function lookup(loc: Locale, key: string, vars: Record<string, string | number> = {}): string {
const get = (l: Locale) => key.split('.').reduce<any>((o, k) => o?.[k], messages[l]);
const raw: string = get(loc) ?? get('en') ?? key;
return raw.replace(/\{(\w+)(?:, plural,[^{}]*(?:\{[^{}]*\}[^{}]*)*)?\}/g, (_m, k) => String(vars[k] ?? ''));
}
export function AppProvider({ ds, children }: { ds: DataSource; children: ReactNode }) {
const [viewer, setViewer] = useState<Viewer | null>(null);
const [ready, setReady] = useState(false);
const [categories, setCategories] = useState<Category[]>([]);
const [courses, setCourses] = useState<Course[]>([]);
const [settings, setSettings] = useState<Settings | null>(null);
const [catalogLoaded, setCatalogLoaded] = useState(false);
const [me, setMe] = useState<Student | null>(null);
const [meLoaded, setMeLoaded] = useState(false);
const [inbox, setInbox] = useState<InboxItem[]>([]);
const [route, setRoute] = useState<string[]>([]);
const [locale, setLocaleState] = useState<Locale>('en');
const [toastMsg, setToastMsg] = useState<string | null>(null);
const [signedOut, setSignedOut] = useState(false);
const chain = useRef<Promise<unknown>>(Promise.resolve());
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// initial route + locale (client only)
useEffect(() => {
const r = parseRoute(location.hash);
const saved = store.get('locale') as Locale | null;
const loc = (LOCALES as string[]).includes(r[0]) ? (r[0] as Locale) : saved && LOCALES.includes(saved) ? saved : 'en';
setLocaleState(loc);
setRoute(r.length ? r : [loc]);
setSignedOut(store.get('signedOut') === '1');
const onHash = () => setRoute(parseRoute(location.hash));
addEventListener('hashchange', onHash); addEventListener('popstate', onHash);
return () => { removeEventListener('hashchange', onHash); removeEventListener('popstate', onHash); };
}, []);
useEffect(() => {
let alive = true;
ds.viewer().then((v) => { if (alive) { setViewer(v); setReady(true); } });
let gotCourses = false, gotCats = false;
const done = () => { if (gotCourses && gotCats) setCatalogLoaded(true); };
const u1 = ds.watchCourses((c) => { setCourses(c); gotCourses = true; done(); });
const u2 = ds.watchCategories((c) => { setCategories([...c].sort((a, b) => a.sortOrder - b.sortOrder)); gotCats = true; done(); });
const u3 = ds.watchSettings(setSettings);
return () => { alive = false; u1(); u2(); u3(); };
}, [ds]);
const uid = viewer?.id ?? null;
useEffect(() => {
if (!ready) return;
if (!uid) { setMeLoaded(true); return; }
const u1 = ds.watchStudent(uid, (s) => { setMe(s); setMeLoaded(true); });
const u2 = ds.watchInbox(uid, setInbox);
return () => { u1(); u2(); };
}, [ds, uid, ready]);
const nav = useCallback((path: string) => {
const r = parseRoute(path);
setRoute(r);
try { if (location.hash !== '#' + path) history.pushState(null, '', '#' + path); } catch { /* sandboxed history: state already updated */ }
try { scrollTo({ top: 0 }); } catch { /* jsdom */ }
}, []);
const toast = useCallback((m: string) => {
setToastMsg(m);
if (toastTimer.current) clearTimeout(toastTimer.current);
toastTimer.current = setTimeout(() => setToastMsg(null), 3200);
}, []);
const msg = useCallback((loc: Locale, key: string, vars?: Record<string, string | number>) => lookup(loc, key, vars), []);
const write = useCallback((fn: () => Promise<void>, okMsg?: string) => {
const p = chain.current.then(fn).then(() => { if (okMsg) toast(okMsg); return true; }, (e) => {
console.warn(e); toast(e?.code === 'not_granted' || e?.code === 'invalid_argument' ? lookup(locale, 'common.readOnly') : lookup(locale, 'common.saveFailed'));
return false;
});
chain.current = p;
return p;
}, [toast, locale]);
const setLocale = useCallback((l: Locale) => {
setLocaleState(l); store.set('locale', l);
setRoute((r) => {
const next = (LOCALES as string[]).includes(r[0]) ? [l, ...r.slice(1)] : r;
try { history.replaceState(null, '', '#/' + next.join('/')); } catch { /* ignore */ }
return next;
});
if (me && me.locale !== l && !me.deletedAt) write(() => ds.patchStudent(me.id, { locale: l }));
}, [me, ds, write]);
const notify = useCallback(async (studentId: string, item: Omit<InboxItem, 'id' | 'createdAt'>) => {
await ds.addInbox(studentId, { ...item, id: newId('n_'), createdAt: new Date().toISOString(), readAt: null });
}, [ds]);
const value: Ctx = {
ds, viewer, ready, categories, courses, settings: settings ?? DEFAULT_SETTINGS, catalogLoaded,
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); },
// 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,
};
return (
<AppCtx.Provider value={value}>
{children}
{toastMsg && <div className="toast" role="status">{toastMsg}</div>}
</AppCtx.Provider>
);
}