# RoboLearn — build contract for remaining dashboard verticals

Project root: `D:/MSR/PROJECT ANTI GRAVITY/PROJECT34 - V2 Robotic coding`
Stack: Next.js 15 App Router, TypeScript, Tailwind v4, Prisma 6 + PostgreSQL, server actions + Zod.
Language: **all UI copy in Indonesian**.

## Non-negotiable conventions

1. **Pages are async Server Components.** Start each page with
   `const user = await requireUser("/dashboard/<path>");` from `@/lib/auth/rbac`.
   Use `requireTeacher` / `requireAdmin` when the whole route is staff-only.
   Never trust a role from the client.
2. **Data access lives in `src/lib/queries/<domain>.ts`**, begins with `import "server-only";`,
   imports `prisma` from `@/lib/db`, and exports **named interfaces** for every returned shape.
   NEVER export `ReturnType<typeof fn>` / `Awaited<ReturnType<...>>` — name the type.
3. **Mutations live in `src/actions/<domain>.ts`**, first line `"use server";`.
   Signature: `export async function xAction(_previous: ActionState, formData: FormData): Promise<ActionState>`.
   Return `actionError(msg, {field: msg})` / `actionSuccess(msg)` from `@/lib/action-state`.
   Authorize inside every action (`authorizeTeacher()`, `authorize("STUDENT")`, …) and wrap in
   try/catch returning `actionError`. Call `recordAudit({...})` from `@/lib/audit`.
   Call `revalidatePath(...)` for each affected route.
4. **Client components** are `"use client"` and use `useActionState(action, IDLE_ACTION)`.
   They must NOT import anything from `@/lib/auth/*`, `@/lib/db`, `@/lib/gamification`,
   or any module with `server-only`. Role/label constants come from `@/lib/roles`
   and `@/lib/labels` (both client-safe).
5. Enum → display text goes through `src/lib/labels.ts` (`PUBLISH_BADGE`, `ATTENDANCE_BADGE`,
   `SUBMISSION_BADGE`, `ROLE_BADGE`, `LEVEL_BADGE`, `LESSON_TYPE_BADGE`,
   `ASSIGNMENT_TYPE_BADGE`, `CODING_STATUS_BADGE`, `LANGUAGE_LABEL`, `ENROLLMENT_BADGE`,
   `scoreTone`, `scoreToneClass`, `attendanceToneClass`). Add new entries there rather than
   hardcoding labels in a page.
6. Dates/numbers via `src/lib/format.ts` (`formatDate`, `formatDateTime`, `formatTime`,
   `formatRelativeTime`, `formatRelativeDay`, `describeDueDate`, `formatPercent`, `formatNumber`,
   `formatFileSize`, `greeting`).
7. Zod schemas already exist in `src/lib/validation.ts` for every domain — **reuse them**,
   do not invent new ones. Flatten with `fieldErrors(parsed.error)`.

## Available UI kit (`src/components/ui/`)

- `button.tsx` → `Button` (`variant`: primary|secondary|outline|ghost|danger|success|subtle|link;
  `size`: sm|md|lg|icon|icon-sm; props `loading`, `asChild`).
- `card.tsx` → `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter`.
- `badge.tsx` → `Badge` (`variant`: neutral|brand|success|warning|danger|info|accent|outline).
- `input.tsx` → `Input`, `Textarea`, `Select`, `Field` (`label`, `htmlFor`, `hint`, `error`, `required`).
- `table.tsx` → `Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell`, `TableCaption`.
- `tabs.tsx` → `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent` (Radix; needs `"use client"`).
- `dialog.tsx` → `Dialog`, `DialogTrigger`, `DialogContent` (`size`: sm|md|lg|xl), `DialogHeader`,
  `DialogTitle`, `DialogDescription`, `DialogBody`, `DialogFooter`, `DialogClose`.
- `progress.tsx` → `Progress` (`value`, `max`, `tone`, `size`, `showLabel`, `label`), `RingProgress`.
- `page-header.tsx` → `PageHeader` (`title`, `description`, `actions`, `breadcrumb`), `StatCard`
  (`label`, `value`, `hint`, `icon`, `tone`), `Section` (`title`, `description`, `actions`, `children`).
- `empty-state.tsx` → `EmptyState` (`icon`, `title`, `description`, `action`, `compact`).
- `avatar.tsx` → `Avatar` (`name` REQUIRED, `src`, `size`: xs|sm|md|lg|xl).
- `alert.tsx` → `Alert` (`tone`: info|success|warning|danger, `title`, `children`, `icon`).
- `action-button.tsx` → `ActionButton` (`action`, `fields`, `label`, `confirm`, `confirmTitle`,
  `confirmLabel`, `icon`, `variant`, `size`, `className`) — use for one-click mutations,
  pass `confirm` to get a confirmation dialog.
- `dynamic-icon.tsx` → `DynamicIcon` (`name`, `className`) renders a Lucide icon by stored name.

**Reference implementation to copy the pattern from:**
- `src/lib/queries/courses.ts`
- `src/actions/courses.ts`
- `src/app/dashboard/courses/page.tsx`
- `src/app/dashboard/courses/[courseId]/page.tsx`
- `src/components/courses/course-form-dialog.tsx`
- `src/components/courses/course-outline-manager.tsx`
- `src/components/courses/course-roster.tsx`

## Auth helpers

```ts
import { requireUser, requireTeacher, requireAdmin, authorize, authorizeTeacher,
         authorizeAdmin, authorizeStudent, canManageOwnedResource } from "@/lib/auth/rbac";
```
`SessionUser` = `{ id, username, fullName, role, status, avatarUrl, email, xp, level }`.
Teacher scope: `const scope = { userId: user.id, role: user.role };` and admins see everything —
follow the `courseAccessFilter` pattern in `lib/queries/courses.ts`.

## Gamification (server-only, from `@/lib/gamification`)

```ts
awardXp({ userId, amount, source, reason, refType, refId, idempotent })
grantSkillXp({ userId, skillSlug, xp })
evaluateAchievements(userId)
```
`XpSource` enum: LESSON_COMPLETE | ASSIGNMENT_SUBMIT | ASSIGNMENT_GRADE | CODING_PROJECT |
QUIZ_PASS | SIMULATOR | ATTENDANCE | ACHIEVEMENT | MANUAL.
Always pass `idempotent: true` with a stable `refId` for anything repeatable.
Pure level math (client-safe) is in `@/lib/level`: `describeLevel(xp)`, `levelForXp`, `levelTitle`.

## Storage (server-only, from `@/lib/storage`)

```ts
import { uploadFile, deleteFile } from "@/lib/storage";
const stored = await uploadFile({ file, folder: "submissions" }); // { key, url, size, contentType, originalName }
```
Accept `File` from FormData; catch `StorageError` and return `actionError`.

## Code execution (server-only, from `@/lib/runner`)

```ts
import { runCode, runTestSuite, type TestCase, type TestResult } from "@/lib/runner";
const outcome = await runCode({ code, language: "JAVASCRIPT" | "PYTHON" | "ROBOT" }); // { ok, stdout, stderr, error, durationMs, timedOut }
const suite = await runTestSuite(code, tests, language); // { results, passed, total, stdout }
```
`CodingProject.tests` is `Json` shaped `TestCase[]` = `{ name: string; test: string }[]`
where `test` is source appended to learner code and should call `assert(...)` / `assertEqual(...)`.

## Robot simulator (client-safe, from `@/lib/simulator`)

```ts
import { runSimulator, configFromChallenge, DIRECTION_LABELS, type SimulatorResult,
         type SimulatorConfig, type TraceFrame } from "@/lib/simulator";
const config = configFromChallenge(challenge); // pass the Prisma row
const result = runSimulator(program, config);  // { success, reachedGoal, stepsUsed, starsCollected,
                                               //   totalStars, parSteps, score, trace, error, errorLine, message }
```
Language commands: `move`, `turnLeft`, `turnRight`, `pick`, plus `repeat N { ... }` and
`if <cond> { ... } else { ... }` with conditions `starHere`, `goalHere`, `canMove`, `pathClear`.
`trace` is `TraceFrame[]` = `{ step, action, x, y, dir, collected, blocked, note }` — animate it.

## Prisma models (already migrated — do NOT change the schema)

`User, Session, AuditLog, Classroom, ClassEnrollment, Course, CourseEnrollment, Module, Lesson,
LessonProgress, AttendanceSession, AttendanceRecord, Assignment, Submission, Comment, Quiz,
QuizQuestion, QuizAttempt, QuizAnswer, CodingProject, CodingSubmission, Skill, UserSkill,
ProjectSkill, XpEvent, Achievement, UserAchievement, SimulatorChallenge, SimulatorAttempt,
Notification, Announcement, SystemSetting`

Read `prisma/schema.prisma` for exact fields before writing queries.

## Rules for this build

- No dummy/placeholder data. Every number must come from a query.
- No `any`. No `@ts-ignore`. No unused imports.
- Do NOT run `npx tsc`, `next build`, or the dev server — the parent agent validates centrally.
- Do NOT edit `prisma/schema.prisma`, `src/lib/nav.ts`, or files owned by another vertical.
- If you need a new shared component, put it in `src/components/<your-domain>/`.
- Indonesian copy, professional tone, sentence case for body text, Title Case for headings.
