// 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 = Partial>; 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>; // 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>>; enrollments: Record; orders: Record; progress: Record; issues: Record; assessments?: Record; // assessment id → latest attempt (best score kept) watchSec?: Record; // '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>; 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; 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>; 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; /** Deep-merge patch: nested objects merge, so a student and an admin can touch different keys of one doc. */ patchStudent(id: string, patch: Record): Promise; saveCourse(c: Course): Promise; deleteCourse(id: string): Promise; saveCategory(c: Category): Promise; deleteCategory(id: string): Promise; saveSettings(s: Settings): Promise; addInbox(studentId: string, item: InboxItem): Promise; patchInbox(studentId: string, id: string, patch: Partial): Promise; saveCampaign(c: Campaign): Promise; addAudit(a: AuditEntry): Promise; /** null when uploads aren't available to this viewer. */ uploads(): Promise }>; assetUrl(id: string): string; download(filename: string, data: string): Promise; /** Opens the reviewer comment composer pinned to an element; false when unavailable. */ feedback(el: Element): Promise; feedbackAvailable(): Promise; } // ---------------------------------------------------------------- Claude db implementation type AnyFn = (...a: any[]) => any; // runtime namespaces are untyped here; see artifact-capabilities d.ts interface ClaudeRuntime { use(name: string): Promise } declare global { interface Window { claude?: ClaudeRuntime } } const use = (name: string): Promise => typeof window !== 'undefined' && window.claude?.use ? window.claude.use(name).catch(() => null) : Promise.resolve(null); const data = (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 { 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 = (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 { 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(s)), () => cb([])); } watchCourses(cb: (c: Course[]) => void) { return watch((d) => d.collection('courses'), (s) => cb(data(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(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(s)), () => cb([])); } watchCampaigns(cb: (c: Campaign[]) => void) { return watch((d) => d.collection('campaigns').orderBy('createdAt', 'desc').limit(200), (s) => cb(data(s)), () => cb([])); } watchAudit(cb: (a: AuditEntry[]) => void) { return watch((d) => d.collection('audit').orderBy('createdAt', 'desc').limit(500), (s) => cb(data(s)), () => cb([])); } async saveStudent(s: Student) { await (await db()).doc(`students/${s.id}`).set(clean(s)); } async patchStudent(id: string, patch: Record) { 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) { 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';