RezinaLMS-CustomerEnd/packages/data/src/index.ts
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

242 lines
13 KiB
TypeScript

// Domain types (field names follow SPEC §6) and the DataSource seam (§18.5).
// Screens only talk to DataSource; the demo passes ClaudeDbDataSource, production will pass ApiDataSource.
export type Locale = 'en' | 'am' | 'om' | 'ti';
export const LOCALES: Locale[] = ['am', 'en', 'om', 'ti'];
export type Currency = 'ETB' | 'USD';
export type AdminRole = 'SUPER_ADMIN' | 'CONTENT_MANAGER' | 'SUPPORT_AGENT' | 'FINANCE' | 'ANALYST';
export type CourseStatus = 'DRAFT' | 'PUBLISHED' | 'ARCHIVED';
export type VideoStatus = 'NONE' | 'UPLOADING' | 'PROCESSING' | 'READY' | 'FAILED';
export type OrderStatus = 'PENDING' | 'PAID' | 'FAILED' | 'EXPIRED' | 'CANCELLED' | 'REFUNDED';
export type IssueStatus = 'OPEN' | 'IN_PROGRESS' | 'RESOLVED' | 'CLOSED';
export type IssueType = 'BUG' | 'PAYMENT' | 'VIDEO' | 'ACCOUNT' | 'CONTENT' | 'OTHER';
export type Channel = 'IN_APP' | 'EMAIL' | 'SMS';
export type UserStatus = 'PENDING' | 'ACTIVE' | 'DEACTIVATED';
export type Tr<T> = Partial<Record<Locale, T>>;
export interface Category {
id: string; slug: string; sortOrder: number; isActive: boolean;
translations: Tr<{ name: string }>;
}
export interface Lesson {
id: string; sortOrder: number; isPreview: boolean; isPublished: boolean;
durationSec: number; videoAssetId?: string | null; videoStatus: VideoStatus;
translations: Tr<{ title: string; description?: string }>;
}
export interface Chapter {
id: string; sortOrder: number;
translations: Tr<{ title: string; summary?: string }>;
lessons: Lesson[];
}
/** Multiple-choice check at the end of a chapter or course. `answer` indexes the options, which share an order across locales. */
export interface Question { id: string; answer: number; translations: Tr<{ prompt: string; options: string[]; explain?: string }> }
export interface Assessment {
id: string; chapterId?: string | null; passPct: number;
translations: Tr<{ title: string; intro?: string }>;
questions: Question[];
}
export interface AssessmentResult { courseId: string; score: number; total: number; bestPct: number; passed: boolean; attempts: number; answers: number[]; submittedAt: string }
export interface Course {
id: string; slug: string; categoryId: string; instructorName: string; instructionLocale: Locale;
coverAssetId?: string | null; coverTone?: string;
status: CourseStatus; isFeatured: boolean; isTest: boolean; sequentialLessons: boolean;
prerequisiteCourseId?: string | null; publishedAt?: string | null; createdAt: string; updatedAt: string;
translations: Tr<{ title: string; subtitle?: string; description: string; audience?: string; outcomes?: string[] }>;
prices: Partial<Record<Currency, number>>; // integer minor units
enrolledCount?: number; // backend aggregate: students enrolled (purchase, grant or free)
chapters: Chapter[];
assessments?: Assessment[];
}
export interface Settings {
brandName: string; supportPhone: string; telegramLink: string; supportEmail: string;
sessionLimit: number; maintenanceBanner: string;
}
export interface PaymentEvent { type: string; at: string; note?: string; amountMinor?: number; currency?: Currency }
export interface Order {
id: string; courseId: string; currency: Currency; amountMinor: number;
provider: 'ARIFPAY' | 'MANUAL'; method: string; status: OrderStatus;
idempotencyKey: string; failureReason?: string | null; flaggedReason?: string | null;
paidAt?: string | null; expiresAt: string; createdAt: string; updatedAt: string;
events: PaymentEvent[];
}
export interface Enrollment { courseId: string; source: 'PURCHASE' | 'ADMIN_GRANT' | 'FREE'; orderId?: string | null; grantedByAdminId?: string | null; revokedAt?: string | null; createdAt: string }
export interface LessonProgress { courseId: string; positionSec: number; maxPositionSec: number; completedAt?: string | null; updatedAt: string }
export interface Issue {
id: string; type: IssueType; subject: string; description: string; status: IssueStatus;
screenshotAssetId?: string | null; assignedToId?: string | null; resolutionNote?: string | null;
reportedByAdminId?: string | null; createdAt: string; updatedAt: string;
}
export interface Student {
id: string; name: string; phone?: string; email?: string; country: string; city: string;
locale: Locale; status: UserStatus; createdAt: string; updatedAt: string; lastActiveAt?: string;
createdByAdminId?: string | null; deletedAt?: string | null; isSample?: boolean;
notificationPrefs?: Record<string, Partial<Record<Channel, boolean>>>;
enrollments: Record<string, Enrollment>;
orders: Record<string, Order>;
progress: Record<string, LessonProgress>;
issues: Record<string, Issue>;
assessments?: Record<string, AssessmentResult>; // assessment id → latest attempt (best score kept)
watchSec?: Record<string, number>; // 'YYYY-MM' → seconds watched (Analytics watch hours)
}
export interface InboxItem { id: string; type: string; title: string; body: string; link?: string | null; readAt?: string | null; createdAt: string }
export interface Campaign {
id: string; createdById: string; channels: Channel[];
audience: { type: 'ALL' | 'COURSE_BUYERS' | 'USERS' | 'CITY'; courseId?: string; userIds?: string[]; city?: string };
content: Tr<{ title: string; body: string }>;
status: 'DRAFT' | 'SCHEDULED' | 'SENT' | 'FAILED'; scheduledAt?: string | null; sentAt?: string | null; createdAt: string;
system?: boolean;
deliveries: Partial<Record<Channel, { sent: number; failed: number; pending: number; failedUserIds?: string[] }>>;
recipientCount: number;
}
export interface AuditEntry { id: string; adminId: string; action: string; entity: string; entityId: string; before?: unknown; after?: unknown; createdAt: string }
export interface Viewer { id: string | null; name: string; avatarUrl: string; isOwner: boolean; canEdit: boolean }
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>>;
watchCategories(cb: (c: Category[]) => void): Unsub;
watchCourses(cb: (c: Course[]) => void): Unsub;
watchSettings(cb: (s: Settings | null) => void): Unsub;
watchStudent(id: string, cb: (s: Student | null) => void): Unsub;
watchStudents(cb: (s: Student[]) => void): Unsub; // admin only
watchInbox(studentId: string, cb: (items: InboxItem[]) => void): Unsub;
watchCampaigns(cb: (c: Campaign[]) => void): Unsub;
watchAudit(cb: (a: AuditEntry[]) => void): Unsub;
saveStudent(s: Student): Promise<void>;
/** Deep-merge patch: nested objects merge, so a student and an admin can touch different keys of one doc. */
patchStudent(id: string, patch: Record<string, unknown>): Promise<void>;
saveCourse(c: Course): Promise<void>;
deleteCourse(id: string): Promise<void>;
saveCategory(c: Category): Promise<void>;
deleteCategory(id: string): Promise<void>;
saveSettings(s: Settings): Promise<void>;
addInbox(studentId: string, item: InboxItem): Promise<void>;
patchInbox(studentId: string, id: string, patch: Partial<InboxItem>): Promise<void>;
saveCampaign(c: Campaign): Promise<void>;
addAudit(a: AuditEntry): Promise<void>;
/** null when uploads aren't available to this viewer. */
uploads(): Promise<null | { upload(file: Blob): Promise<{ id: string; url: string }> }>;
assetUrl(id: string): string;
download(filename: string, data: string): Promise<boolean>;
/** Opens the reviewer comment composer pinned to an element; false when unavailable. */
feedback(el: Element): Promise<boolean>;
feedbackAvailable(): Promise<boolean>;
}
// ---------------------------------------------------------------- Claude db implementation
type AnyFn = (...a: any[]) => any; // runtime namespaces are untyped here; see artifact-capabilities d.ts
interface ClaudeRuntime { use(name: string): Promise<any> }
declare global { interface Window { claude?: ClaudeRuntime } }
const use = (name: string): Promise<any> =>
typeof window !== 'undefined' && window.claude?.use ? window.claude.use(name).catch(() => null) : Promise.resolve(null);
const data = <T,>(snap: { docs: { id: string; data(): unknown }[] }) => snap.docs.map((d) => ({ ...(d.data() as object), id: d.id }) as T);
/** Watch helper: subscribes once the db namespace resolves; returns a sync unsubscribe. */
function watch(build: (db: any) => { onSnapshot: AnyFn }, next: (snap: any) => void, onMissing?: () => void): Unsub {
let unsub: Unsub | null = null; let dead = false;
use('db').then((db) => {
if (dead) return;
if (!db) { onMissing?.(); return; }
try { unsub = build(db).onSnapshot(next, (e: { code: string }) => console.warn('db watch ended', e.code)); }
catch (e) { console.warn(e); onMissing?.(); }
});
return () => { dead = true; unsub?.(); };
}
async function db(): Promise<any> {
const d = await use('db');
if (!d) throw Object.assign(new Error('Saving is not available in this view.'), { code: 'not_granted' });
return d;
}
const clean = <T,>(o: T): T => JSON.parse(JSON.stringify(o)); // strips undefined; db bodies are plain JSON
export class ClaudeDbDataSource implements DataSource {
readonly kind = 'claude-db' as const;
async viewer(): Promise<Viewer> {
const u = await use('user');
if (!u) return { id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false };
const me = await u.me();
return { id: me.id, name: me.name, avatarUrl: me.avatarUrl, isOwner: me.isOwner, canEdit: me.canEdit };
}
async names(ids: string[]) {
const u = await use('user');
if (!u || !ids.length) return {};
const ps = await u.profiles(ids);
return Object.fromEntries(ids.map((id) => [id, ps[id]?.name || '']));
}
watchCategories(cb: (c: Category[]) => void) { return watch((d) => d.collection('categories'), (s) => cb(data<Category>(s)), () => cb([])); }
watchCourses(cb: (c: Course[]) => void) { return watch((d) => d.collection('courses'), (s) => cb(data<Course>(s)), () => cb([])); }
watchSettings(cb: (s: Settings | null) => void) { return watch((d) => d.doc('settings/app'), (s) => cb(s.exists ? (s.data() as Settings) : null), () => cb(null)); }
watchStudent(id: string, cb: (s: Student | null) => void) { return watch((d) => d.doc(`students/${id}`), (s) => cb(s.exists ? ({ ...s.data(), id } as Student) : null), () => cb(null)); }
watchStudents(cb: (s: Student[]) => void) { return watch((d) => d.collection('students'), (s) => cb(data<Student>(s)), () => cb([])); }
watchInbox(id: string, cb: (i: InboxItem[]) => void) { return watch((d) => d.collection(`students/${id}/inbox`).orderBy('createdAt', 'desc').limit(100), (s) => cb(data<InboxItem>(s)), () => cb([])); }
watchCampaigns(cb: (c: Campaign[]) => void) { return watch((d) => d.collection('campaigns').orderBy('createdAt', 'desc').limit(200), (s) => cb(data<Campaign>(s)), () => cb([])); }
watchAudit(cb: (a: AuditEntry[]) => void) { return watch((d) => d.collection('audit').orderBy('createdAt', 'desc').limit(500), (s) => cb(data<AuditEntry>(s)), () => cb([])); }
async saveStudent(s: Student) { await (await db()).doc(`students/${s.id}`).set(clean(s)); }
async patchStudent(id: string, patch: Record<string, unknown>) { await (await db()).doc(`students/${id}`).update(clean(patch)); }
async saveCourse(c: Course) { await (await db()).doc(`courses/${c.id}`).set(clean(c)); }
async deleteCourse(id: string) { await (await db()).doc(`courses/${id}`).delete(); }
async saveCategory(c: Category) { await (await db()).doc(`categories/${c.id}`).set(clean(c)); }
async deleteCategory(id: string) { await (await db()).doc(`categories/${id}`).delete(); }
async saveSettings(s: Settings) { await (await db()).doc('settings/app').set(clean(s)); }
async addInbox(studentId: string, item: InboxItem) { await (await db()).doc(`students/${studentId}/inbox/${item.id}`).set(clean(item)); }
async patchInbox(studentId: string, id: string, patch: Partial<InboxItem>) { await (await db()).doc(`students/${studentId}/inbox/${id}`).update(clean(patch)); }
async saveCampaign(c: Campaign) { await (await db()).doc(`campaigns/${c.id}`).set(clean(c)); }
async addAudit(a: AuditEntry) { await (await db()).doc(`audit/${a.id}`).set(clean(a)); }
async uploads() {
const a = await use('assets');
return a ? { upload: async (f: Blob) => { const r = await a.upload(f); return { id: r.id, url: r.url }; } } : null;
}
assetUrl(id: string) { return `/_blob/${id}`; }
async download(filename: string, body: string) {
const d = await use('downloads');
if (!d) return false;
try { await d.save({ filename, data: body }); return true; } catch { return false; }
}
async feedbackAvailable() { return !!(await use('comments')); }
async feedback(el: Element) {
const c = await use('comments');
if (!c) return false;
try { await c.openComposer({ element: el }); return true; } catch { return false; }
}
}
export const newId = (prefix = '') => prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
export { ApiDataSource, ApiError } from './api';