RezinaLMS-CustomerEnd/SPEC.md
kirukib 118d26d158 feat: Phase 0 Claude-hosted demo of the e-learning platform
Spec v1.2, Logosmental-based design direction and tokens, pnpm monorepo
(apps/demo, packages/data|features|i18n|db/seed), student + admin screens
in 4 locales, simulated ArifPay checkout on the real order state machine,
artifact inline/check tools, domain rule checks and UI audit fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 23:57:11 +03:00

76 KiB
Raw Permalink Blame History

E-Learning Platform — Web Demo Implementation Spec (v1.2)

How to use this file. This is the only document needed to build the system. Claude (or any engineer) reads it top to bottom before writing code, then works task-by-task through §15 (Build Order), starting with Phase 0, the Claude-hosted demo (§18). Working rules are in "How to work" below; conventions in §14; build scripts in Appendix A. When something is marked DECISION NEEDED, stop and ask instead of guessing. Update this file in the same PR whenever a decision changes.

How to work

  1. Pick the next unchecked task ID in §15 (e.g. C0-03, W1-06). One task per branch and PR.
  2. Before coding, restate the task's acceptance criteria, the test IDs from §13 it covers, and the files you'll touch.
  3. If the task depends on a DECISION NEEDED item in §17, stop and ask. Never guess on payments, security or roles.
  4. UI tasks: read design/inspo/README.md and design/tokens.json first, write a short token and layout plan, build, then run a design critique, UX copy review and accessibility review.
  5. Write tests alongside code. Run lint, typecheck, tests and the click-everything smoke test before calling a task done.
  6. If you change the data model, API, or a decision, update this spec in the same PR.

Hard rules

  • Never unlock a course from the browser's return URL or any client claim. Only from a verified webhook or a server-side status query.
  • Never make the R2 bucket or any video object public.
  • Money is integer minor units. Never floats. Never add ETB and USD together.
  • Orders and enrollments are transactional and idempotent.
  • isTest courses never appear to students or in stats.
  • No delete that cascades into courses, lessons or purchases. Archive instead.
  • No visible button or link without a working action. Hide unfinished features behind flags.
  • No raw hex colors or ad-hoc font sizes in components. Use tokens.
  • No secrets in code or commits.

Commands (create these scripts in W1-01 / C0-02)

Purpose Command
Install pnpm install
Local services docker compose -f infra/docker-compose.yml up -d (Postgres, Redis, MinIO, Mailpit at http://localhost:8025)
Database pnpm --filter db prisma migrate dev · seed: pnpm --filter db seed
Dev pnpm dev (api, worker, web, admin) · demo: pnpm --filter demo dev
Tests pnpm test · E2E: pnpm e2e · smoke: pnpm e2e:smoke
Checks pnpm lint && pnpm typecheck && pnpm i18n:check
Claude 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

0. What changed in v1.1 and v1.2

Change Why
Demo is web-only. The Flutter apps are deferred. Students use a responsive web app (mobile-first, installable as a PWA). Faster to demo, no app store review, and no Apple/Google billing rules to deal with yet. The API stays client-agnostic so Flutter can be added later without backend rewrites (§16).
Lessons from Yimaru built in (§2). The Yimaru UAT sheet, Issues doc, and backend test plan show exactly which things went wrong or got re-requested. Each one is now a requirement or a test here.
ArifPay is the primary payment provider. Yimaru already integrated it (checkout, verify, webhook, direct OTP payment). One aggregator covers Telebirr, CBE Birr and other local methods. Direct Telebirr/CBE adapters become optional.
Design direction section added (§11). So the UI is built from a deliberate token system and inspiration references, not default component-kit styling.
Test plan rewritten in Yimaru's format (§13): module IDs, P0–P3 priorities, test pyramid. The team already knows this format and the client has seen it.
Admin dashboard, notifications, user management and roles specified in detail. These were the most re-worked areas in Yimaru UAT.
Claude-hosted demo added (§18, Phase 0). A working click-through version of the platform is published as a Claude artifact before the production build. The client can review and comment on real screens within days, and UAT feedback lands as comments pinned to the exact screen instead of a spreadsheet. The production stack (§3) is unchanged.
Next.js everywhere, including the Claude-hosted demo. The demo is a Next.js 15 app (apps/demo) built as a static export and inlined into one HTML file. One framework and one set of components for demo and production. Verified: an inlined Next.js 15.5 export loads, handles clicks and hash routing, renders Ge'ez text, and makes zero network requests.

1. Product summary

A learning platform for Ethiopian and diaspora students. Students browse courses, pay once per course (lifetime access), and stream video lessons organized as Category → Course → Chapter → Lesson. Admins manage content, students, payments and notifications from a web panel.

1.1 Demo goals

  1. A student on a mid-range Android phone in Chrome can go from landing page → paid → watching lesson 1 in under 5 minutes.
  2. ≥ 95% of successful payments unlock the course automatically within 60 s, with no admin action.
  3. Video starts in < 4 s at p75 on a 4G connection; 240p/360p options play on weak 3G.
  4. No path exists for a non-purchasing user to get playable video (verified by §13.4).
  5. The client can publish a course with 20 lessons and send a notification without developer help.
  6. Every visible button and link does something. No dead ends (Yimaru lesson L3).

1.2 In the demo

Student web app · Admin panel · API · Video pipeline (R2 + FFmpeg + HLS) · ArifPay payments (ETB) · Email + SMS + in-app notifications · Four languages · Issue reporting.

1.3 Not in the demo

Flutter mobile apps, app store billing, live classes, chat, quizzes/exams, certificates, AI tutor, offline downloads, studio DRM, subscriptions, custom role builder. §16 explains how the design keeps each of these possible later.

1.4 Personas

  • Student: usually on an Android phone browser, metered data, may prefer Amharic, Afaan Oromoo or Tigrinya.
  • Diaspora student: laptop or phone, may pay in USD (DECISION NEEDED D3).
  • Content manager: uploads videos, edits courses. Never sees money.
  • Support agent: helps students, grants access, resolves issues.
  • Finance: sees orders and revenue, marks refunds.
  • Super admin: everything, including admin accounts and settings.

2. Lessons from Yimaru (requirements, not suggestions)

Each item below came from the Yimaru UAT sheet, the Issues doc, or the backend test plan. The ID is referenced in tasks and tests.

ID What happened on Yimaru Rule for this project
L1 Google sign-in failed in UAT more than once. Demo ships with phone OTP + email/password only. Google sign-in is P1 and only enabled after it passes an end-to-end test on the real staging domain (OAuth redirect URIs and consent screen configured for that domain).
L2 OTP email arrived from sender "Y" with an unbranded body. Client said it looked untrustworthy. All email goes through Resend with sender name "<Brand> Academy" <no-reply@domain>, SPF/DKIM/DMARC set, and branded HTML templates in all 4 languages. A test asserts the sender name.
L3 "Start learning" showed a blank screen; My Progress buttons, Telegram support and Call support did nothing. No UI element ships without a working action. Unfinished features are hidden behind feature flags, not shown disabled. A Playwright "click every link and button" smoke test runs in CI on every page (§13.5). tel: and https://t.me/ links come from admin settings and are tested.
L4 Password rules (number + symbol) frustrated users; client asked to relax them. Minimum 8 characters, maximum 128, no composition rules (NIST SP 800-63B). Optional check against a common-password list.
L5 "Where are you from" city field had to be fixed after the client asked three times. Country dropdown. If Ethiopia → city dropdown (seeded list). Otherwise → free-text city. Written into acceptance criteria so it can't be missed.
L6 Dashboard was reworked repeatedly: missing time range, "active vs total" counts, monthly revenue trend, analytics mixed into dashboard. Dashboard and Analytics are separate pages, specified exactly in §10.3. Every metric has a definition in the spec.
L7 A 0.1 Birr test plan, created to test ArifPay, showed up in the client's view and caused confusion. Courses have an isTest flag. Test courses are hidden from students and labeled "Test" in admin. Real-money testing uses them; they're excluded from all stats.
L8 Notification page needed compose, channel choice, audience, history table, filters and delivery detail. Built that way from the start (§10.5).
L9 Issue reporting existed in admin but not on the student side. Both sides ship together: students report from Help, admins triage and resolve, the student is notified on status change.
L10 Nobody knew what admin "Register User" was for. No ambiguous actions. Admin has a clearly named "Add student manually" with a description of when to use it (walk-in or phone sales).
L11 "Add new role" didn't work. Fixed roles for the demo (§10.1). Custom role builder is P2.
L12 Client wanted courses linked in sequence with prerequisites. Course has optional prerequisiteCourseId. Course also has sequentialLessons: if on, lesson N+1 unlocks after lesson N is completed.
L13 Activity log needed filters. Audit log filterable by actor, action, entity, and date range from day one.
L14 Assets were "in the Figma file" but developers couldn't extract them; low-quality images were used. Design handoff rule: all assets exported to /design/assets as SVG, or PNG/WebP at 2× and 3×, before the task that uses them starts. Figma is the source of truth for layout; the repo is the source of truth for assets.
L15 Yimaru deleting a category cascaded and deleted its courses. Deleting anything that has children or purchases is blocked. Use archive. Hard delete only for empty drafts.
L16 Yimaru tested file uploads for spoofed content types, path traversal and size limits. Same checks here: content sniffing (magic bytes), UUID filenames, size limits per type (§13.4).

3. System architecture

 Student browser                Admin browser
 (Next.js web app)              (Next.js admin)
        │  HTTPS, cookie auth          │  HTTPS, cookie auth + 2FA
        ▼                              ▼
 ┌──────────────────────────────────────────┐
 │ API — Node 22 / TypeScript / Fastify     │──▶ PostgreSQL 16 (Prisma)
 │ client-agnostic: cookie OR bearer auth   │──▶ Redis (rate limits, cache, BullMQ)
 └───────┬───────────────────────┬──────────┘
         │ enqueue                │ webhooks in
         ▼                        ▼
 ┌──────────────────┐      ┌──────────────┐
 │ Worker + FFmpeg  │      │ ArifPay      │
 │ (BullMQ)         │      └──────────────┘
 └───────┬──────────┘
         │ HLS output                 Resend (email) · AfroSMS (SMS)
         ▼                            Sentry (errors)
 ┌──────────────────┐
 │ Cloudflare R2    │◀── Cloudflare Worker validates signed token on every
 │ (private)        │    playlist/segment request; hls.js plays in browser
 └──────────────────┘

Key choices:

  • Separate API, not Next.js API routes. The future Flutter app needs the same API; keeping it separate now avoids a rewrite.
  • Fastify for schema validation and TypeScript support.
  • BullMQ + Redis for transcoding, notification fan-out, payment reconciliation. Heavy work never runs in the API process.
  • Direct-to-R2 multipart upload from the admin browser with presigned URLs. Large files never pass through the API.
  • Cloudflare Worker in front of private R2. R2 is never public.

3.1 Backend language — DECISION NEEDED (D1)

Yimaru's backend is Go (Fiber, sqlc, pgx). The client's scope document specifies Node.js + TypeScript + Prisma.

  • Default in this spec: Node/TS, as the client asked. Port Yimaru's designs (ArifPay flow, AfroSMS client, role model, test cases), not its code.
  • Alternative: reuse Yimaru Go modules directly for speed. Only if the client agrees to change the stack in writing.

4. Repository layout

/
├── SPEC.md                 ← this file
├── design/
│   ├── inspo/              screenshots/links from the inspiration board (§11.1)
│   ├── tokens.json         color, type, spacing, radius tokens (§11.3)
│   └── assets/             exported logos, illustrations, patterns (L14)
├── apps/
│   ├── api/                Fastify + Prisma
│   ├── worker/             BullMQ consumers, FFmpeg
│   ├── web/                Student web app — Next.js 15 App Router
│   ├── admin/              Admin panel — Next.js 15 App Router
│   ├── demo/               Claude-hosted demo — Next.js 15, static export, inlined to one HTML (§18)
│   └── edge/               Cloudflare Worker for signed HLS delivery
├── packages/
│   ├── db/                 Prisma schema, migrations, seed
│   ├── shared/             Zod schemas, types, error codes
│   ├── ui/                 Shared React components built on tokens (Radix primitives + Tailwind)
│   ├── features/           Shared screens (student + admin) that read data through a DataSource
│   ├── data/               DataSource interface + ApiDataSource (production) + ClaudeDbDataSource (demo)
│   ├── i18n/               Message catalogs en/am/om/ti + helpers
│   ├── emails/             React Email templates (4 languages)
│   └── config/             eslint, tsconfig, prettier, tailwind preset
├── tools/                  artifact-inline.mjs, artifact-check.mjs (Appendix A)
├── e2e/                    Playwright tests (incl. click-everything smoke test)
├── infra/                  docker-compose (Postgres, Redis, MinIO, Mailpit), deploy configs
└── .github/workflows/      CI

Tooling: pnpm workspaces + Turborepo, Node 22 LTS. docker compose up gives Postgres 16, Redis 7, MinIO (local R2), and Mailpit (local email inbox).


5. Student web app — requirements

P0 = must ship in the demo. P1 = ship if time allows. Each feature lists acceptance criteria.

5.1 Platform (P0)

  • Next.js 15 App Router, React Server Components for catalog pages (fast, indexable), client components only where interactive.
  • Mobile-first responsive: designed at 360 px wide first, then tablet and desktop.
  • Locale in the URL: /{am|en|om|ti}/... via next-intl. Default locale from the Accept-Language header, then stored in a cookie and on the user profile.
  • Course and category pages are public and indexable (SEO, link sharing on Telegram). Each has Open Graph tags with the course cover.
  • PWA (P1): web manifest, icons, installable to home screen. No offline video.

5.2 Authentication (P0)

  • Phone + SMS OTP (AfroSMS, +251 default, other country codes allowed). 6 digits, 5-minute expiry, 5 wrong attempts max, resend after 60 s, max 5 sends per hour per number.
  • Email + password as the second option (diaspora). Password rule per L4. Email verification by OTP via Resend (branded per L2).
  • Password reset: send code → verify → set new password (same flow Yimaru tested in AUTH-15).
  • Sessions on web: httpOnly, Secure, SameSite=Lax cookies holding a short-lived access token (15 min) and a rotating refresh token (30 days). The API also accepts Authorization: Bearer so the mobile app can use the same endpoints later.
  • CSRF: SameSite=Lax plus an Origin header check on every state-changing request.
  • Session limit: max 2 active sessions per student (configurable). Signing in on a third browser shows the active sessions and asks the student to sign one out.
  • Google sign-in: P1, gated by L1.

Acceptance:

  • New phone number → OTP → profile setup (name, country, city per L5, language) → Home.
  • 5 wrong OTPs lock that code.
  • Reusing an old refresh token signs out every session in that token family.
  • Third session is blocked until another is signed out.
  • OTP and reset emails show the brand sender name (L2).

5.3 Home & browsing (P0)

  • Public landing page for signed-out visitors: what the platform is, featured courses, how payment works (Telebirr / CBE Birr logos), language switcher, sign-in.
  • Signed-in Home: Continue watching, My courses, featured, categories, new courses.
  • Category page → course list. Cursor pagination, 20 per page.
  • Search by title, instructor, category in all four languages (Postgres pg_trgm; Ge'ez text matched as typed). Debounced 300 ms.

5.4 Course page (P0)

  • Cover, title, description, instructor, language of instruction, total duration, lesson count, price, last updated.
  • Prerequisite notice if prerequisiteCourseId is set and not completed (L12).
  • Curriculum: chapters expand to lessons with duration and lock state. Free preview lessons play without buying.
  • Buttons: "Buy for ETB 1,200" if not owned, "Continue lesson 4" if owned.

5.5 Purchase (P0) — §8

  • Choose method → redirect to ArifPay hosted checkout → return to /orders/{id}.
  • Order page polls GET /orders/:id every 3 s for up to 3 min.
  • Paid → "You now own this course" → "Start lesson 1". Failed → reason + "Try again". Still pending after 3 min → "We're still waiting for confirmation from your bank. You'll get an SMS when it's done."

5.6 My Courses & progress (P0)

  • Owned courses with progress bar and "Resume" (last lesson + position).
  • My Progress page: per course, chapters with completed lessons ticked. Every button on it works (L3).

5.7 Video player (P0)

  • hls.js (with native HLS on Safari). Custom controls built on tokens: play/pause, ±10 s, speed 0.75–2×, quality (Auto / 240p / 360p / 480p / 720p), fullscreen, captions slot (P2), next lesson.
  • Data saver toggle, on by default when navigator.connection.saveData or effective type is 2g/3g: caps Auto at 360p.
  • Resumes from saved position.
  • Watermark: faint, slowly moving overlay with masked phone/email. Browsers can't block screen recording, so this is the deterrent.
  • Keyboard shortcuts (space, ←/→, f, m) and full screen-reader labels.

5.8 Progress tracking (P0)

  • Heartbeat every 15 s while playing, and on pause, lesson change, and visibilitychange/pagehide (via navigator.sendBeacon).
  • Lesson completed at ≥ 90% watched. Course progress = completed / published lessons.
  • Server keeps the maximum position; stale heartbeats never move progress backwards.
  • If sequentialLessons is on, the next lesson unlocks on completion (L12).

5.9 Notifications (P0)

  • In-app inbox (bell icon with unread count), mark read / mark all read.
  • Channels for the demo: in-app, email, SMS. Web push is P1.
  • Per-type opt-out in settings (payment receipts can't be turned off).

5.10 Help & issue reporting (P0, L9)

  • Help page: FAQ, Telegram link, phone number (both from admin Settings, both tested per L3), "Report a problem" form (type, subject, description, optional screenshot ≤ 5 MB).
  • My reports list with status. Student is notified when status changes.

5.11 Profile (P0)

  • Name, avatar (≤ 5 MB, jpg/png/webp, converted to WebP), phone, email, country/city (L5), language, notification settings, active sessions with sign-out, purchase history with receipts, delete account.

5.12 Empty, error and loading states (P0)

  • Every list has an empty state that tells the student what to do next.
  • Every fetch has a skeleton loading state and an error state with a retry button.
  • Video still processing → lesson shows "Coming soon", not playable.
  • Course archived after purchase → still fully accessible to owners.

6. Data model (Prisma)

File: packages/db/prisma/schema.prisma. IDs are cuid(). Timestamps UTC. Money is integer minor units (santim/cents), never floats. Deletes follow L15: onDelete: Restrict on anything with children or purchases.

generator client { provider = "prisma-client-js" }
datasource db { provider = "postgresql"; url = env("DATABASE_URL") }

enum Locale           { en am om ti }
enum Currency         { ETB USD }
enum UserStatus       { PENDING ACTIVE DEACTIVATED }
enum AdminRole        { SUPER_ADMIN CONTENT_MANAGER SUPPORT_AGENT FINANCE ANALYST }
enum CourseStatus     { DRAFT PUBLISHED ARCHIVED }
enum VideoStatus      { UPLOADING QUEUED PROCESSING READY FAILED }
enum OrderStatus      { PENDING PAID FAILED EXPIRED CANCELLED REFUNDED }
enum PaymentProvider  { ARIFPAY TELEBIRR CBE MANUAL APPLE_IAP GOOGLE_PLAY } // last two reserved for mobile
enum EnrollmentSource { PURCHASE ADMIN_GRANT FREE }
enum Channel          { IN_APP EMAIL SMS PUSH }
enum DeliveryStatus   { PENDING SENT FAILED }
enum IssueStatus      { OPEN IN_PROGRESS RESOLVED CLOSED }
enum IssueType        { BUG PAYMENT VIDEO ACCOUNT CONTENT OTHER }

model User {
  id           String     @id @default(cuid())
  phone        String?    @unique            // E.164
  email        String?    @unique
  emailVerifiedAt DateTime?
  passwordHash String?
  name         String?
  avatarKey    String?
  country      String?                       // ISO 3166-1 alpha-2
  city         String?                       // from ET list if country=ET, else free text (L5)
  locale       Locale     @default(am)
  status       UserStatus @default(PENDING)
  createdByAdminId String?                   // set when "Add student manually" (L10)
  createdAt    DateTime   @default(now())
  updatedAt    DateTime   @updatedAt
  deletedAt    DateTime?
  sessions     Session[]
  enrollments  Enrollment[]
  orders       Order[]
  progress     LessonProgress[]
  notifications Notification[]
  issues       Issue[]
  notificationPrefs Json?                    // { NEW_LESSON: { email: false }, ... }
  @@index([status, createdAt])
}

model Session {
  id          String   @id @default(cuid())
  userId      String
  user        User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  kind        String   // web | android | ios
  userAgent   String?
  ip          String?
  label       String?  // "Chrome on Android"
  pushToken   String?
  lastSeenAt  DateTime @default(now())
  revokedAt   DateTime?
  createdAt   DateTime @default(now())
  refreshTokens RefreshToken[]
  @@index([userId])
}

model RefreshToken {
  id        String   @id @default(cuid())
  sessionId String
  session   Session  @relation(fields: [sessionId], references: [id], onDelete: Cascade)
  familyId  String
  tokenHash String   @unique
  expiresAt DateTime
  revokedAt DateTime?
  createdAt DateTime @default(now())
  @@index([familyId])
}

model OtpCode {
  id         String   @id @default(cuid())
  target     String                          // phone or email
  purpose    String                          // LOGIN | VERIFY_EMAIL | RESET_PASSWORD
  codeHash   String
  attempts   Int      @default(0)
  expiresAt  DateTime
  consumedAt DateTime?
  createdAt  DateTime @default(now())
  @@index([target, purpose, createdAt])
}

model Admin {
  id           String    @id @default(cuid())
  email        String    @unique
  passwordHash String
  name         String
  role         AdminRole
  totpSecret   String?                       // required for SUPER_ADMIN and FINANCE
  isActive     Boolean   @default(true)
  lastLoginAt  DateTime?
  createdAt    DateTime  @default(now())
  auditLogs    AuditLog[]
}

model Category {
  id        String  @id @default(cuid())
  slug      String  @unique
  sortOrder Int     @default(0)
  isActive  Boolean @default(true)
  translations CategoryTranslation[]
  courses   Course[]
}

model CategoryTranslation {
  id         String   @id @default(cuid())
  categoryId String
  category   Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
  locale     Locale
  name       String
  @@unique([categoryId, locale])
}

model Course {
  id                   String       @id @default(cuid())
  slug                 String       @unique
  categoryId           String
  category             Category     @relation(fields: [categoryId], references: [id], onDelete: Restrict)
  instructorName       String
  instructionLocale    Locale
  coverImageKey        String?
  status               CourseStatus @default(DRAFT)
  isFeatured           Boolean      @default(false)
  isTest               Boolean      @default(false)   // L7: hidden from students and stats
  sequentialLessons    Boolean      @default(false)   // L12
  prerequisiteCourseId String?                        // L12
  prerequisite         Course?      @relation("Prereq", fields: [prerequisiteCourseId], references: [id], onDelete: SetNull)
  dependents           Course[]     @relation("Prereq")
  publishedAt          DateTime?
  createdAt            DateTime     @default(now())
  updatedAt            DateTime     @updatedAt
  translations         CourseTranslation[]
  prices               CoursePrice[]
  chapters             Chapter[]
  enrollments          Enrollment[]
  orders               Order[]
  @@index([status, isTest, publishedAt])
}

model CourseTranslation {
  id          String @id @default(cuid())
  courseId    String
  course      Course @relation(fields: [courseId], references: [id], onDelete: Cascade)
  locale      Locale
  title       String
  subtitle    String?
  description String                          // markdown
  audience    String?                         // "Who it's for" (added 2026-10-06, Logosmental reference)
  outcomes    String[]                        // "What you'll be able to do"
  @@unique([courseId, locale])
}

model CoursePrice {
  id          String   @id @default(cuid())
  courseId    String
  course      Course   @relation(fields: [courseId], references: [id], onDelete: Cascade)
  currency    Currency
  amountMinor Int
  @@unique([courseId, currency])
}

model Chapter {
  id        String @id @default(cuid())
  courseId  String
  course    Course @relation(fields: [courseId], references: [id], onDelete: Restrict)
  sortOrder Int
  translations ChapterTranslation[]
  lessons   Lesson[]
  @@index([courseId, sortOrder])
}

model ChapterTranslation {
  id        String  @id @default(cuid())
  chapterId String
  chapter   Chapter @relation(fields: [chapterId], references: [id], onDelete: Cascade)
  locale    Locale
  title     String
  summary   String?                           // "Why it matters" line
  @@unique([chapterId, locale])
}

model Lesson {
  id          String  @id @default(cuid())
  chapterId   String
  chapter     Chapter @relation(fields: [chapterId], references: [id], onDelete: Restrict)
  sortOrder   Int
  isPreview   Boolean @default(false)
  isPublished Boolean @default(false)
  videoId     String? @unique
  video       Video?  @relation(fields: [videoId], references: [id])
  translations LessonTranslation[]
  progress    LessonProgress[]
  createdAt   DateTime @default(now())
  @@index([chapterId, sortOrder])
}

model LessonTranslation {
  id          String @id @default(cuid())
  lessonId    String
  lesson      Lesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
  locale      Locale
  title       String
  description String?
  @@unique([lessonId, locale])
}

model Video {
  id            String      @id @default(cuid())
  sourceKey     String
  hlsPrefix     String?
  status        VideoStatus @default(UPLOADING)
  durationSec   Int?
  renditions    Json?
  thumbnailKey  String?
  keyCipher     Bytes?                        // AES-128 key, encrypted with APP_KEK
  errorMessage  String?
  sizeBytes     BigInt?
  createdAt     DateTime    @default(now())
  updatedAt     DateTime    @updatedAt
  lesson        Lesson?
}

model Enrollment {
  id        String           @id @default(cuid())
  userId    String
  user      User             @relation(fields: [userId], references: [id], onDelete: Cascade)
  courseId  String
  course    Course           @relation(fields: [courseId], references: [id], onDelete: Restrict)
  source    EnrollmentSource
  orderId   String?          @unique
  grantedByAdminId String?
  revokedAt DateTime?
  createdAt DateTime         @default(now())
  @@unique([userId, courseId])
}

model Order {
  id             String          @id @default(cuid())
  userId         String
  user           User            @relation(fields: [userId], references: [id])
  courseId       String
  course         Course          @relation(fields: [courseId], references: [id], onDelete: Restrict)
  currency       Currency
  amountMinor    Int                           // snapshot of price at checkout
  provider       PaymentProvider
  method         String?                       // e.g. TELEBIRR, CBE_BIRR, AMOLE via ArifPay
  status         OrderStatus     @default(PENDING)
  providerRef    String?                       // ArifPay session id
  idempotencyKey String          @unique
  checkoutUrl    String?
  failureReason  String?
  flaggedReason  String?                       // amount mismatch etc.
  paidAt         DateTime?
  expiresAt      DateTime
  createdAt      DateTime        @default(now())
  updatedAt      DateTime        @updatedAt
  events         PaymentEvent[]
  @@index([userId, status])
  @@index([status, createdAt])
  @@unique([provider, providerRef])
}

model PaymentEvent {
  id          String          @id @default(cuid())
  orderId     String?
  order       Order?          @relation(fields: [orderId], references: [id])
  provider    PaymentProvider
  eventId     String
  type        String
  payload     Json
  signatureOk Boolean
  processedAt DateTime?
  createdAt   DateTime        @default(now())
  @@unique([provider, eventId])
}

model LessonProgress {
  id             String    @id @default(cuid())
  userId         String
  user           User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  lessonId       String
  lesson         Lesson    @relation(fields: [lessonId], references: [id], onDelete: Cascade)
  positionSec    Int       @default(0)
  maxPositionSec Int       @default(0)
  completedAt    DateTime?
  updatedAt      DateTime  @updatedAt
  @@unique([userId, lessonId])
}

model NotificationCampaign {                   // L8: admin-composed sends
  id            String    @id @default(cuid())
  createdById   String
  channels      Channel[]
  audience      Json                          // { type: "ALL" | "COURSE_BUYERS" | "USERS", courseId?, userIds? }
  content       Json                          // { en: {title, body}, am: {...}, ... }
  scheduledAt   DateTime?
  sentAt        DateTime?
  status        String    @default("DRAFT")   // DRAFT | SCHEDULED | SENDING | SENT | FAILED
  createdAt     DateTime  @default(now())
  deliveries    NotificationDelivery[]
}

model NotificationDelivery {
  id          String          @id @default(cuid())
  campaignId  String?
  campaign    NotificationCampaign? @relation(fields: [campaignId], references: [id])
  userId      String
  channel     Channel
  status      DeliveryStatus  @default(PENDING)
  error       String?
  sentAt      DateTime?
  @@index([campaignId, status])
}

model Notification {                           // in-app inbox item
  id        String    @id @default(cuid())
  userId    String
  user      User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  type      String
  title     String
  body      String
  link      String?
  readAt    DateTime?
  createdAt DateTime  @default(now())
  @@index([userId, readAt, createdAt])
}

model Issue {                                  // L9
  id            String      @id @default(cuid())
  userId        String?
  user          User?       @relation(fields: [userId], references: [id])
  reportedByAdminId String?                   // admin can log an issue on a student's behalf
  type          IssueType
  subject       String
  description   String
  screenshotKey String?
  status        IssueStatus @default(OPEN)
  assignedToId  String?
  resolutionNote String?
  createdAt     DateTime    @default(now())
  updatedAt     DateTime    @updatedAt
  @@index([status, createdAt])
}

model Setting {                                // support phone, Telegram link, session limit, etc.
  key       String   @id
  value     Json
  updatedAt DateTime @updatedAt
}

model AuditLog {
  id        String   @id @default(cuid())
  adminId   String?
  admin     Admin?   @relation(fields: [adminId], references: [id])
  action    String                            // course.publish, enrollment.grant, order.refund ...
  entity    String
  entityId  String
  before    Json?
  after     Json?
  ip        String?
  userAgent String?
  createdAt DateTime @default(now())
  @@index([entity, entityId])
  @@index([adminId, createdAt])
  @@index([action, createdAt])
}

Rules:

  • Translation fallback: requested locale → en → first available. Admin warns on missing locales before publish.
  • isTest courses are excluded from every student query and every stat (L7). Enforce in one Prisma extension or query helper, not per call site.
  • Order.amountMinor is a snapshot; later price changes never affect existing orders.

7. API contract

Base /v1. JSON only. Bodies validated with Zod schemas from packages/shared, exported to OpenAPI at /v1/docs (non-production). Locale from Accept-Language.

Error envelope:

{ "error": { "code": "COURSE_NOT_OWNED", "message": "Localized message", "fields": { "email": "INVALID_FORMAT" } } }

Validation errors return field-level codes (as Yimaru VAL-01). Error codes are constants in packages/shared/errors.ts.

Pagination: cursor based, ?cursor=&limit=20 → { items, nextCursor }. Admin tables also return totalCount.

7.1 Student

Method Path Notes
POST /auth/otp/request {target, purpose} → 204, rate limited
POST /auth/otp/verify → sets cookies (web) or returns tokens (bearer clients)
POST /auth/email/register · /auth/email/login
POST /auth/password/reset/request · /verify · /complete
POST /auth/refresh · /auth/logout
GET/PATCH/DELETE /me profile; delete = soft delete, anonymize after 30 days
GET /me/sessions · DELETE /me/sessions/:id
GET /locations/et-cities L5
GET /home one call for the home screen
GET /categories · /courses?q=&category=&cursor= · /courses/:slug public
GET /me/courses · /me/progress
GET /lessons/:id/playback entitlement check → signed manifest URL
PUT /lessons/:id/progress heartbeat; accepts sendBeacon text/plain body
GET /payment-methods?courseId=
POST /orders {courseId, method, idempotencyKey} → {orderId, checkoutUrl}
GET /orders/:id · /me/orders
GET /me/notifications · POST /me/notifications/:id/read · POST /me/notifications/read-all · GET /me/notifications/unread-count
POST /issues · GET /me/issues L9
GET /settings/public support phone, Telegram link, etc.
GET /keys/:videoId?t= HLS key, re-checks entitlement

7.2 Webhooks

POST /webhooks/arifpay (and later /telebirr, /cbe): verify signature → insert PaymentEvent (unique provider+eventId makes duplicates no-ops) → enqueue payment.process → return 200 quickly.

7.3 Admin (/v1/admin/*, RBAC per route, every mutation audited)

Categories CRUD + archive · Courses CRUD + publish/unpublish/archive + translations + prices + prerequisite · Chapters/lessons CRUD + reorder · Videos: start upload, complete, status, retry · Students: list with filters (status, country, city, enrolled course, joined date), detail, activate/deactivate, add student manually, sessions revoke · Enrollments: grant/revoke · Orders: list/filter/detail/CSV export/mark refunded · Notifications: campaigns create/schedule/send/list/detail · Issues: list/filter/assign/update status/create on behalf · Dashboard & analytics endpoints (§10.3) · Settings get/update · Admins CRUD · Audit log list with filters.

7.4 Cross-cutting

  • Rate limits (Redis): OTP 5/h per target and 20/h per IP; login 10 per 15 min per IP; general 300/min per user.
  • helmet, strict CORS (only the web and admin origins), 1 MB JSON body limit (uploads go to R2 directly).
  • Request ID on every log line and error response.

8. Payments

8.1 Adapter design

One interface, one adapter per provider, in apps/api/src/payments/. Order and enrollment code never knows which provider is used.

interface PaymentAdapter {
  id: PaymentProvider;
  methods(ctx: { currency: Currency }): Promise<PaymentMethodInfo[]>;
  createCheckout(order: Order, user: User): Promise<{ checkoutUrl: string; providerRef: string }>;
  verifyWebhook(req: RawRequest): Promise<VerifiedEvent | null>;
  queryStatus(order: Order): Promise<'PAID' | 'FAILED' | 'PENDING'>;
}

8.2 Providers for the demo

Provider Status Notes
ArifPay P0 Hosted checkout session + webhook + verify-by-session. Port the flow from Yimaru (PAY-01 to PAY-08). Covers Telebirr, CBE Birr and other local methods; confirm the exact list on the client's merchant account. Verify field names against current ArifPay docs.
ArifPay direct (OTP) payment P1 Yimaru PAY-09/10. Student pays without leaving the site.
Telebirr / CBE direct P2 Only if the client wants to avoid aggregator fees later. Same adapter interface.
International (USD) DECISION NEEDED D3 Confirm whether the client's ArifPay account accepts international cards. Otherwise defer.

On the web there are no app store billing rules. That issue returns only when the Flutter apps are built (§16).

8.3 Order state machine

PENDING ──verified webhook / reconcile PAID──▶ PAID ──admin mark refunded──▶ REFUNDED
   ├── verified FAILED ──▶ FAILED
   ├── student cancels ──▶ CANCELLED
   └── 30 min passed ────▶ EXPIRED
  • → PAID and the Enrollment insert happen in one transaction and are idempotent.
  • Never unlock from the browser's return URL. The return page only shows status; unlock comes from a verified webhook or a server-side queryStatus.
  • Webhook amount and currency must equal the order's. Mismatch → flaggedReason set, no unlock, admin alert.
  • Reconciliation job every 2 min checks PENDING orders older than 2 min.
  • A student who already owns a course can't create another order for it.
  • On PAID: in-app notification + SMS + emailed receipt.

8.4 Testing payments (L7)

  • Staging uses ArifPay sandbox.
  • Real-money tests in production use isTest courses priced at the provider minimum, bought by a staff account, then marked refunded. They never appear to students or in stats.

9. Video system

9.1 Upload

  1. Admin picks a file (MP4/MOV/MKV, ≤ 10 GB; type checked by magic bytes after the first part, L16).
  2. POST /admin/videos/uploads → Video{UPLOADING} + R2 multipart upload + presigned part URLs (100 MB parts).
  3. Browser uploads parts directly to R2 with a progress bar; resumes after a network drop.
  4. POST /admin/videos/:id/complete → QUEUED → enqueue video.transcode.

9.2 Transcoding (worker)

  • ffprobe to validate and read duration → generate random 16-byte AES key, encrypt with APP_KEK, store on Video → FFmpeg to HLS:
    • 240p @ 300 kbps, 360p @ 600 kbps, 480p @ 1 Mbps, 720p @ 2.2 Mbps (skip renditions above source height). AAC 64 kbps mono for 240/360, 96 kbps stereo above.
    • H.264 main profile, keyframe every 2 s, 6 s segments, hls_playlist_type vod, AES-128 via -hls_key_info_file.
  • Thumbnail at 10% of duration (WebP).
  • Upload output to hls/{videoId}/ in the private bucket → READY. Keep the source for re-encoding.
  • 3 retries with backoff; then FAILED with message, retry button in admin.

9.3 Secure playback

  1. Web app calls GET /lessons/:id/playback.
  2. API checks: user active, session valid, lesson is a preview or active enrollment exists, sequential/prerequisite rules pass, video READY.
  3. Returns manifestUrl = https://media.<domain>/hls/{videoId}/master.m3u8?t=<token> where the token is an HMAC of {videoId, userId, sessionId, exp: now + 4h}.
  4. Cloudflare Worker validates the token on every request, reads from private R2, and rewrites URIs inside .m3u8 files to carry the token.
  5. Key URI → GET /v1/keys/{videoId}?t= re-checks entitlement live and returns the key. This is the real enforcement point.
  6. Revoking a session or enrollment stops new key fetches immediately.

Tell the client plainly: this stops link sharing and casual downloading. It is not studio DRM, and no website can stop a screen recorder; the watermark discourages it.


10. Admin panel

Next.js 15 App Router, packages/ui components, TanStack Query + TanStack Table, react-hook-form + shared Zod schemas. Desktop-first, usable on a tablet. English UI (Amharic P1).

10.1 Roles (fixed for the demo, L11)

Capability SUPER_ADMIN CONTENT_MANAGER SUPPORT_AGENT FINANCE ANALYST
Categories, courses, chapters, lessons, videos ✅ ✅ view view view
Prices, test flag ✅ ❌ ❌ ✅ ❌
Students: view, filter ✅ ❌ ✅ view aggregate only
Students: add manually, activate/deactivate ✅ ❌ ✅ ❌ ❌
Grant / revoke course access ✅ ❌ ✅ ❌ ❌
Orders & revenue ✅ ❌ view (no totals) ✅ view
Mark refunded ✅ ❌ ❌ ✅ ❌
Notifications ✅ ✅ ✅ ❌ ❌
Issues ✅ view ✅ view (payment type) ❌
Dashboard ✅ content cards support cards ✅ ✅
Analytics ✅ ❌ ❌ ✅ ✅
Settings, admins, audit log ✅ ❌ ❌ ❌ ❌

Login: email + password; TOTP 2FA required for SUPER_ADMIN and FINANCE. httpOnly session cookie on the admin domain. Every mutation writes an AuditLog with IP and user agent.

Navigation shows only what the role can use. Hidden, not disabled (L3).

10.2 Screens

Dashboard · Analytics · Courses · Categories · Students · Orders · Notifications · Issues · Settings · Admins · Audit log.

10.3 Dashboard and Analytics (L6)

Global time filter on both pages: All time / Year (dropdown) / Year + month (two dropdowns). All cards respect it except "right now" cards, which are labeled as such.

Dashboard (operational, what needs attention today):

Card Definition
Total students Users with status ACTIVE or DEACTIVATED created in the period
Active students Users with ≥ 1 progress heartbeat in the period
Paying students Distinct users with ≥ 1 PAID order in the period
Revenue (ETB) Sum of PAID orders in the period minus REFUNDED, excluding isTest. USD shown separately; currencies are never added together
Orders needing attention PENDING > 10 min + flagged orders (right now)
Videos processing / failed Right now
Open issues OPEN + IN_PROGRESS (right now)

Analytics (trends):

  • Revenue trend: monthly bars for a selected year (year dropdown).
  • New students per month.
  • Top courses by revenue and by enrollments.
  • Course completion rate per course.
  • Videos: total published, total watch hours (from heartbeats).
  • Payment method split.

10.4 Course editor

Tabs: Details (translation tabs per locale with missing-locale badges, category, instructor, language of instruction, cover image, prerequisite, sequential lessons toggle, featured, test flag) · Pricing · Curriculum (drag-and-drop chapters and lessons, per-lesson upload with progress, processing status, preview player, preview flag, publish toggle) · Students (enrolled list).

Publish checklist (button disabled with reasons listed): English title and description, cover image, ≥ 1 published lesson with a READY video, ETB price set.

10.5 Notifications (L8)

  • Compose: title and body per locale (English required, others fall back), channels (in-app / email / SMS, multi-select), audience (all students / buyers of a course / specific students / students in a city), send now or schedule.
  • Preview before sending with a recipient count and an SMS cost estimate.
  • History table: date, title, channels, audience, status, sent/failed counts. Filters by date, channel, status, audience.
  • Detail page: full message, channels, per-channel delivery breakdown (sent / failed / pending), failed recipients list with error, "Retry failed".
  • Automatic notifications (payment confirmed, new lesson in owned course, issue status changed) use the same delivery pipeline and appear in the history as "System".

10.6 Students (L10)

  • Table with filters: status, country, city, enrolled course, joined date range, has paid.
  • Detail: profile, sessions (revoke), enrollments (grant/revoke), orders, progress per course, issues.
  • Add student manually: helper text "Use this for students who pay in person or by phone. They'll get an SMS to set up their account." Creates user + optional course grant.
  • Activate / deactivate with a required reason (stored in audit log).

10.7 Issues (L9)

Table with filters (status, type, date, assignee) · detail with screenshot, student info and order links · assign · change status with resolution note (student notified) · "Log an issue for a student".

10.8 Settings

Support phone, Telegram link, support email, session limit, OTP settings (read-only), maintenance banner text. Each link field has a "Test" button (L3).


11. Design direction

11.1 Inspiration

  • Put inspiration references in design/inspo/ (screenshots + README.md with links and one line on what to take from each: layout, type, a specific interaction). DECISION NEEDED D9: the inspiration board or plugin to pull from.
  • If the client has a Figma file, it wins over everything in this section. Figma = layout source of truth; design/assets = asset source of truth (L14).
  • Before building UI, Claude reads design/inspo/README.md, writes a short token plan (palette, type, layout, principles), checks it against generic defaults, then builds. Use the Design plugin skills for design critique, UX copy and accessibility review at the end of each UI task.

11.2 Provisional direction (replace with client branding when available)

The subject is learning in Ethiopian languages on a phone. The one bold element is Ge'ez type: course and chapter headings in Amharic/Tigrinya are set large and given room, so the script itself is the visual identity. Everything around it stays quiet.

Token Value Use
Ink #1B2340 Text, primary buttons
Paper #FFFFFF Background
Mist #EEF1F6 Surfaces, inputs
Adey yellow #F2B705 Single accent: progress, "Continue", focus ring (inspired by the Meskel daisy)
Highland green #2E7D5B Success, completed lessons
Alert red #C2362B Errors only
  • Type: Noto Serif Ethiopic for Ge'ez headings, Noto Sans Ethiopic for Ge'ez body, Atkinson Hyperlegible for Latin (built for legibility on small, low-quality screens). Loaded with next/font, subset, font-display: swap.
  • Type scale: 14 / 16 / 20 / 25 / 31 / 39 px. Ethiopic line-height 1.7, Latin 1.5.
  • Layout: single column on phones, max line length ~70 characters. Course cards vary by role: the "Continue" card is wide and prominent; catalog cards are compact.
  • Avoid: identical rounded-card grids everywhere, gradient washes, all-caps eyebrow labels, decorative motion. One purposeful motion moment: the progress ring filling on lesson completion. Respect prefers-reduced-motion.
  • Admin is plain and dense: same tokens, smaller type, tables first.

11.3 Tokens in code

design/tokens.json → generated CSS variables + Tailwind preset in packages/config. Components never use raw hex values. Dark mode is P2.

11.4 Copy rules

Sentence case. Buttons say what they do ("Buy course", "Resume lesson 4"), and the confirmation uses the same verb ("Course bought"). Errors say what happened and what to do, without apologizing. Empty states point to the next action.


12. Localization

  • Locales: en, am (Ge'ez script), om (Latin, Qubee), ti (Ge'ez script). Default am (DECISION NEEDED D7).
  • UI strings in packages/i18n/messages/{locale}.json (ICU format via next-intl). English is the template; CI fails on missing keys. Untranslated strings fall back to English and are listed in a CI report.
  • Translators never edit JSON: pnpm i18n:export → spreadsheet, pnpm i18n:import ← spreadsheet.
  • Content (courses, chapters, lessons, categories, notifications, emails) uses the translation tables.
  • Dates: Gregorian in the demo; Ethiopian calendar display is P2. Currency formatted as ETB 1,200 / $25.00.
  • Test every screen in Amharic at 360 px width; Ge'ez strings often run longer and taller than English.

13. Test plan (Yimaru format)

13.1 Strategy

        ┌─────────┐
        │  E2E    │  Playwright: student + admin flows, click-everything smoke test
       ┌┴─────────┴┐
       │ API/integ  │  Fastify inject + real Postgres (Testcontainers)
      ┌┴────────────┴┐
      │  Service      │  Vitest, adapters mocked
     ┌┴──────────────┴┐
     │ Domain/utils    │  Pure unit tests
     └────────────────┘

External services (ArifPay, AfroSMS, Resend, R2) are stubbed in tests; recorded sandbox payloads are used for webhook tests. Each suite runs in a transaction that rolls back. Seed fixtures: one user per role, categories, courses (published, draft, test, prerequisite-linked), a short sample video.

Priorities: P0 Auth, payments, entitlement, video access · P1 Content CRUD, video pipeline, progress, students · P2 Notifications, issues, dashboard, settings · P3 Audit log, analytics.

13.2 Module cases

ID Case Expected
AUTH-01 OTP request, valid phone 204, SMS stub called once
AUTH-02 OTP verify wrong code ×5 Code locked
AUTH-03 OTP expired 400 OTP_EXPIRED
AUTH-04 Email register, duplicate email 409 EMAIL_TAKEN
AUTH-05 Password with 8 letters only Accepted (L4)
AUTH-06 Login deactivated user 403 ACCOUNT_DEACTIVATED
AUTH-07 Refresh token reuse Whole family revoked
AUTH-08 Third session 409 SESSION_LIMIT with session list
AUTH-09 Password reset full flow 200 at each step, old sessions revoked
AUTH-10 OTP email sender From name is brand name (L2)
AUTH-11 State-changing request with foreign Origin 403
RBAC-01..n Every admin route × every role Matches §10.1 table exactly (generated test)
USR-01 Profile country=ET, city not in list 400 (L5)
USR-02 Profile country=KE, free-text city 200
USR-03 Avatar 6 MB 400
USR-04 Avatar .exe renamed .jpg 400 (magic bytes, L16)
USR-05 Admin adds student manually User created, SMS sent, audit logged
CRS-01 Publish without checklist 400 with missing items
CRS-02 Delete course with enrollments 409, suggests archive (L15)
CRS-03 Delete category with courses 409 (L15)
CRS-04 isTest course in public list/search/stats Never present (L7)
CRS-05 Prerequisite not completed Course page shows notice; playback blocked
CRS-06 Sequential lessons, lesson 3 before 2 completed LESSON_LOCKED
CRS-07 Reorder lessons Order persisted, no duplicates
VID-01 Upload + complete QUEUED → READY, renditions present
VID-02 Corrupt file FAILED with message; retry works
VID-03 Source 480p No 720p rendition
SEC-01 Manifest without token 403
SEC-02 Token for video A on video B 403
SEC-03 Expired token 403
SEC-04 Key request after enrollment revoked 403 immediately
SEC-05 Key request after session revoked 403
SEC-06 Direct R2 object URL Not reachable
SEC-07 Non-owner playback of paid lesson COURSE_NOT_OWNED
PAY-01 Create order 201, checkoutUrl, PENDING
PAY-02 Valid webhook PAID Order PAID + Enrollment in one transaction
PAY-03 Same webhook twice One enrollment
PAY-04 Bad signature 401, no state change
PAY-05 Amount mismatch Not unlocked, flagged, alert
PAY-06 Browser hits return URL, provider still pending Not unlocked
PAY-07 Webhook missed Reconciliation unlocks within 3 min
PAY-08 Order for owned course 409 ALREADY_OWNED
PAY-09 Concurrent double-click checkout (same idempotency key) One order
PAY-10 Order expires EXPIRED after 30 min
PRG-01 Heartbeat older position than stored Max position unchanged
PRG-02 90% watched Lesson completed, course % updated
PRG-03 sendBeacon text/plain body Accepted
NOT-01 Campaign to course buyers, 3 channels Deliveries created per user × channel
NOT-02 SMS provider fails for one user That delivery FAILED, others SENT, retry works
NOT-03 Student opted out of email for NEW_LESSON No email delivery
NOT-04 Unread count Correct after read / read-all
ISS-01 Student creates issue with screenshot 201, appears in admin
ISS-02 Admin resolves Student notified
DSH-01 Time filter Year=2026 All period cards use 2026 only
DSH-02 ETB and USD revenue Never summed
DSH-03 Refunded order Subtracted from revenue
LOG-01 Every admin mutation Audit entry with actor, IP, UA, before/after
LOG-02 Filter by actor + action + date Correct subset

13.3 End-to-end flows (Playwright, run against staging)

  1. Student: land → switch to Amharic → OTP sign-up → profile (Ethiopia + city dropdown) → browse → preview lesson → buy (ArifPay sandbox) → auto-unlock → watch → progress saved → resume next day.
  2. Admin content: login + 2FA → create category → create course (4 locales) → upload video → wait READY → publish → visible to student.
  3. Support: student reports issue → agent resolves → student sees notification.
  4. Notifications: compose to buyers of a course, SMS + email + in-app → delivery detail shows counts.
  5. Manual sale: support adds student manually + grants course → student receives SMS → signs in → course is in My Courses.

13.4 Upload and input security

Spoofed content type rejected by magic bytes · filenames replaced with UUIDs · null bytes and path traversal in names handled · per-type size limits (avatar 5 MB, cover 10 MB, screenshot 5 MB, video 10 GB) · malformed JSON → 400 · oversized JSON body → 413.

13.5 Click-everything smoke test (L3)

A Playwright crawler signs in as a student and as each admin role, visits every route, clicks every visible a and button, and fails if any click produces: no navigation and no visible state change, a 404/500, an unhandled console error, or a blank main region. Runs on every PR against a seeded preview.

13.6 Performance and quality budgets

Metric Target
LCP, course page, mid-range Android, 4G < 2.5 s
Initial JS on student pages < 170 KB gzipped
API p95, read endpoints < 200 ms
/home payload < 50 KB gzipped
Video start p75 (4G) < 4 s
Lighthouse accessibility ≥ 95; WCAG 2.1 AA manual check on key flows

k6 load test before demo: 100 concurrent students browsing + 20 streaming + 10 checkouts.


14. Engineering conventions

  • TypeScript strict. No any without a comment explaining why.
  • Validate every external input with Zod at the boundary; infer types from schemas.
  • Route handlers parse → call service → map result. Business logic lives in services/.
  • Anything touching money or access is transactional and idempotent.
  • prisma migrate only; never edit an applied migration.
  • Feature flags (packages/shared/flags.ts, values from Settings) hide unfinished UI (L3).
  • Secrets only from environment; .env.example lists every variable with a comment.
  • Logging: pino JSON with request ID. Sentry in api, worker, web, admin.
  • Conventional Commits. One PR per task ID in §15. PR description lists acceptance criteria and test IDs covered.
  • CI: lint, typecheck, unit + integration tests, i18n key check, Playwright smoke test, Lighthouse CI on preview. All must pass before merge.
  • No new dependencies without a line in the PR explaining why.
  • Seed script: one admin per role, 3 categories, 4 courses (published, draft, test, prerequisite-linked) with all 4 locales (placeholder text allowed), Ethiopian city list, sample short videos.

15. Build order (web demo)

Each phase ends in something the client can click through. Task IDs are used in branches and PRs.

Day 1 — client-side, in parallel (blocks Phase 2)

  • ArifPay merchant account (or confirm Yimaru-style sandbox credentials for this client) and list of enabled methods.
  • AfroSMS sender ID approved with the brand name.
  • Sending domain for Resend (DNS access for SPF/DKIM/DMARC).
  • Branding, Figma (if any) and inspiration board (D9).
  • 2–3 real videos and one complete course structure.

Phase 0 — Claude-hosted demo (~1–2 weeks, see §18)

Demo: the client opens a Claude link, browses courses in Amharic, "buys" a course with a simulated Telebirr checkout, watches lessons, and uses the admin panel. They leave feedback as comments on the screens.

ID Task
C0-01 Token plan and design review (§11), using the inspiration board
C0-02 apps/demo Next.js shell: static export config, hash router, next-intl in client mode (4 locales), Google Fonts, tokens, role detection; artifact-inline + artifact-check in CI
C0-02b packages/data: DataSource interface + ClaudeDbDataSource (production ApiDataSource is stubbed until W1-03)
C0-03 Student screens: landing, home, catalog, search, course page, player, My Courses, progress, profile, help/issues, notifications
C0-04 Simulated OTP sign-in and simulated checkout following the real state machine
C0-05 Admin screens: dashboard, analytics, courses + curriculum + video upload, students, orders, notifications, issues, settings
C0-06 Seed data via the ArtifactData tool (categories, 4 courses in 4 locales, compressed sample clips)
C0-07 Comment-based UAT round with the client; fix, reply, resolve
C0-08 Freeze: export final data shapes and copy to packages/db/seed and packages/i18n for the production build

Exit: client signs off on screens, flows and copy. Their comments become the UAT baseline for Phase 3.

Phase 1 — Foundation and content loop (~3–4 weeks)

Demo: admin creates a course and uploads a video; a student signs up in Amharic and watches a free preview lesson securely.

ID Task
W1-01 Monorepo, CI, docker-compose (Postgres, Redis, MinIO, Mailpit), .env.example, root scripts from "How to work"
W1-02 Prisma schema (§6), migrations, seed
W1-03 API skeleton: Fastify, Zod, error envelope, logging, health checks, OpenAPI, rate limits
W1-04 Design tokens, packages/ui base components, fonts (§11)
W1-05 i18n package, 4 locales, export/import scripts (§12)
W1-06 Student auth: OTP (AfroSMS adapter + console adapter for dev), email/password, reset, sessions, session limit, branded emails
W1-07 Admin auth, 2FA, RBAC middleware + generated RBAC tests, audit log
W1-08 Admin: categories, courses, chapters, lessons, translations, reorder, publish checklist
W1-09 Video: multipart upload, worker transcode to encrypted HLS, status, retry
W1-10 Edge Worker, key endpoint, /lessons/:id/playback, SEC-01..07 tests
W1-11 Web: landing, home, categories, search, course page
W1-12 Web: player (hls.js, quality, data saver, watermark) with preview lessons
W1-13 Web: profile (country/city L5), sessions, language switch, delete account
W1-14 Click-everything smoke test wired into CI

Phase 2 — Payments, ownership, progress, operations (~3–4 weeks)

Demo: student pays with Telebirr through ArifPay sandbox, course unlocks automatically, progress and resume work; admin sees the order and the dashboard.

ID Task
W2-01 Payment adapter interface, order service, state machine, webhook ingestion, reconciliation job
W2-02 ArifPay adapter (port flow from Yimaru, verify against current docs), PAY-01..10
W2-03 Checkout UX: method choice, redirect, order status page, receipts
W2-04 Enrollments, My Courses, entitlement for paid lessons, prerequisites and sequential lessons
W2-05 Progress heartbeats, completion, resume, My Progress page
W2-06 Admin: students (filters, detail, add manually, activate/deactivate), grant/revoke
W2-07 Admin: orders (filters, detail with event timeline, flagged, CSV, mark refunded)
W2-08 Admin: dashboard + analytics with time filter (§10.3)

Phase 3 — Notifications, support, polish, demo deploy (~2–3 weeks)

Demo: complete platform on a staging URL the client can share.

ID Task
W3-01 Notification pipeline (in-app, email, SMS), preferences, automatic notifications
W3-02 Admin notifications: compose, preview, schedule, history, delivery detail, retry
W3-03 Issues: student report + admin triage + status notifications
W3-04 Settings page with tested support links
W3-05 PWA manifest and icons (P1)
W3-06 Performance and accessibility pass against §13.6; design critique + UX copy review
W3-07 Staging/production deploy, backups + restore drill, Sentry alerts
W3-08 Real-money test with an isTest course (L7), then refund
W3-09 UAT with the client using a shared sheet in the Yimaru UAT format (UX issues / UI issues / status / comment)
W3-10 Admin guide (short) and a 1-hour client training session

Done means: all P0 tests in §13 pass, smoke test green, zero open P0/P1 UAT items, and the client has published a course and completed a test sale without developer help.


16. After the demo: adding Flutter

The API is already client-agnostic (bearer auth, Session.kind, pushToken, JSON-only). When mobile starts:

  • Build the Flutter app against the same /v1 endpoints.
  • Add FCM push as a fourth delivery channel (the PUSH enum value already exists).
  • Decide app store billing (Apple and Google generally require their own in-app billing for digital content bought in-app; rules vary by country and have changed recently, so verify then). APPLE_IAP and GOOGLE_PLAY provider values are reserved.
  • Add FLAG_SECURE (Android) and screen-capture detection (iOS).

Other future items and what already supports them: offline downloads (encrypted HLS + per-session keys), studio DRM (single Worker + key endpoint to swap), quizzes (add Lesson.type), subscriptions (add EnrollmentSource.SUBSCRIPTION; Yimaru's subscription plan design can be reused), coupons (orders already snapshot price), custom roles (replace enum with a permissions table).


17. Decisions log

# Decision Owner Blocks
D1 Backend language: Node/TS (client scope) or reuse Yimaru Go modules You + client W1-03
D2 ArifPay account for this client, enabled methods, fees Client W2-02
D3 USD / international payments in the demo or later Client Nothing in demo if deferred
D4 AfroSMS sender ID and SMS budget Client W1-06 production
D5 Session limit (default 2) Client —
D6 Lifetime access vs. time-limited Client — (default lifetime)
D7 Default locale (am assumed) Client —
D8 Hosting provider and budget You + client W3-07
D9 Inspiration board / plugin source and client branding. Partly decided 2026-10-06: Logosmental LMS is the structural reference for admin + course pages (design/inspo/README.md); client branding still open You + client W1-04
D10 Receipt and VAT requirements Client's accountant W3-08
D11 Refund policy Client —
D12 Who gets access to the Claude-hosted demo (org members and invited guests only) and which client emails to invite You + client C0-07

18. Claude-hosted demo (artifact)

18.1 Purpose

A working, clickable version of the whole platform, hosted on Claude, used to agree on screens, flows, copy and languages with the client before the production build. It is not production: it has no real payments, SMS, email or video encryption, and only people in your Claude organization or invited guests can open it.

18.2 What maps to what

Production (§3–§10) Claude-hosted demo
Next.js web + admin apps/demo: a Next.js 15 app (static export) with one page that renders the shared screens from packages/features, using hash routing (#/am/... student, #/admin/... admin). The export is inlined into one HTML file and published
Fastify API + Postgres db capability (shared documents and collections)
R2 + FFmpeg + HLS + Worker assets capability: short sample clips (≤ 20 MiB each, pre-compressed to 360p/480p MP4 with FFmpeg locally) played in <video>. No encryption
Phone OTP / email login user capability (viewer's Claude identity). The OTP screen is kept for UX review and shows the demo code on screen, so it still works (L3)
ArifPay Simulated checkout screen ("Telebirr (demo)", "CBE Birr (demo)") with Pay and Fail buttons. It drives the same order states as §8.3: PENDING → PAID/FAILED/EXPIRED
Admin RBAC Owner and Editors = super admin. A "View as" switcher (owner only) previews each role's navigation from §10.1
SMS / email / push In-app inbox only. Notification delivery detail shows SMS and email rows labeled "Simulated"
CSV export downloads capability
UAT spreadsheet comments capability (composer_only). Every screen has a "Leave feedback" button that opens a comment pinned to that element
Audit log db collection written on each admin action

18.3 Capabilities to declare

{ db: { rules: [...] }, user: { scopes: ["profile"] }, assets: {}, comments: { composer_only: true }, downloads: true }

  • Load the artifact-capabilities skill and read its typed call definitions before writing code. They are authoritative over this spec. Capabilities are declared via the Artifact tool's capabilities input at publish time.
  • Every claude.use(...) call can return null. Render the page first, then light features up; hide a feature when its capability is absent.
  • Declaring assets makes the artifact organization-internal. Client reviewers must be invited (D12).
  • Optional P1: sample to draft Amharic, Oromo and Tigrinya translations of course descriptions in the admin editor, always marked "Draft — needs translator review".

18.4 Data layout in db

Use the same field names as the Prisma models in §6 so the data can be exported straight into the production seed (C0-08).

  • catalog/categories/*, catalog/courses/* (chapters and lessons embedded per course with videoAssetId), settings/app: everyone reads, admins write.
  • students/{userId}: profile, enrollments, orders, progress for one student. The student writes their own doc; admins read all.
  • issues/*, notifications/*, campaigns/*, audit/*: written per §10 rules.
  • Exact rule syntax for "student writes own, admins read all" must be checked in db.d.ts. If the runtime can't express it, fall back to "all signed-in viewers read" and show a banner that the demo uses no real personal data.
  • No hardcoded seed data in the page. Seed with the ArtifactData tool (batch writes) against the artifact URL after the first publish, and render a proper empty state when the db is empty.

18.5 Build rules

  • One HTML file under 16 MB. Scripts only from cdnjs, jsdelivr (/npm/), the Tailwind play CDN or code.jquery.com; fonts from Google Fonts (Noto Sans Ethiopic, Noto Serif Ethiopic, Atkinson Hyperlegible are all available there). Everything else is inlined.
  • Framework: Next.js 15 (App Router) + React 19, same versions as apps/web and apps/admin.
  • Shared code, swapped data layer. Screens live in packages/features and only talk to a DataSource interface (packages/data). Production passes ApiDataSource (calls /v1); the demo passes ClaudeDbDataSource (calls claude.use("db"), "user", "assets"). When Phase 1 starts, the screens move into apps/web/apps/admin unchanged; only the data source changes.
  • Build pipeline:
    1. next build with output: 'export', images: { unoptimized: true }, and for the client bundle splitChunks: false and runtimeChunk: false (Appendix A.1).
    2. node tools/artifact-inline.mjs apps/demo/out dist/demo.html (Appendix A.2) inlines every /_next script and stylesheet, drops preloads, and fails if any asset is left un-inlined or the file exceeds 15 MB.
    3. node tools/artifact-check.mjs dist/demo.html (Appendix A.3, needs jsdom as a dev dependency) loads the file with all network blocked, visits key routes, and fails on any fetch, script load or runtime error. Runs in CI.
    4. Publish dist/demo.html with the Artifact tool, to the same URL each time.
  • Next.js features that don't work in an artifact, and what to use instead:
    Don't use Because Use instead
    Multiple routes, next/link, useRouter().push Navigation fetches RSC .txt payloads from the server One app/page.tsx + a small hash router in packages/features
    next/dynamic, React.lazy, import() Loads a separate chunk over the network Static imports only
    Server Actions, Route Handlers, middleware, cookies()/headers() No server ClaudeDbDataSource
    next/font Font files are emitted as separate files Google Fonts <link> in the layout (allowed by the artifact host)
    next/image optimization Needs a server images.unoptimized, or plain <img> with /_blob/{assetId} URLs
    Remote images or API calls to other sites Blocked by the artifact's security policy Upload through assets; embed small images as data URIs
  • Every claude.use(...) call happens inside useEffect (client only), never during static rendering. The page renders its shell and loading states first.
  • Same tokens (§11.3), copy rules (§11.4) and message catalogs (§12) as production, so screens transfer directly.
  • Responsive from 360 px, light and dark viewer themes, safe-area insets, keyboard focus visible, reduced motion respected.
  • No localStorage for shared data. Only per-viewer conveniences such as last-used language, wrapped in try/catch.
  • The click-everything rule (L3) applies: every button does something, even if the result is labeled "Simulated".

18.6 Comment-based UAT

  1. Invite reviewers (D12). They open the link and click "Leave feedback" on any element.
  2. Claude reads threads with the ArtifactComments tool, fixes the issue, republishes to the same URL, replies with what changed, and resolves the thread only once the change is made.
  3. Questions and "can't fix" items get a reply explaining why and stay open for the client, as on the Yimaru UAT sheet.

18.7 Limits to tell the client

  • Students in Ethiopia can't sign up publicly; only invited reviewers can open it.
  • Payments, SMS and email are simulated.
  • Videos are short sample clips and are not protected the way production video is (§9.3).
  • Data in the demo is test data and is reset before the production build.

19. Glossary

HLS: video split into short segments with a playlist. Rendition: one quality level. Entitlement: the server's decision that a student may watch a lesson. Enrollment: a student owning a course. Aggregator: a payment company that offers many local methods through one API (ArifPay). Minor units: smallest currency unit (santim, cents). Test course: a hidden course used only for real-money payment testing.


Appendix A. Claude-hosted demo build files

Changed 2026-10-06 while building C0-02 (the files in tools/ are now the source of truth):

  • artifact-inline.mjs also moves <title> to the top of <head> (the host reads only the first 8 KB), adds viewport-fit=cover, and escapes U+FFFD inside scripts (the publisher rejects the raw character).
  • artifact-check.mjs also scans the DOM for <link>/<script> tags React inserts at hydration (jsdom doesn't fetch them).
  • apps/demo/app/layout.tsx inlines packages/features/src/styles.css with a <style> tag at build time. A normal CSS import gets re-requested by React's stylesheet hoisting at hydration, which the artifact CSP blocks.
  • next.config.mjs adds transpilePackages for the workspace packages.

These were tested on a Next.js 15.5 static export: the inlined page loaded its interactive parts, handled clicks and hash routing, rendered Ge'ez text, and made no network requests. Create them as-is in C0-02.

A.1 apps/demo/next.config.mjs

// apps/demo/next.config.mjs
export default {
  output: 'export',
  images: { unoptimized: true },
  trailingSlash: false,
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.optimization.splitChunks = false;   // one client bundle, no lazy chunks
      config.optimization.runtimeChunk = false;
    }
    return config;
  },
};

A.2 tools/artifact-inline.mjs

// Turns a Next.js static export (output: 'export') into ONE self-contained HTML file
// that can be published as a Claude artifact. Usage: node tools/artifact-inline.mjs apps/demo/out dist/demo.html
import fs from 'fs'; import path from 'path';
const [outDir = 'apps/demo/out', dest = 'dist/demo.html'] = process.argv.slice(2);
let html = fs.readFileSync(path.join(outDir, 'index.html'), 'utf8');
const read = (p) => fs.readFileSync(path.join(outDir, p.replace(/^\//, '')), 'utf8');

html = html.replace(/<link[^>]+rel="preload"[^>]*>/g, '');                       // preloads would hit the network
html = html.replace(/<link[^>]+rel="stylesheet"[^>]*href="(\/_next[^"]+)"[^>]*>/g, (_, h) => `<style>${read(h)}</style>`);
html = html.replace(/<script([^>]*?)src="(\/_next[^"]+)"([^>]*)><\/script>/g, (_, a, src, b) => {
  const attrs = (a + b).replace(/\s(async|defer|noModule|nomodule)(="")?/g, '');
  return `<script${attrs}>${read(src).replace(/<\/script/gi, '<\\/script')}</script>`;
});

const leftovers = (html.match(/(src|href)="\/_next\/[^"]+"/g) || []);
if (leftovers.length) { console.error('Un-inlined Next assets:', leftovers); process.exit(1); }
const mb = Buffer.byteLength(html) / 1024 / 1024;
if (mb > 15) { console.error(`Too large for an artifact: ${mb.toFixed(1)} MB (limit 16 MB)`); process.exit(1); }
fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.writeFileSync(dest, html);
console.log(`Wrote ${dest} (${mb.toFixed(2)} MB)`);

A.3 tools/artifact-check.mjs

// CI check: loads the inlined demo in jsdom with ALL network blocked and fails if the page
// tries to fetch or load any script (e.g. a lazy chunk or an RSC .txt payload), or throws.
// Usage: node tools/artifact-check.mjs dist/demo.html
import { JSDOM, VirtualConsole } from 'jsdom'; import fs from 'fs';
const file = process.argv[2] || 'dist/demo.html';
const errors = [], network = [];
const vc = new VirtualConsole();
vc.on('jsdomError', (e) => errors.push(String(e.message)));
const dom = new JSDOM(fs.readFileSync(file, 'utf8'), {
  runScripts: 'dangerously', url: 'https://artifact.local/', virtualConsole: vc, pretendToBeVisual: true,
  beforeParse(w) {
    Object.assign(w, { TextEncoder, TextDecoder, MessageChannel, ReadableStream, structuredClone });
    w.fetch = (u) => { network.push(`fetch ${u}`); return Promise.reject(new Error('blocked')); };
    const create = w.document.createElement.bind(w.document);
    w.document.createElement = (tag, ...rest) => {
      const el = create(tag, ...rest);
      if (tag === 'script') {
        const d = Object.getOwnPropertyDescriptor(w.HTMLScriptElement.prototype, 'src');
        Object.defineProperty(el, 'src', { set(v) { network.push(`script ${v}`); d.set.call(el, v); }, get() { return d.get.call(el); } });
      }
      return el;
    };
  },
});
const w = dom.window;
await new Promise((r) => setTimeout(r, 2000));
for (const route of ['#/am', '#/am/courses', '#/admin']) { w.location.hash = route; await new Promise((r) => setTimeout(r, 300)); }
const allowed = (u) => /cdnjs\.cloudflare\.com|cdn\.jsdelivr\.net\/npm|fonts\.googleapis\.com|fonts\.gstatic\.com/.test(u);
const bad = network.filter((n) => !allowed(n));
console.log({ networkAttempts: bad, errors });
process.exit(bad.length || errors.length ? 1 : 0);