diff --git a/README.md b/README.md index a8628ac..c542886 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# MakeUp Academy — e-learning platform +# RezinaLMS — Customer End + +The student-facing side of the MakeUp Academy e-learning platform. This repo has no admin screens. Video courses for makeup artists in Amharic, Afaan Oromoo, Tigrinya and English. Students pay once per course (Telebirr / CBE Birr through ArifPay) and keep it for life. @@ -11,7 +13,7 @@ Video courses for makeup artists in Amharic, Afaan Oromoo, Tigrinya and English. | Path | What | |---|---| | `apps/demo` | Next.js 15 static export, inlined into one HTML file and published as the Claude artifact (SPEC §18) | -| `packages/features` | All student and admin screens, plus `domain.ts` (payments, access, progress, dashboard rules) | +| `packages/features` | All student screens, plus `domain.ts` (payments, access, progress, dashboard rules) | | `packages/data` | `DataSource` interface + `ClaudeDbDataSource`. Production adds `ApiDataSource` | | `packages/i18n` | Message catalogs. `om` and `ti` are drafts that need a translator | | `packages/db/seed` | Demo seed (fictional sample students are marked `isSample`) | @@ -26,6 +28,6 @@ npx -y pnpm@9 test # domain rules (payments, entitlement, progress, npx -y pnpm@9 run i18n:check # every locale has every key ``` -**Vercel (standalone demo):** `vercel.json` builds the static export, then `tools/vercel-build.mjs` injects the runtime mock and the seed. Outside Claude, all data lives in memory in each visitor's browser and resets on reload, and every visitor gets admin access. Deploy with `npx vercel deploy --prod`. +**Vercel (standalone demo):** `vercel.json` builds the static export, then `tools/vercel-build.mjs` injects the runtime mock and the seed. Outside Claude, all data lives in memory in each visitor's browser and resets on reload. Deploy with `npx vercel deploy --prod`. Phases 1–3 (Fastify API, Postgres, ArifPay, R2 video) haven't started yet. They wait on decisions D1, D2 and D8 in SPEC §17. diff --git a/packages/db/seed/demo-seed.mjs b/packages/db/seed/demo-seed.mjs index bd7b189..1783232 100644 --- a/packages/db/seed/demo-seed.mjs +++ b/packages/db/seed/demo-seed.mjs @@ -130,7 +130,7 @@ put('courses', 'crs-test', order({ ...base, slug: 'payment-test', categoryId: 'c translations: { en: { title: 'Payment test (staff only)', description: 'Real-money payment check at the provider minimum. Hidden from students and stats (L7).' } }, chapters: [ch('ch-t1', { en: 'Test' }, {}, [L('les-t1', 1, { en: { title: 'Test lesson' } })])] })); -// ---- fictional sample students so the admin dashboard has something to show +// ---- fictional sample students so the demo has realistic data const people = [ ['Abebech G.', '+251911000101', '', 'ET', 'Addis Ababa', 'am', '2026-01-14'], ['Tigist M.', '+251911000102', 'tigist@example.com', 'ET', 'Hawassa', 'am', '2026-02-03'], diff --git a/packages/features/src/admin.tsx b/packages/features/src/admin.tsx deleted file mode 100644 index a3b2645..0000000 --- a/packages/features/src/admin.tsx +++ /dev/null @@ -1,1115 +0,0 @@ -'use client'; -import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; -import type { AdminRole, Campaign, Category, Channel, Chapter, Course, Issue, IssueStatus, IssueType, Lesson, Locale, Order, Settings, Student, UserStatus } from '@lms/data'; -import { LOCALES, newId } from '@lms/data'; -import { LOCALE_NAMES } from '@lms/i18n'; -import { AdminDataProvider, lookup, useAdminData, useApp } from './store'; -import { - analytics, can, COUNTRIES, courseDuration, courseProgress, dashboardMetrics, effectiveStatus, ET_CITIES, formatDuration, formatMoney, missingLocales, - owns, publishedLessons, publishProblems, ROLE_AREAS, tr, validateLocation, type Area, type Period, -} from './domain'; -import { LocationFields } from './student'; -import { Cover, Empty, FeedbackButton, fmtDate, fmtDateTime, Icon, Logo, Modal, VIMEO_PLACEHOLDER, Skeleton, StatusPill } from './ui'; - -const ROLE_LABEL: Record = { SUPER_ADMIN: 'Super admin', CONTENT_MANAGER: 'Content manager', SUPPORT_AGENT: 'Support agent', FINANCE: 'Finance', ANALYST: 'Analyst' }; -const NAV: { group: string; items: [Area, string, string][] }[] = [ - { group: 'Overview', items: [['dashboard', 'Dashboard', 'grid'], ['analytics', 'Analytics', 'chart']] }, - { group: 'People', items: [['students', 'Students', 'users'], ['admins', 'Admins & roles', 'shield']] }, - { group: 'Learning', items: [['courses', 'Courses', 'book'], ['categories', 'Categories', 'tag']] }, - { group: 'Operations', items: [['orders', 'Orders', 'cart'], ['notifications', 'Notifications', 'send'], ['issues', 'Issues', 'flag'], ['audit', 'Audit log', 'list'], ['settings', 'Settings', 'cog']] }, -]; -const AREA_BLURB: Record = { - dashboard: 'What needs attention today.', analytics: 'Trends across the year.', courses: 'Categories → courses → chapters → lessons.', - categories: 'How the catalog is grouped for students.', students: 'Everyone who has a student account.', orders: 'Every checkout and its payment events.', - notifications: 'Send in-app, email and SMS messages and check delivery.', issues: 'Problems students reported, and their status.', - settings: 'Support contacts and platform options students see.', admins: 'Who can do what in this panel.', audit: 'Every change an admin made.', -}; -const CH_LABEL: Record = { IN_APP: 'In-app', EMAIL: 'Email', SMS: 'SMS' }; -const SMS_COST_MINOR = 50; // ETB 0.50 per SMS — estimate only, confirm with AfroSMS (D4) -const en = (c: Course) => tr(c.translations, 'en')?.title ?? c.slug; -const studentName = (s?: Student) => (s ? `${s.name}${s.isSample ? ' (sample)' : ''}` : 'Unknown student'); -const isoDay = (d: string) => (d ? new Date(d + 'T00:00:00Z').toISOString() : ''); - -function Head({ eyebrow, title, desc, actions }: { eyebrow: string; title: string; desc?: string; actions?: ReactNode }) { - return
{eyebrow}

{title}

{desc &&

{desc}

}
{actions &&
{actions}
}
; -} - -function Stat({ label, value, note, tone, now }: { label: string; value: ReactNode; note: string; tone?: 'ok' | 'bad'; now?: boolean }) { - return
{label}{now && RIGHT NOW}
{value}
{note}
; -} - -function useNames(ids: string[]) { - const { ds, viewer } = useApp(); - const [names, setNames] = useState>({}); - const key = [...new Set(ids)].sort().join(','); - useEffect(() => { ds.names(key ? key.split(',') : []).then(setNames); }, [ds, key]); - return (id: string) => (id === viewer?.id ? 'You' : names[id] || 'An admin'); -} - -// ---------------------------------------------------------------- shell - -export function AdminApp() { - const { viewer, ready, role, nav, locale } = useApp(); - const needsSignIn = ready && !!viewer?.canEdit && role !== 'admin'; - useEffect(() => { if (needsSignIn) nav(`/${locale}/signin/admin`); }, [needsSignIn, nav, locale]); - if (!ready || needsSignIn) return
; - if (!viewer?.canEdit) return ; - return ; -} - -function NoAccess() { - const { nav, locale } = useApp(); - return
nav(`/${locale}`)}>Go to the student app}>The admin panel is for people this demo is shared with as Editors. Ask the owner for edit access.
; -} - -function AdminShell() { - const app = useApp(); - const { route, nav, adminRole, setAdminRole, viewer, settings, locale, setRole } = app; - const { students } = useAdminData(); - const [open, setOpen] = useState(false); - const mainRef = useRef(null); - const area = (route[1] ?? 'dashboard') as Area; - const allowed = ROLE_AREAS[adminRole]; - const openIssues = students.flatMap((s) => Object.values(s.issues ?? {})).filter((i) => i.status === 'OPEN').length; - useScheduledCampaigns(); - return ( -
- -
-
- - Admin · {ROLE_LABEL[adminRole]} · demo data, payments simulated - mainRef.current} /> -
-
- {allowed.includes(area) ? : nav('/admin')}>Go to dashboard}>{ROLE_LABEL[adminRole]} can't open this page.} -
-
-
- ); -} - -function AdminRoutes({ area }: { area: Area }) { - const { route } = useApp(); - const [, , a, b] = route; - switch (area) { - case 'dashboard': return ; - case 'analytics': return ; - case 'courses': return a ? : ; - case 'categories': return ; - case 'students': return a ? : ; - case 'orders': return ; - case 'notifications': return a ? : ; - case 'issues': return ; - case 'settings': return ; - case 'admins': return ; - case 'audit': return ; - } -} - -// ---------------------------------------------------------------- period filter (§10.3) - -function PeriodPicker({ value, onChange }: { value: Period; onChange(p: Period): void }) { - const y = new Date().getUTCFullYear(); - const years = [y, y - 1, y - 2]; - const year = value.kind === 'all' ? y : value.year; - return ( -
-
- - - -
- {value.kind !== 'all' && } - {value.kind === 'month' && } -
- ); -} - -// ---------------------------------------------------------------- dashboard - -function Dashboard() { - const { courses, adminRole, nav, viewer } = useApp(); - const { students, auditLog, loaded } = useAdminData(); - const [p, setP] = useState({ kind: 'all' }); - const [tabSel, setTab] = useState(''); - const m = useMemo(() => dashboardMetrics(students, courses, p), [students, courses, p]); - const name = useNames(auditLog.slice(0, 8).map((a) => a.adminId)); - if (!loaded) return ; - const revenue = can.seeRevenue(adminRole); - const content = adminRole === 'CONTENT_MANAGER'; - const pendingOrders = students.flatMap((s) => Object.values(s.orders ?? {}).map((o) => ({ s, o }))).filter(({ o }) => effectiveStatus(o) === 'PENDING' && (o.flaggedReason || Date.now() - Date.parse(o.createdAt) > 10 * 60_000)); - const issues = students.flatMap((s) => Object.values(s.issues ?? {}).map((i) => ({ s, i }))).filter(({ i }) => i.status === 'OPEN' || i.status === 'IN_PROGRESS').sort((a, b) => b.i.createdAt.localeCompare(a.i.createdAt)); - const stats = [ - !content && , - !content && , - revenue && , - , - revenue && , - !content && , - , - ].filter(Boolean); - const top = stats.slice(0, 4), more = stats.slice(4); - const tabs = ([ - ['attention', 'Needs attention', issues.length + pendingOrders.length], - ...(more.length ? [['metrics', 'More metrics', 0]] : []), - ['activity', 'Recent activity', 0], - ['content', 'Content', 0], - ] as [string, string, number][]).filter(([k]) => !(content && k === 'attention')); - const tab = tabs.some(([k]) => k === tabSel) ? tabSel : tabs[0][0]; - return ( - <> - } /> -
{top}
-
-
{tabs.map(([k, label, n]) => )}
- {tab === 'attention' && (issues.length + pendingOrders.length === 0 ?

Nothing waiting. New issues and stuck payments show up here.

:
- {pendingOrders.slice(0, 5).map(({ s, o }) => nav('/admin/orders')}>)} - {issues.slice(0, 6).map(({ s, i }) => nav('/admin/issues')}>)} -
{studentName(s)}{formatMoney(o.amountMinor, o.currency)}
{i.subject}
{studentName(s)}
{fmtDate(i.createdAt)}
)} - {tab === 'metrics' &&
{more}
} - {tab === 'activity' && (auditLog.length ? <>
    {auditLog.slice(0, 8).map((a) =>
  1. {describeAction(a.action)}
    {name(a.adminId)} · {fmtDateTime(a.createdAt)}
  2. )}
- {adminRole === 'SUPER_ADMIN' && } :

Admin changes will appear here.

)} - {tab === 'content' && } -
- - ); -} - -function describeAction(a: string) { return a.replace('.', ': ').replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase()); } - -function ContentSnapshot() { - const { courses, categories, nav } = useApp(); - const lessons = courses.flatMap((c) => c.chapters.flatMap((ch) => ch.lessons)); - return ( -

Content snapshot

-

{categories.length} categories · {courses.length} courses · {courses.reduce((s, c) => s + c.chapters.length, 0)} chapters · {lessons.length} lessons

- {courses.slice(0, 5).map((c) => )} -
- ); -} - -// ---------------------------------------------------------------- analytics - -function BarChart({ values, labels, format }: { values: number[]; labels: string[]; format(v: number): string }) { - const W = 640, H = 220, pad = { l: 56, r: 8, t: 12, b: 26 }; - const max = Math.max(1, ...values); - const nice = Math.pow(10, Math.floor(Math.log10(max))); - const top = Math.ceil(max / nice) * nice; - const bw = (W - pad.l - pad.r) / values.length; - const y = (v: number) => pad.t + (H - pad.t - pad.b) * (1 - v / top); - const now = new Date().getUTCMonth(); - return ( - `${labels[i]} ${format(v)}`).join(', ')}> - {[0, .5, 1].map((f) => {format(top * f)})} - {values.map((v, i) => {`${labels[i]}: ${format(v)}`}{labels[i]})} - - ); -} - -function Analytics() { - const { courses } = useApp(); - const { students, loaded } = useAdminData(); - const [year, setYear] = useState(new Date().getUTCFullYear()); - const a = useMemo(() => analytics(students, courses, year), [students, courses, year]); - if (!loaded) return ; - const months = Array.from({ length: 12 }, (_, i) => new Date(Date.UTC(2000, i, 1)).toLocaleString('en', { month: 'short' })); - const methodTotal = Object.values(a.methodSplit).reduce((s, v) => s + v, 0); - const maxRev = Math.max(1, ...a.topByRevenue.map((r) => r.revenue)); - return ( - <> - Year} /> -
- s + v, 0), 'ETB')} note="ETB only, paid orders, test courses excluded." /> - s + v, 0)} note="Accounts created this year." /> - - -
-
-

Revenue by month (ETB)

v / 100)} labels={months} format={(v) => (v >= 1000 ? `${Math.round(v / 100) / 10}k` : String(Math.round(v)))} />
-

New students by month

String(Math.round(v))} />
-

Top courses by revenue

{a.topByRevenue.filter((r) => r.revenue).length ? a.topByRevenue.filter((r) => r.revenue).map((r) =>
{en(r.course)}{formatMoney(r.revenue, 'ETB')}
) :

No paid orders this year yet.

}
-

Enrollments and completion

{a.topByEnrollments.map((r) => )}
CourseEnrolledCompleted
{en(r.course)}{r.enrollments}{r.completionRate}%
-

Payment methods

{methodTotal ? Object.entries(a.methodSplit).map(([k, v]) =>
{k.replace('_', ' ')}{Math.round((v / methodTotal) * 100)}%
) :

No paid orders this year yet.

}
-
- - ); -} - -// ---------------------------------------------------------------- courses list (grouped like Logosmental "Content") - -function blankCourse(categoryId: string): Course { - const now = new Date().toISOString(); const id = newId('crs_'); - return { id, slug: id, categoryId, instructorName: '', instructionLocale: 'am', coverTone: 'rose', status: 'DRAFT', isFeatured: false, isTest: false, sequentialLessons: false, prerequisiteCourseId: null, publishedAt: null, createdAt: now, updatedAt: now, translations: { en: { title: 'Untitled course', description: '' } }, prices: {}, chapters: [] }; -} - -function Courses() { - const { courses, categories, nav, adminRole, ds, write, audit, catalogLoaded } = useApp(); - const [show, setShow] = useState<'all' | 'PUBLISHED' | 'DRAFT' | 'ARCHIVED' | 'TEST'>('all'); - const editable = can.editContent(adminRole); - const list = courses.filter((c) => show === 'all' || (show === 'TEST' ? c.isTest : c.status === show && !c.isTest)); - const create = async () => { - if (!categories.length) { nav('/admin/categories'); return; } - const c = blankCourse(categories[0].id); - if (await write(() => ds.saveCourse(c))) { await audit('course.create', 'Course', c.id, null, { title: en(c) }); nav(`/admin/courses/${c.id}`); } - }; - if (!catalogLoaded) return ; - return ( - <> - Create course} /> -
- !c.isTest).length} note={`${courses.filter((c) => c.status === 'PUBLISHED' && !c.isTest).length} published`} /> - s + c.chapters.length, 0)} note="Across all courses" /> - s + c.chapters.reduce((a, ch) => a + ch.lessons.length, 0), 0)} note={`${courses.reduce((s, c) => s + publishedLessons(c).length, 0)} published`} /> -
-
{(['all', 'PUBLISHED', 'DRAFT', 'ARCHIVED', 'TEST'] as const).map((s) => )}
- {!courses.length && Create course}>No courses yet. Create a category first, then a course inside it.} - {categories.map((cat) => { - const cs = list.filter((c) => c.categoryId === cat.id); - if (!cs.length) return null; - return
{tr(cat.translations, 'en')?.name} - {cs.map((c) => ( - - ))} -
; - })} - - ); -} - -// ---------------------------------------------------------------- course editor (§10.4) - -function CourseEditor({ id, tab = 'details' }: { id: string; tab?: string }) { - const { courses, nav, ds, write, audit, adminRole, notify, toast } = useApp(); - const { students } = useAdminData(); - const saved = courses.find((c) => c.id === id); - const [draft, setDraft] = useState(null); - const [loc, setLoc] = useState('en'); - useEffect(() => { if (saved && !draft) setDraft(structuredClone(saved)); }, [saved, draft]); - if (!saved) return nav('/admin/courses')}>All courses}>This course doesn't exist or was deleted.; - if (!draft) return ; - const editable = can.editContent(adminRole); - const dirty = JSON.stringify(draft) !== JSON.stringify(saved); - const problems = publishProblems(draft); - const enrolled = students.filter((s) => owns(s, id)); - const hasPurchases = students.some((s) => Object.values(s.orders ?? {}).some((o) => o.courseId === id)) || enrolled.length > 0; - const set = (patch: Partial) => setDraft({ ...draft, ...patch, updatedAt: new Date().toISOString() }); - - const save = async (next: Course = draft, action = 'course.update') => { - const body = { ...next, slug: slugify(tr(next.translations, 'en')?.title ?? next.slug, next.id) }; - if (!(await write(() => ds.saveCourse(body), 'Saved'))) return; - await audit(action, 'Course', id, { status: saved.status }, { status: body.status, title: en(body) }); - setDraft(structuredClone(body)); - // automatic notification: new published lesson in a published course → owners (§10.5) - if (body.status === 'PUBLISHED') { - const before = new Set(publishedLessons(saved).map((l) => l.id)); - const added = publishedLessons(body).filter((l) => !before.has(l.id)); - if (added.length && saved.status === 'PUBLISHED') for (const s of enrolled) await write(() => notify(s.id, { type: 'NEW_LESSON', title: tr(added[0].translations, s.locale)?.title ?? 'New lesson', body: `${tr(body.translations, s.locale)?.title}: ${added.length} new lesson${added.length > 1 ? 's' : ''}.`, link: `/${s.locale}/course/${body.slug}` })); - } - }; - const tabs: [string, string][] = [['details', 'Details'], ['pricing', 'Pricing'], ['curriculum', 'Curriculum'], ['students', `Students (${enrolled.length})`]]; - return ( - <> -
- - - {dirty && } - {draft.status !== 'PUBLISHED' - ? - : } - {draft.status !== 'ARCHIVED' && draft.status === 'PUBLISHED' && } - {draft.status === 'DRAFT' && } - } /> - {draft.status !== 'PUBLISHED' && problems.length > 0 &&
Before you can publish: {problems.join(' · ')}
} -
{tabs.map(([k, label]) => )}
- {tab === 'details' && } - {tab === 'pricing' && } - {tab === 'curriculum' && } - {tab === 'students' &&
- {enrolled.length ? enrolled.map((s) => nav(`/admin/students/${s.id}`)}>) : } -
StudentSourceProgressEnrolled
{studentName(s)}{s.enrollments[id].source.replace('_', ' ').toLowerCase()}{courseProgress(saved, s).pct}%{fmtDate(s.enrollments[id].createdAt)}
No students yet. Grant access from a student's page, or share the course link.
} - {dirty && editable &&
} - - ); -} - -const slugify = (s: string, id: string) => (s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || id); - -function LocaleTabs({ value, onChange, missing }: { value: Locale; onChange(l: Locale): void; missing: Locale[] }) { - const order: Locale[] = ['en', 'am', 'om', 'ti']; - return
{order.map((l) => )}
; -} - -function DetailsTab({ c, set, loc, setLoc, editable }: { c: Course; set(p: Partial): void; loc: Locale; setLoc(l: Locale): void; editable: boolean }) { - const { categories, courses, ds, adminRole } = useApp(); - const tx = c.translations[loc] ?? { title: '', description: '' }; - const setTx = (p: Partial) => set({ translations: { ...c.translations, [loc]: { ...tx, ...p } } }); - const [uploader, setUploader] = useState>>(null); - const [upErr, setUpErr] = useState(''); - useEffect(() => { ds.uploads().then(setUploader); }, [ds]); - const dis = !editable; - return ( -
-
-

Text

- {loc !== 'en' &&

Empty fields fall back to English for students.

} -
- - - -