diff --git a/docs/Yimaru_Admin_Developer_Documentation.docx b/docs/Yimaru_Admin_Developer_Documentation.docx new file mode 100644 index 0000000..3c9a687 Binary files /dev/null and b/docs/Yimaru_Admin_Developer_Documentation.docx differ diff --git a/docs/generate_admin_developer_docx.py b/docs/generate_admin_developer_docx.py new file mode 100644 index 0000000..6da7353 --- /dev/null +++ b/docs/generate_admin_developer_docx.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +"""Generate Yimaru Admin Panel Developer Documentation (.docx).""" + +from datetime import date +from pathlib import Path + +from docx import Document +from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING +from docx.oxml.ns import qn +from docx.shared import Inches, Pt, RGBColor + +OUT = Path(__file__).resolve().parent / "Yimaru_Admin_Developer_Documentation.docx" + + +def set_run_font(run, name="Calibri", size=11, bold=False, italic=False, color=None): + run.font.name = name + run._element.rPr.rFonts.set(qn("w:eastAsia"), name) + run.font.size = Pt(size) + run.bold = bold + run.italic = italic + if color is not None: + run.font.color.rgb = color + + +def add_para( + doc, + text, + *, + size=11, + bold=False, + italic=False, + space_after=8, + space_before=0, + align=None, +): + p = doc.add_paragraph() + if align is not None: + p.alignment = align + pf = p.paragraph_format + pf.space_after = Pt(space_after) + pf.space_before = Pt(space_before) + pf.line_spacing_rule = WD_LINE_SPACING.SINGLE + run = p.add_run(text) + set_run_font(run, size=size, bold=bold, italic=italic) + return p + + +def add_heading_custom(doc, text, level=1): + h = doc.add_heading(text, level=level) + for run in h.runs: + set_run_font( + run, + name="Calibri", + size={1: 18, 2: 14, 3: 12}.get(level, 11), + bold=True, + ) + if level == 1: + run.font.color.rgb = RGBColor(0x5E, 0x1F, 0x70) + elif level == 2: + run.font.color.rgb = RGBColor(0x9E, 0x28, 0x91) + return h + + +def add_bullets(doc, items, size=11): + for item in items: + p = doc.add_paragraph(style="List Bullet") + p.paragraph_format.space_after = Pt(3) + run = p.add_run(item) + set_run_font(run, size=size) + + +def add_numbered(doc, items, size=11): + for item in items: + p = doc.add_paragraph(style="List Number") + p.paragraph_format.space_after = Pt(3) + run = p.add_run(item) + set_run_font(run, size=size) + + +def add_code_block(doc, text): + for line in text.strip("\n").splitlines(): + p = doc.add_paragraph() + p.paragraph_format.space_after = Pt(0) + p.paragraph_format.space_before = Pt(0) + p.paragraph_format.left_indent = Inches(0.15) + run = p.add_run(line if line else " ") + set_run_font(run, name="Consolas", size=9, color=RGBColor(0x33, 0x33, 0x33)) + doc.add_paragraph().paragraph_format.space_after = Pt(8) + + +def add_table(doc, headers, rows): + table = doc.add_table(rows=1 + len(rows), cols=len(headers)) + table.style = "Table Grid" + hdr = table.rows[0].cells + for i, h in enumerate(headers): + hdr[i].text = "" + p = hdr[i].paragraphs[0] + run = p.add_run(h) + set_run_font(run, size=10, bold=True, color=RGBColor(0x5E, 0x1F, 0x70)) + for r_i, row in enumerate(rows): + cells = table.rows[r_i + 1].cells + for c_i, val in enumerate(row): + cells[c_i].text = "" + p = cells[c_i].paragraphs[0] + run = p.add_run(str(val)) + set_run_font(run, size=9) + doc.add_paragraph().paragraph_format.space_after = Pt(10) + + +def configure_styles(doc): + normal = doc.styles["Normal"] + normal.font.name = "Calibri" + normal.font.size = Pt(11) + normal._element.rPr.rFonts.set(qn("w:eastAsia"), "Calibri") + + +def build(): + doc = Document() + configure_styles(doc) + section = doc.sections[0] + section.top_margin = Inches(0.9) + section.bottom_margin = Inches(0.9) + section.left_margin = Inches(1.0) + section.right_margin = Inches(1.0) + + # Title + for _ in range(3): + doc.add_paragraph() + add_para(doc, "Yimaru Admin Panel", size=28, bold=True, align=WD_ALIGN_PARAGRAPH.CENTER, space_after=6) + add_para(doc, "Developer Documentation", size=20, bold=True, align=WD_ALIGN_PARAGRAPH.CENTER, space_after=18) + add_para( + doc, + "A practical guide for engineers building and maintaining the Yimaru Academy admin SPA", + size=12, + italic=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=28, + ) + add_para( + doc, + f"Package: yimaru-admin (React 19 · TypeScript · Vite 7)\n" + f"Document generated {date.today().isoformat()}\n" + f"Audience: Frontend / full-stack developers working on the admin console\n" + f"Source: https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git", + size=10, + align=WD_ALIGN_PARAGRAPH.CENTER, + space_after=12, + ) + add_para( + doc, + "Internal / proprietary — Yaltopia Tech · Yimaru Academy", + size=9, + italic=True, + align=WD_ALIGN_PARAGRAPH.CENTER, + ) + doc.add_page_break() + + # 1 Intro + add_heading_custom(doc, "1. Introduction", 1) + add_para( + doc, + "The Yimaru Admin Panel is the staff-facing web app for Yimaru Academy. Content " + "managers reorder courses at midnight, support agents triage issues, finance peeks at " + "revenue charts, and super-admins invite the next teammate—all through this SPA. It does " + "not own business rules; it talks to Yimaru-Backend over HTTPS and presents them safely.", + ) + add_para( + doc, + "This document is written for developers who will change routes, API clients, permission " + "gates, or UI. It assumes React and TypeScript familiarity. It does not assume you already " + "know why we bootstrap the team session before first paint, or why invite payloads must " + "send SUPER_ADMIN instead of the label “Super Admin.”", + ) + add_para(doc, "Keep these siblings open while you work:", space_after=4) + add_bullets( + doc, + [ + "Backend: https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd.git", + "Backend docs/*-admin-panel-integration.md — API contracts for invites, exports, practices, etc.", + "This repo’s README.md — quick start and env tables", + "Backend Swagger on a running API — /swagger/index.html", + ], + ) + + add_heading_custom(doc, "1.1 What the admin app is (and is not)", 2) + add_para( + doc, + "It is a team-member console: authentication is against team_members, not learner users. " + "Permissions come from RBAC keys on the JWT / member payload. It is not the mobile learner " + "app, and it should not invent entitlement logic that the API does not enforce.", + ) + + add_heading_custom(doc, "1.2 Branches", 2) + add_para( + doc, + "We keep main and production aligned for releases. Typical flow: land on main, push, " + "fast-forward production, push production. If only one branch is updated, deploys drift—" + "and someone will ask why UAT looks different from production.", + ) + + # 2 Stack + add_heading_custom(doc, "2. Tech stack and runtime shape", 1) + add_table( + doc, + ["Concern", "Choice"], + [ + ["UI library", "React 19 + React DOM"], + ["Language", "TypeScript ~5.9 (strict-ish project defaults)"], + ["Bundler / dev server", "Vite 7"], + ["Routing", "react-router-dom 7 — see src/app/AppRoutes.tsx"], + ["HTTP", "Axios instance in src/api/http.ts"], + ["Styling", "Tailwind 3 + CSS variables in index.css"], + ["Primitives", "Radix UI (dialog, dropdown, avatar, …)"], + ["Icons", "lucide-react"], + ["Charts", "Recharts"], + ["Drag and drop", "@dnd-kit (reorder pages)"], + ["Toasts", "Sonner"], + ["Global state", "Zustand (src/zustand) + lots of local React state"], + ["Uploads", "tus-js-client where resumable/Vimeo flows need it"], + ], + ) + add_para( + doc, + "Build metadata: vite.config.ts injects __BUILD_HASH__ (git short SHA) and __BUILD_TIME__. " + "Handy when support asks “which admin build is live?”", + space_before=6, + ) + + # 3 Architecture + add_heading_custom(doc, "3. Application architecture", 1) + add_para( + doc, + "Think in layers that stay boring on purpose:", + ) + add_code_block( + doc, + """ +main.tsx → App.tsx (session bootstrap) → AppRoutes + └─ public auth/legal routes + └─ AppLayout (Sidebar + Topbar + ) + └─ page components under src/pages/* + └─ call src/api/*.ts + └─ Axios http.ts (Bearer + refresh queue) +""", + ) + add_table( + doc, + ["Folder", "Put here…"], + [ + ["src/pages/", "Route screens and feature-specific UI"], + ["src/components/", "Reusable UI (ui/, sidebar/, analytics/, dashboard/)"], + ["src/api/", "One module per backend domain"], + ["src/types/", "TS shapes mirroring API JSON (usually snake_case fields)"], + ["src/lib/", "Pure helpers: auth storage, teamRoles, analytics formatters, errors"], + ["src/hooks/", "Shared hooks (e.g. useTeamPermissions)"], + ["src/layouts/", "AppLayout shell"], + ["src/zustand/", "Cross-page client state when props drilling hurts"], + ], + ) + add_para( + doc, + "Canonical routing truth is AppRoutes.tsx—not the sidebar labels, not this document if " + "they diverge. When you add a page, register the route and wire nav (with permission) in " + "Sidebar.tsx.", + space_before=6, + ) + + # 4 Setup + add_heading_custom(doc, "4. Local development setup", 1) + add_heading_custom(doc, "4.1 Prerequisites", 2) + add_bullets( + doc, + [ + "Node.js 18+ (20 LTS recommended)", + "npm (package-lock.json is the source of truth)", + "A running Yimaru Backend reachable from the browser", + "A team account with the permissions you need to test", + ], + ) + add_heading_custom(doc, "4.2 First run", 2) + add_numbered( + doc, + [ + "git clone https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git && cd Yimaru-Admin", + "npm install", + "Create .env with VITE_API_BASE_URL (and VITE_GOOGLE_CLIENT_ID if testing Google login)", + "npm run dev — usually http://localhost:5173", + "Log in with a team member; confirm Network tab hits your API prefix", + ], + ) + add_para( + doc, + "Example env (adjust host/port to your backend):", + space_before=6, + space_after=4, + ) + add_code_block( + doc, + """ +VITE_API_BASE_URL=http://localhost:8080/api/v1 +VITE_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com +""", + ) + add_para( + doc, + "Vite only exposes VITE_* variables, and they are baked in at build time for production " + "bundles. Changing .env requires restarting the dev server; changing production API URL " + "requires a rebuild.", + ) + + add_heading_custom(doc, "4.3 Scripts", 2) + add_table( + doc, + ["Script", "Purpose"], + [ + ["npm run dev", "Vite HMR"], + ["npm run build", "Production bundle to dist/"], + ["npm run preview", "Serve dist locally"], + ["npm run lint", "ESLint"], + ], + ) + + # 5 Auth + add_heading_custom(doc, "5. Authentication and session lifecycle", 1) + add_para( + doc, + "Admin auth is team-based. Learners cannot log into this app with a student password and " + "should not be able to—if they can, something is very wrong on the backend route guards.", + ) + add_heading_custom(doc, "5.1 Public vs shell routes", 2) + add_table( + doc, + ["Path", "Purpose"], + [ + ["/login", "Email/password (+ Google when configured)"], + ["/forgot-password", "Request reset email"], + ["/reset-password", "Complete reset with OTP from link"], + ["/verification", "OTP UI where the flow still uses it"], + ["/accept-invite", "Invitee sets profile/password"], + ["/about, /terms, /privacy, /account-deletion", "Public/legal"], + ["Everything under AppLayout", "Requires a usable team session"], + ], + ) + add_heading_custom(doc, "5.2 Storage and http.ts", 2) + add_para( + doc, + "Tokens and member metadata live in browser storage via src/lib/teamAuthStorage " + "(access_token, refresh_token, member_id, team_role, …). The shared Axios client:", + ) + add_bullets( + doc, + [ + "Sets Authorization: Bearer on outbound calls", + "Proactively refreshes when the access JWT is near expiry", + "Queues concurrent 401s while a single /team/refresh is in flight", + "Clears session and redirects to /login on hard failures (including inactive account query flag)", + "Can skipErrorToast for flows that handle errors inline (invites, some auth)", + ], + ) + add_para( + doc, + "App.tsx bootstraps the browser session before the first protected render. That exists " + "because we used to flash “Authorization header missing” toasts when clearTeamSession " + "raced with early API calls. Do not “simplify” bootstrap away without re-testing cold loads.", + space_before=6, + ) + + add_heading_custom(doc, "5.3 Team invites — role keys and email checks", 2) + add_para( + doc, + "POST /team/members/invite expects team_role as a built-in key (SUPER_ADMIN), an exact " + "RBAC role name, or a numeric roles.id. Display labels like “Super Admin” are for humans. " + "Helpers in src/lib/teamRoles.ts (teamRoleNameForInvite, rbacRolesToTeamRoleOptions) keep " + "the invite dialog honest. The dialog also loads existing team emails and blocks " + "duplicates before send—invites cannot target an email that already exists on team_members.", + ) + + # 6 Permissions + add_heading_custom(doc, "6. Permissions (RBAC) in the UI", 1) + add_para( + doc, + "Gate features on permission keys, not on team_role === \"ADMIN\". Sidebar entries use " + "useTeamPermissions and helpers like hasFaqPermission, hasRatingsPermission, " + "hasExportPermission, etc. fetchCurrentTeamMemberPermissions in team.api.ts walks the " + "members list to find the signed-in member’s permissions array (and syncs team_role).", + ) + add_para( + doc, + "When you add a new admin action, ask backend for the permission string they wired in " + "RequirePermission, then gate the button and ideally the route. Hiding a nav link is not " + "security—the API must still refuse—but showing a dead-end page is a bad UX.", + ) + + # 7 Navigation map + add_heading_custom(doc, "7. Product areas and routing map", 1) + add_para( + doc, + "High-level navigation (see Sidebar.tsx + AppRoutes.tsx for exact paths):", + ) + add_table( + doc, + ["Area", "Typical paths", "Notes"], + [ + ["Dashboard", "/dashboard", "KPIs, charts, plans peek"], + ["Analytics", "/analytics", "Tabbed deep analytics"], + ["Users", "/users/list, /users/:id, groups, deletion-requests", "Learner admin"], + ["Roles", "/roles, /roles/add", "RBAC + invite-into-role"], + ["Team", "/team, /team/add, /team/:id", "Staff directory"], + ["New content", "/new-content, /reorder, question-types, courses…", "Primary CMS"], + ["Legacy content", "/content/*", "Older category flows; still routed"], + ["Personas", "/personas", "permission: personas.list"], + ["Notifications", "/notifications/* + email templates", "Create/schedule"], + ["Payments", "/payments", "Payment ops"], + ["Subscriptions export", "subscriptions export routes", "CSV helpers"], + ["Issues", "/issues", "Use status rejected, not closed"], + ["FAQs / ratings / user-log", "/faqs, ratings, /user-log", "Permission gated"], + ["Profile / settings", "/profile, /settings", "Self-service team profile"], + ], + ) + + add_heading_custom(doc, "7.1 New content vs legacy /content", 2) + add_para( + doc, + "Day-to-day CMS work happens under /new-content (Learn English programs and " + "Duolingo/IELTS catalog, practices, question-type library, reorder). /content/* remains " + "for older hierarchies. Prefer extending new-content unless you are fixing a legacy path " + "that production still bookmarks.", + ) + + add_heading_custom(doc, "7.2 Reorder Content", 2) + add_para( + doc, + "Route: /new-content/reorder. Tabs: Learn English | Duolingo/IELTS. Drag-and-drop via " + "@dnd-kit; persist on drop through reorder* helpers in courses.api.ts. Shared list UI " + "lives in ContentHierarchyList / ExamPrepContentHierarchyList. Keep the layout dense—" + "editors reorder long trees and hate giant paddings.", + ) + + # 8 API layer + add_heading_custom(doc, "8. API client layer", 1) + add_para( + doc, + "Convention: one file per backend domain under src/api/. Pages import functions; they " + "should not construct raw axios instances. Types belong in src/types/.", + ) + add_table( + doc, + ["Module", "Domain"], + [ + ["http.ts", "Shared client + interceptors"], + ["team.api.ts / teamRefresh.api.ts", "Team auth, members, invites"], + ["analytics.api.ts", "Dashboard analytics"], + ["courses.api.ts", "LMS + exam-prep content & reorder"], + ["users.api.ts", "Learners"], + ["rbac.api.ts", "Roles & permissions"], + ["notifications.api.ts / emailTemplates.api.ts", "Messaging"], + ["payments.api.ts / subscription-plans.api.ts / admin-subscriptions.api.ts", "Money"], + ["issues.api.ts / faq.api.ts / ratings.api.ts / personas.api.ts", "Support content"], + ["files.api.ts", "Uploads"], + ["activity-logs.api.ts", "Audit trail"], + ["questionTypeDefinitions.api.ts / …Groups…", "Dynamic question types"], + ["app-versions.api.ts", "Mobile version gates"], + ["progress.api.ts", "Progress-related admin views if used"], + ], + ) + add_para( + doc, + "Errors: prefer notifyApiError / getApiErrorMessage from src/lib/apiErrors.ts. For " + "multi-step dialogs (bulk invite), collect per-email outcomes instead of a single toast.", + space_before=6, + ) + add_para( + doc, + "When the backend publishes a new admin-panel-integration.md, update types + api module " + "in the same PR as the UI. Drift between Swagger and our TypeScript types is how silent " + "undefined bugs are born.", + ) + + # 9 Design system + add_heading_custom(doc, "9. Design system and UI patterns", 1) + add_para( + doc, + "Brand purple is intentional (brand-500 ≈ #9E2891). Gold and mint are accents for " + "highlights and positive trends. Neutrals use grayScale-* backed by CSS variables " + "(--gs-*). Font: Inter. Prefer components under src/components/ui/ over one-off markup.", + ) + add_heading_custom(doc, "9.1 Dashboard / Analytics visual language", 2) + add_para( + doc, + "Shared primitives (where present) and page patterns aim for: light page canvas, white " + "cards with thin borders, underline tabs in brand color, KPI cards with label + thin " + "icon + large value + trend pill, purple area charts with soft fills. Sensitive money " + "fields use SensitiveValue / SensitiveRevealProvider so operators can hide revenue in " + "screen shares.", + ) + add_heading_custom(doc, "9.2 Accessibility and density", 2) + add_para( + doc, + "Radix primitives give us focus management for dialogs/menus—keep using them. For dense " + "ops screens (reorder, issue queues), favor information density over marketing whitespace, " + "but never remove hit targets for drag handles and primary actions.", + ) + + # 10 Feature deep dives + add_heading_custom(doc, "10. Feature deep dives", 1) + + add_heading_custom(doc, "10.1 Analytics", 2) + add_para( + doc, + "Data comes from getDashboard with DashboardFilters (all_time / year / year_month / " + "custom). AnalyticsTimeRangeFilter owns the date UX. Tabs conceptually split Learn " + "English, Content Performance, and Subscription & Revenue so operators are not scrolling " + "a single endless page. Formatters and pie builders live in src/lib/analytics.ts—" + "including label cleanup (Unknown → Other) to match backend normalization.", + ) + + add_heading_custom(doc, "10.2 Users and subscriptions on user detail", 2) + add_para( + doc, + "User detail composes profile, learning activity, and subscription admin " + "(grant/extend/cancel) against admin-subscriptions APIs. Follow backend integration docs " + "for payload shapes; do not guess lifecycle transitions.", + ) + + add_heading_custom(doc, "10.3 Roles and bulk deactivate", 2) + add_para( + doc, + "RolesListPage can invite into a role, edit permissions, and bulk deactivate/reactivate. " + "SUPER_ADMIN guardrails are enforced server-side—surface API errors clearly instead of " + "retrying blindly.", + ) + + add_heading_custom(doc, "10.4 Issues", 2) + add_para( + doc, + "Valid PATCH statuses include pending, in_progress, resolved, rejected. The UI once sent " + "closed, which failed validation. Keep rejected in the selector; legacy closed may still " + "display for old rows.", + ) + + add_heading_custom(doc, "10.5 Notifications & email templates", 2) + add_para( + doc, + "Creating notifications supports audiences by user ids, platform roles, team members, " + "team roles, and direct emails (depending on channel). Scheduled sends need RFC3339 " + "timestamps the API accepts. Email templates are a separate CRUD surface—test with " + "Resend configured on the backend.", + ) + + # 11 Shipping + add_heading_custom(doc, "11. How we like to ship UI changes", 1) + add_numbered( + doc, + [ + "Confirm the API exists (or is shipping in the same release) and note the permission key.", + "Add/extend types in src/types and functions in src/api.", + "Build the page or dialog with existing ui/ components.", + "Gate nav and destructive actions with permissions.", + "Handle loading, empty, and error states—ops users hate infinite spinners with no retry.", + "npm run lint; smoke the happy path and one failure path (403, validation).", + "Commit with why; push main and sync production when releasing.", + ], + ) + add_para( + doc, + "Avoid drive-by refactors in the same PR as a production hotfix. Match local naming and " + "file layout. Prefer snake_case field names in API types to match JSON rather than " + "renaming everything to camelCase at the boundary—unless a module already maps explicitly.", + space_before=6, + ) + + # 12 Deploy + add_heading_custom(doc, "12. Build and deploy notes", 1) + add_code_block( + doc, + """ +npm run lint +npm run build +# deploy dist/ behind HTTPS; set VITE_* at build time +""", + ) + add_para( + doc, + "Coordinate TEAM_INVITE_BASE_URL / TEAM_PASSWORD_RESET_BASE_URL on the backend with the " + "deployed admin origin so invite and reset emails deep-link correctly.", + ) + + # 13 Troubleshooting + add_heading_custom(doc, "13. Troubleshooting field guide", 1) + add_table( + doc, + ["Symptom", "Likely cause / fix"], + [ + ["CORS / network errors", "Wrong VITE_API_BASE_URL; backend CORS; mixed content"], + ["Immediate bounce to login", "Refresh failing; cleared storage; JWT_KEY rotated on API"], + ["401 toasts on first paint", "Session bootstrap race—keep App.tsx + http.ts behavior"], + ["Invite invalid team role", "Sending display label; use SUPER_ADMIN / RBAC name / id"], + ["Invite email already exists", "Member or pending invite exists; dialog should block"], + ["Issue status PATCH fails", "Do not send closed; use rejected"], + ["Empty analytics", "API error, date filter, or missing permission"], + ["Nav item missing", "Permission helper returned false; check role permissions"], + ["Google login broken", "VITE_GOOGLE_CLIENT_ID + backend Google OAuth env"], + ["Production looks stale", "main pushed but production not updated (or CDN cache)"], + ], + ) + + # 14 Glossary + add_heading_custom(doc, "14. Glossary", 1) + add_table( + doc, + ["Term", "Meaning in this app"], + [ + ["Team member", "Staff account in team_members; admin login identity"], + ["Permission key", "String like team.members.invite used to show/hide actions"], + ["New content", "Primary CMS under /new-content"], + ["Duolingo/IELTS tab", "Exam-prep hierarchy in reorder UI"], + ["SensitiveValue", "UI control to mask revenue/PII-ish numbers"], + ["Accept invite", "Public page completing staff onboarding from email link"], + ], + ) + + # 15 Related docs + add_heading_custom(doc, "15. Related documentation", 1) + add_bullets( + doc, + [ + "This repo README.md", + "docs/course-management-api-integration.md (if present in docs/)", + "Backend README + docs/Yimaru_Backend_Developer_Documentation.docx", + "Backend docs/team-member-invitation-admin-panel-integration.md", + "Backend docs/team-member-refresh-token-admin-panel-integration.md", + "Backend docs/csv-export-admin-panel-integration.md", + "Backend docs/bulk-scheduled-notifications-integration.md", + "Backend practice/question-type/vimeo/file-upload integration guides", + ], + ) + + # Closing + add_heading_custom(doc, "16. Closing notes", 1) + add_para( + doc, + "The admin panel is where humans operate a live learning business. Broken toasts, wrong " + "role payloads, and ungated delete buttons create real support load. Prefer clear empty " + "states, honest error messages, and permission-aware UI. When the API contract changes, " + "update types and the screen together.", + ) + add_para( + doc, + "If this document disagrees with AppRoutes.tsx or http.ts, trust the code—then fix the " + "doc (or regenerate it from docs/generate_admin_developer_docx.py).", + italic=True, + ) + add_para( + doc, + "— Yaltopia engineering, for Yimaru Academy admin developers", + space_before=16, + italic=True, + ) + + OUT.parent.mkdir(parents=True, exist_ok=True) + doc.save(OUT) + print(f"Wrote {OUT}") + + +if __name__ == "__main__": + build() diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index f2bb359..4b1d5b3 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -1181,6 +1181,9 @@ export const updateQuestionSet = (questionSetId: number, data: Partial http.post(`/question-sets/${questionSetId}/questions`, data) +export const removeQuestionFromSet = (questionSetId: number, questionId: number) => + http.delete(`/question-sets/${questionSetId}/questions/${questionId}`) + export const createQuestion = (data: CreateQuestionRequest) => http.post("/questions", data) diff --git a/src/api/initial-assessment.api.ts b/src/api/initial-assessment.api.ts new file mode 100644 index 0000000..1488cab --- /dev/null +++ b/src/api/initial-assessment.api.ts @@ -0,0 +1,336 @@ +import http from "./http" +import { + addQuestionToSet, + createQuestion, + createQuestionSet, + getQuestionById, + getQuestionSetById, + getQuestionSetQuestions, + getQuestionSets, + removeQuestionFromSet, + updateQuestionSet, +} from "./courses.api" +import { unwrapApiPayload } from "./questionTypeDefinitions.api" +import { normalizeMultipleChoiceValue } from "../lib/multipleChoiceSlotValue" +import type { + CreateQuestionRequest, + CreateQuestionSetRequest, + QuestionOption, + QuestionSetDetail, +} from "../types/course.types" +import type { DynamicQuestionPayload } from "../types/questionTypeDefinition.types" + +export type CefrLevel = "A1" | "A2" | "B1" | "B2" | "C1" | "C2" + +export interface InitialAssessmentLevelThreshold { + level: CefrLevel | string + min_percent: number + display_order: number +} + +export interface PlacementQuestionRow { + setItemId: number + questionId: number + displayOrder: number + questionText: string + questionType: string + difficultyLevel: string + points: number + status: string +} + +/** Normalized question fields for placement create/edit UI (legacy + dynamic_payload). */ +export interface PlacementQuestionDetail { + id: number + question_text: string + question_type: string + difficulty_level: string + points: number + status: string + tips: string + explanation: string + options: QuestionOption[] +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value) +} + +function elementStringValue(value: unknown): string { + if (typeof value === "string") return value.trim() + if (typeof value === "number" && Number.isFinite(value)) return String(value) + if (isRecord(value)) { + for (const key of ["text", "content", "value", "label"]) { + const nested = value[key] + if (typeof nested === "string" && nested.trim()) return nested.trim() + } + } + return "" +} + +function asDynamicPayload(raw: unknown): DynamicQuestionPayload | null { + if (!isRecord(raw)) return null + const stimulus = Array.isArray(raw.stimulus) ? raw.stimulus : [] + const response = Array.isArray(raw.response) ? raw.response : [] + if (stimulus.length === 0 && response.length === 0) return null + return { + stimulus: stimulus.filter(isRecord).map((el) => ({ + id: String(el.id ?? ""), + kind: String(el.kind ?? ""), + value: el.value, + meta: isRecord(el.meta) ? el.meta : undefined, + })), + response: response.filter(isRecord).map((el) => ({ + id: String(el.id ?? ""), + kind: String(el.kind ?? ""), + value: el.value, + meta: isRecord(el.meta) ? el.meta : undefined, + })), + } +} + +function stimulusTextFromPayload(payload: DynamicQuestionPayload | null): string { + if (!payload) return "" + const preferred = ["QUESTION_TEXT", "INSTRUCTION", "TEXT_PASSAGE", "TEXT"] + for (const want of preferred) { + for (const el of payload.stimulus) { + if (String(el.kind).toUpperCase() !== want) continue + const text = elementStringValue(el.value) + if (text) return text + } + } + return "" +} + +function optionsFromPayload(payload: DynamicQuestionPayload | null): QuestionOption[] { + if (!payload) return [] + for (const el of payload.response) { + const kind = String(el.kind ?? "").toUpperCase() + if (kind !== "MULTIPLE_CHOICE" && kind !== "OPTION") continue + const normalized = normalizeMultipleChoiceValue(el.value) + return normalized.options + .filter((o) => o.text.trim()) + .map((o, index) => ({ + option_order: index + 1, + option_text: o.text, + is_correct: o.is_correct, + })) + } + return [] +} + +function optionsFromRaw(raw: unknown): QuestionOption[] { + if (!Array.isArray(raw)) return [] + return raw + .filter(isRecord) + .map((o, index) => ({ + option_order: Number(o.option_order ?? index + 1), + option_text: String(o.option_text ?? o.text ?? ""), + is_correct: Boolean(o.is_correct ?? o.isCorrect), + })) + .filter((o) => o.option_text.trim()) + .sort((a, b) => a.option_order - b.option_order) +} + +export function normalizePlacementQuestionDetail(raw: unknown): PlacementQuestionDetail | null { + if (!isRecord(raw)) return null + const id = Number(raw.id ?? raw.question_id) + if (!Number.isFinite(id) || id <= 0) return null + + const payload = + asDynamicPayload(raw.effective_dynamic_payload) ?? + asDynamicPayload(raw.dynamic_payload) + + const flatText = String(raw.question_text ?? "").trim() + const questionText = flatText || stimulusTextFromPayload(payload) + + const flatOptions = optionsFromRaw(raw.options) + const options = flatOptions.length > 0 ? flatOptions : optionsFromPayload(payload) + + return { + id, + question_text: questionText, + question_type: String(raw.question_type ?? "").trim() || "unassigned", + difficulty_level: String(raw.difficulty_level ?? "").trim() || "unassigned", + points: Number(raw.points ?? 1) || 1, + status: String(raw.question_status ?? raw.status ?? "").trim() || "unassigned", + tips: String(raw.tips ?? ""), + explanation: String(raw.explanation ?? ""), + options, + } +} + +function unwrapListPayload(body: unknown): unknown[] { + const payload = isRecord(body) && "data" in body ? body.data : body + if (Array.isArray(payload)) return payload + if (isRecord(payload) && Array.isArray(payload.questions)) return payload.questions + return [] +} + +function normalizeThreshold(raw: unknown): InitialAssessmentLevelThreshold | null { + if (!isRecord(raw)) return null + const level = String(raw.level ?? "").toUpperCase() + const min = Number(raw.min_percent ?? raw.minPercent) + const order = Number(raw.display_order ?? raw.displayOrder ?? 0) + if (!level || !Number.isFinite(min)) return null + return { + level, + min_percent: min, + display_order: Number.isFinite(order) ? order : 0, + } +} + +export function parseLevelThresholds(body: unknown): InitialAssessmentLevelThreshold[] { + const payload = isRecord(body) && "data" in body ? body.data : body + if (!Array.isArray(payload)) return [] + return payload + .map(normalizeThreshold) + .filter((row): row is InitialAssessmentLevelThreshold => row !== null) + .sort((a, b) => a.display_order - b.display_order || a.level.localeCompare(b.level)) +} + +export async function getInitialAssessmentLevelThresholds(): Promise { + const res = await http.get("/admin/assessment/level-thresholds") + return parseLevelThresholds(res.data) +} + +export async function updateInitialAssessmentLevelThresholds( + thresholds: InitialAssessmentLevelThreshold[], +): Promise { + const res = await http.put("/admin/assessment/level-thresholds", { thresholds }) + return parseLevelThresholds(res.data) +} + +function unwrapQuestionSets(body: unknown): Array> { + if (!isRecord(body)) return [] + const data = body.data + if (Array.isArray(data)) return data.filter(isRecord) + if (isRecord(data) && Array.isArray(data.question_sets)) { + return data.question_sets.filter(isRecord) + } + return [] +} + +function pickStandalonePlacement(sets: Array>): Record | null { + const publishedStandalone = sets.find((set) => { + const status = String(set.status ?? "").toUpperCase() + const owner = String(set.owner_type ?? "STANDALONE").toUpperCase() + return status === "PUBLISHED" && (owner === "STANDALONE" || owner === "") + }) + if (publishedStandalone) return publishedStandalone + + const anyStandalone = sets.find((set) => { + const owner = String(set.owner_type ?? "STANDALONE").toUpperCase() + return owner === "STANDALONE" || owner === "" + }) + if (anyStandalone) return anyStandalone + + return sets[0] ?? null +} + +export async function findPlacementAssessmentSet(): Promise { + const res = await getQuestionSets({ + set_type: "INITIAL_ASSESSMENT", + limit: 50, + offset: 0, + }) + const sets = unwrapQuestionSets(res.data) + const picked = pickStandalonePlacement(sets) + if (!picked) return null + const id = Number(picked.id) + if (!Number.isFinite(id)) return null + const detailRes = await getQuestionSetById(id) + return detailRes.data?.data ?? null +} + +export async function createPlacementAssessmentSet(input?: { + title?: string + description?: string +}): Promise { + const payload: CreateQuestionSetRequest = { + title: input?.title?.trim() || "Initial Placement Assessment", + description: input?.description?.trim() || "PLACEMENT", + set_type: "INITIAL_ASSESSMENT", + owner_type: "STANDALONE", + owner_id: null, + shuffle_questions: false, + status: "DRAFT", + } + const res = await createQuestionSet(payload) + const created = res.data?.data + const id = Number(created?.id) + if (!Number.isFinite(id)) { + throw new Error("Placement set created but no id returned") + } + const detailRes = await getQuestionSetById(id) + if (!detailRes.data?.data) { + throw new Error("Failed to load created placement set") + } + return detailRes.data.data +} + +export async function ensurePlacementAssessmentSet(): Promise { + const existing = await findPlacementAssessmentSet() + if (existing) return existing + return createPlacementAssessmentSet() +} + +export async function savePlacementAssessmentSet( + setId: number, + patch: Partial, +): Promise { + await updateQuestionSet(setId, patch) + const detailRes = await getQuestionSetById(setId) + if (!detailRes.data?.data) { + throw new Error("Failed to reload placement set") + } + return detailRes.data.data +} + +export async function listPlacementQuestions(setId: number): Promise { + const res = await getQuestionSetQuestions(setId) + const rows = unwrapListPayload(res.data) + + return rows.map((raw, index) => { + const detail = normalizePlacementQuestionDetail(raw) + const record = isRecord(raw) ? raw : {} + const questionId = detail?.id ?? Number(record.question_id ?? record.id) ?? index + return { + setItemId: Number(record.id) || index, + questionId, + displayOrder: Number(record.display_order ?? index + 1), + questionText: detail?.question_text.trim() || `(Question #${questionId})`, + questionType: detail?.question_type || "unassigned", + difficultyLevel: detail?.difficulty_level || "unassigned", + points: detail?.points ?? 1, + status: detail?.status || "unassigned", + } + }) +} + +export async function getPlacementQuestionDetail(questionId: number): Promise { + const res = await getQuestionById(questionId) + const raw = unwrapApiPayload(res) ?? res.data?.data ?? res.data + const detail = normalizePlacementQuestionDetail(raw) + if (!detail) { + throw new Error("Question not found") + } + return detail +} + +export async function createAndAttachPlacementQuestion( + setId: number, + payload: CreateQuestionRequest, +): Promise { + const createRes = await createQuestion(payload) + const questionId = Number(createRes.data?.data?.id) + if (!Number.isFinite(questionId)) { + throw new Error("Question created but no id returned") + } + await addQuestionToSet(setId, { question_id: questionId }) + return questionId +} + +export async function detachPlacementQuestion(setId: number, questionId: number): Promise { + await removeQuestionFromSet(setId, questionId) +} diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index bfe25b2..882ba1e 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -30,6 +30,7 @@ import { ProgramTypeSelectionPage } from "../pages/content-management/ProgramTyp import { ProgramDetailPage } from "../pages/content-management/ProgramDetailPage"; import { CourseManagementPage } from "../pages/content-management/CourseManagementPage"; import { UnitManagementPage } from "../pages/content-management/UnitManagementPage"; +import { InitialAssessmentPage } from "../pages/content-management/InitialAssessmentPage"; import { QuestionTypeLibraryPage } from "../pages/content-management/QuestionTypeLibraryPage"; import { QuestionTypeGroupDetailPage } from "../pages/content-management/QuestionTypeGroupDetailPage"; import { CreateQuestionTypeFlow } from "../pages/content-management/CreateQuestionTypeFlow"; @@ -188,6 +189,10 @@ export function AppRoutes() { path="/new-content/question-types" element={} /> + } + /> } diff --git a/src/components/sidebar/Sidebar.tsx b/src/components/sidebar/Sidebar.tsx index 4989a65..3255d1b 100644 --- a/src/components/sidebar/Sidebar.tsx +++ b/src/components/sidebar/Sidebar.tsx @@ -84,6 +84,7 @@ const navEntries: NavEntry[] = [ { label: "Learning content", to: "/new-content", end: true }, { label: "Reorder structure", to: "/new-content/reorder" }, { label: "Question types", to: "/new-content/question-types" }, + { label: "Initial assessment", to: "/new-content/initial-assessment" }, ], }, { diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index b6b0cc5..f59947e 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -3,6 +3,7 @@ import React, { useEffect, useState } from "react"; import { Eye, EyeOff, + Gauge, Globe, Lock, Moon, @@ -30,18 +31,21 @@ import type { TeamMeProfile } from "../types/team.types"; import { toast } from "sonner"; import { AppVersionsTab } from "./settings/AppVersionsTab"; import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab"; +import { InitialAssessmentThresholdsTab } from "./settings/InitialAssessmentThresholdsTab"; import { ThemeModePreview } from "./settings/components/ThemeModePreview"; import { useTheme } from "../contexts/ThemeContext"; type SettingsTab = | "subscription" | "app-versions" + | "assessment" | "security" | "appearance"; const tabs: { id: SettingsTab; label: string; icon: typeof Shield }[] = [ { id: "subscription", label: "Subscription packages", icon: CreditCard }, { id: "app-versions", label: "App versions", icon: Smartphone }, + { id: "assessment", label: "Initial assessment", icon: Gauge }, { id: "security", label: "Security", icon: Shield }, { id: "appearance", label: "Appearance", icon: Palette }, ]; @@ -441,6 +445,7 @@ export function SettingsPage() {
{activeTab === "subscription" && } {activeTab === "app-versions" && } + {activeTab === "assessment" && } {activeTab === "security" && } {activeTab === "appearance" && }
diff --git a/src/pages/content-management/InitialAssessmentPage.tsx b/src/pages/content-management/InitialAssessmentPage.tsx new file mode 100644 index 0000000..2ad42ce --- /dev/null +++ b/src/pages/content-management/InitialAssessmentPage.tsx @@ -0,0 +1,1007 @@ +import { useCallback, useEffect, useMemo, useState } from "react" +import { + CheckCircle2, + ClipboardList, + HelpCircle, + Pencil, + Plus, + RefreshCw, + Save, + Search, + Trash2, + X, +} from "lucide-react" +import { toast } from "sonner" +import { + createAndAttachPlacementQuestion, + detachPlacementQuestion, + ensurePlacementAssessmentSet, + getPlacementQuestionDetail, + listPlacementQuestions, + savePlacementAssessmentSet, + type PlacementQuestionDetail, + type PlacementQuestionRow, +} from "../../api/initial-assessment.api" +import { updateQuestion } from "../../api/courses.api" +import { notifyApiError } from "../../lib/apiErrors" +import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination" +import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab" +import { TablePagination } from "../../components/admin/TablePagination" +import { Badge } from "../../components/ui/badge" +import { Button } from "../../components/ui/button" +import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" +import { Input } from "../../components/ui/input" +import { Select } from "../../components/ui/select" +import { SpinnerIcon } from "../../components/ui/spinner-icon" +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table" +import { Textarea } from "../../components/ui/textarea" +import { ToggleSwitch } from "../../components/ui/toggle-switch" +import { cn } from "../../lib/utils" +import type { QuestionSetDetail } from "../../types/course.types" + +type TabId = "set" | "questions" | "thresholds" +type DraftQuestionType = "MCQ" | "TRUE_FALSE" + +interface DraftOption { + text: string + isCorrect: boolean +} + +interface QuestionDraft { + questionText: string + questionType: DraftQuestionType + difficulty: "EASY" | "MEDIUM" | "HARD" + points: number + options: DraftOption[] + tips: string + explanation: string +} + +const emptyDraft = (): QuestionDraft => ({ + questionText: "", + questionType: "MCQ", + difficulty: "EASY", + points: 1, + options: [ + { text: "", isCorrect: true }, + { text: "", isCorrect: false }, + { text: "", isCorrect: false }, + { text: "", isCorrect: false }, + ], + tips: "", + explanation: "", +}) + +const typeColors: Record = { + MCQ: "bg-blue-50 text-blue-700 ring-1 ring-inset ring-blue-200", + TRUE_FALSE: "bg-brand-100 text-brand-700 ring-1 ring-inset ring-brand-200", + SHORT_ANSWER: "bg-mint-100 text-green-700 ring-1 ring-inset ring-green-200", + SHORT: "bg-mint-100 text-green-700 ring-1 ring-inset ring-green-200", + AUDIO: "bg-purple-100 text-purple-700 ring-1 ring-inset ring-purple-200", + DYNAMIC: "bg-amber-50 text-amber-800 ring-1 ring-inset ring-amber-200", +} + +const typeLabels: Record = { + MCQ: "Multiple choice", + TRUE_FALSE: "True / False", + SHORT_ANSWER: "Short answer", + SHORT: "Short answer", + AUDIO: "Audio", + DYNAMIC: "Dynamic", +} + +const difficultyColors: Record = { + EASY: "bg-mint-50 text-green-700 ring-1 ring-inset ring-green-200", + MEDIUM: "bg-amber-50 text-amber-800 ring-1 ring-inset ring-amber-200", + HARD: "bg-red-50 text-red-700 ring-1 ring-inset ring-red-200", +} + +function draftFromQuestionDetail(q: PlacementQuestionDetail): QuestionDraft { + const rawType = String(q.question_type ?? "MCQ").toUpperCase() + const questionType: DraftQuestionType = rawType === "TRUE_FALSE" ? "TRUE_FALSE" : "MCQ" + const difficulty = + q.difficulty_level === "MEDIUM" || q.difficulty_level === "HARD" + ? q.difficulty_level + : q.difficulty_level === "EASY" + ? "EASY" + : "EASY" + + const sortedOptions = [...(q.options ?? [])].sort( + (a, b) => Number(a.option_order ?? 0) - Number(b.option_order ?? 0), + ) + + let options: DraftOption[] + if (questionType === "TRUE_FALSE") { + const trueOpt = sortedOptions.find((o) => String(o.option_text).toLowerCase() === "true") + const falseOpt = sortedOptions.find((o) => String(o.option_text).toLowerCase() === "false") + const correctIsTrue = trueOpt?.is_correct + ? true + : falseOpt?.is_correct + ? false + : sortedOptions.find((o) => o.is_correct)?.option_text?.toLowerCase() !== "false" + options = [ + { text: "True", isCorrect: correctIsTrue }, + { text: "False", isCorrect: !correctIsTrue }, + ] + } else { + options = sortedOptions.map((o) => ({ + text: String(o.option_text ?? ""), + isCorrect: Boolean(o.is_correct), + })) + while (options.length < 2) { + options.push({ text: "", isCorrect: false }) + } + if (!options.some((o) => o.isCorrect) && options.length > 0) { + options[0] = { ...options[0], isCorrect: true } + } + } + + return { + questionText: String(q.question_text ?? ""), + questionType, + difficulty, + points: Number(q.points ?? 1) || 1, + options, + tips: String(q.tips ?? ""), + explanation: String(q.explanation ?? ""), + } +} + +export function InitialAssessmentPage() { + const [tab, setTab] = useState("set") + const [loading, setLoading] = useState(true) + const [savingSet, setSavingSet] = useState(false) + const [setDetail, setSetDetail] = useState(null) + const [title, setTitle] = useState("") + const [description, setDescription] = useState("PLACEMENT") + const [status, setStatus] = useState("DRAFT") + const [shuffle, setShuffle] = useState(false) + const [timeLimit, setTimeLimit] = useState("") + + const [questions, setQuestions] = useState([]) + const [questionsLoading, setQuestionsLoading] = useState(false) + const [addOpen, setAddOpen] = useState(false) + const [editingQuestionId, setEditingQuestionId] = useState(null) + const [editingStatus, setEditingStatus] = useState("PUBLISHED") + const [formLoading, setFormLoading] = useState(false) + const [draft, setDraft] = useState(emptyDraft) + const [savingQuestion, setSavingQuestion] = useState(false) + const [removingId, setRemovingId] = useState(null) + const [statusUpdatingId, setStatusUpdatingId] = useState(null) + const [questionsPage, setQuestionsPage] = useState(1) + const [questionsPageSize, setQuestionsPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) + const [questionsSearch, setQuestionsSearch] = useState("") + + const loadSet = useCallback(async () => { + setLoading(true) + try { + const detail = await ensurePlacementAssessmentSet() + setSetDetail(detail) + setTitle(detail.title || "Initial Placement Assessment") + setDescription(detail.description || "PLACEMENT") + setStatus(String(detail.status || "DRAFT").toUpperCase()) + setShuffle(Boolean(detail.shuffle_questions)) + setTimeLimit( + detail.time_limit_minutes != null && detail.time_limit_minutes > 0 + ? String(detail.time_limit_minutes) + : "", + ) + } catch (e) { + console.error(e) + notifyApiError(e, "Failed to load placement assessment") + setSetDetail(null) + } finally { + setLoading(false) + } + }, []) + + const loadQuestions = useCallback(async (setId: number) => { + setQuestionsLoading(true) + try { + const rows = await listPlacementQuestions(setId) + setQuestions(rows) + } catch (e) { + console.error(e) + notifyApiError(e, "Failed to load placement questions") + setQuestions([]) + } finally { + setQuestionsLoading(false) + } + }, []) + + useEffect(() => { + void loadSet() + }, [loadSet]) + + useEffect(() => { + if (setDetail?.id && (tab === "questions" || tab === "set")) { + void loadQuestions(setDetail.id) + } + }, [setDetail?.id, tab, loadQuestions]) + + const totalPoints = useMemo( + () => questions.reduce((sum, q) => sum + (Number.isFinite(q.points) ? q.points : 0), 0), + [questions], + ) + + const questionsSorted = useMemo( + () => + [...questions].sort( + (a, b) => + a.displayOrder - b.displayOrder || + a.questionId - b.questionId, + ), + [questions], + ) + + const filteredQuestions = useMemo(() => { + const q = questionsSearch.trim().toLowerCase() + if (!q) return questionsSorted + return questionsSorted.filter((row) => { + const typeLabel = (typeLabels[row.questionType] ?? row.questionType).toLowerCase() + const haystack = [ + row.questionText, + String(row.questionId), + row.questionType, + typeLabel, + row.difficultyLevel, + row.status, + String(row.points), + ] + .join(" ") + .toLowerCase() + return haystack.includes(q) + }) + }, [questionsSorted, questionsSearch]) + + const questionsPageCount = Math.max(1, Math.ceil(filteredQuestions.length / questionsPageSize)) + const safeQuestionsPage = Math.min(questionsPage, questionsPageCount) + const paginatedQuestions = useMemo(() => { + const start = (safeQuestionsPage - 1) * questionsPageSize + return filteredQuestions.slice(start, start + questionsPageSize) + }, [filteredQuestions, safeQuestionsPage, questionsPageSize]) + const questionsStartEntry = + filteredQuestions.length === 0 ? 0 : (safeQuestionsPage - 1) * questionsPageSize + 1 + const questionsEndEntry = Math.min(safeQuestionsPage * questionsPageSize, filteredQuestions.length) + + useEffect(() => { + setQuestionsPage(1) + }, [questionsPageSize, setDetail?.id, questionsSearch]) + + const handleSaveSet = async () => { + if (!setDetail) return + if (!title.trim()) { + toast.error("Title is required") + return + } + setSavingSet(true) + try { + const updated = await savePlacementAssessmentSet(setDetail.id, { + title: title.trim(), + description: description.trim() || "PLACEMENT", + status, + shuffle_questions: shuffle, + time_limit_minutes: timeLimit.trim() ? Number(timeLimit) : null, + owner_type: "STANDALONE", + owner_id: null, + set_type: "INITIAL_ASSESSMENT", + }) + setSetDetail(updated) + toast.success("Placement set saved") + } catch (e) { + notifyApiError(e, "Failed to save placement set") + } finally { + setSavingSet(false) + } + } + + const handlePublishToggle = async (nextPublished: boolean) => { + if (!setDetail) return + if (nextPublished && questions.length === 0) { + toast.error("Add at least one question before publishing") + setTab("questions") + return + } + const publishedCount = questions.filter( + (q) => String(q.status).toUpperCase() === "PUBLISHED", + ).length + if (nextPublished && publishedCount === 0) { + toast.error("Publish at least one question before going live — draft questions are hidden from the app") + setTab("questions") + return + } + setSavingSet(true) + try { + const nextStatus = nextPublished ? "PUBLISHED" : "DRAFT" + const updated = await savePlacementAssessmentSet(setDetail.id, { + title: title.trim() || setDetail.title, + description: description.trim() || "PLACEMENT", + status: nextStatus, + shuffle_questions: shuffle, + time_limit_minutes: timeLimit.trim() ? Number(timeLimit) : null, + owner_type: "STANDALONE", + set_type: "INITIAL_ASSESSMENT", + }) + setSetDetail(updated) + setStatus(nextStatus) + toast.success(nextPublished ? "Placement assessment published" : "Placement assessment unpublished") + } catch (e) { + notifyApiError(e, "Failed to update publish status") + } finally { + setSavingSet(false) + } + } + + const closeQuestionForm = () => { + setAddOpen(false) + setEditingQuestionId(null) + setEditingStatus("PUBLISHED") + setDraft(emptyDraft()) + setFormLoading(false) + } + + const openCreateQuestion = () => { + setEditingQuestionId(null) + setEditingStatus("PUBLISHED") + setDraft(emptyDraft()) + setAddOpen(true) + } + + const openEditQuestion = async (questionId: number) => { + setEditingQuestionId(questionId) + setDraft(emptyDraft()) + setAddOpen(true) + setFormLoading(true) + try { + const detail = await getPlacementQuestionDetail(questionId) + const questionType = String(detail.question_type ?? "").toUpperCase() + if (questionType !== "MCQ" && questionType !== "TRUE_FALSE") { + toast.error("Only multiple choice and true/false questions can be edited here") + closeQuestionForm() + return + } + setEditingStatus( + detail.status && detail.status !== "unassigned" ? detail.status : "DRAFT", + ) + setDraft(draftFromQuestionDetail(detail)) + } catch (e) { + notifyApiError(e, "Failed to load question") + closeQuestionForm() + } finally { + setFormLoading(false) + } + } + + const validateDraft = (): string | null => { + if (!draft.questionText.trim()) return "Question text is required" + if (draft.points < 1) return "Points must be at least 1" + const filled = draft.options.filter((o) => o.text.trim()) + if (filled.length < 2) return "Add at least two options" + if (!filled.some((o) => o.isCorrect)) return "Mark one correct option" + return null + } + + const buildQuestionPayload = () => ({ + question_text: draft.questionText.trim(), + question_type: draft.questionType, + difficulty_level: draft.difficulty, + points: draft.points, + status: editingQuestionId != null ? editingStatus : "PUBLISHED", + tips: draft.tips.trim() || undefined, + explanation: draft.explanation.trim() || undefined, + options: draft.options + .filter((o) => o.text.trim()) + .map((o, idx) => ({ + option_order: idx + 1, + option_text: o.text.trim(), + is_correct: o.isCorrect, + })), + }) + + const handleSaveQuestion = async () => { + if (!setDetail) return + const error = validateDraft() + if (error) { + toast.error(error) + return + } + setSavingQuestion(true) + try { + const payload = buildQuestionPayload() + if (editingQuestionId != null) { + await updateQuestion(editingQuestionId, payload) + toast.success("Question updated") + } else { + await createAndAttachPlacementQuestion(setDetail.id, payload) + toast.success("Question added to placement set") + } + closeQuestionForm() + await loadQuestions(setDetail.id) + await loadSet() + } catch (e) { + notifyApiError(e, editingQuestionId != null ? "Failed to update question" : "Failed to add question") + } finally { + setSavingQuestion(false) + } + } + + const handleRemoveQuestion = async (questionId: number) => { + if (!setDetail) return + setRemovingId(questionId) + try { + await detachPlacementQuestion(setDetail.id, questionId) + toast.success("Question removed from placement set") + await loadQuestions(setDetail.id) + await loadSet() + } catch (e) { + notifyApiError(e, "Failed to remove question") + } finally { + setRemovingId(null) + } + } + + const handleToggleQuestionStatus = async (row: PlacementQuestionRow) => { + const currentlyPublished = String(row.status).toUpperCase() === "PUBLISHED" + const nextStatus = currentlyPublished ? "DRAFT" : "PUBLISHED" + setStatusUpdatingId(row.questionId) + try { + const detail = await getPlacementQuestionDetail(row.questionId) + const questionType = + String(detail.question_type).toUpperCase() === "TRUE_FALSE" ? "TRUE_FALSE" : "MCQ" + const difficulty = + detail.difficulty_level === "MEDIUM" || detail.difficulty_level === "HARD" + ? detail.difficulty_level + : "EASY" + const questionText = + detail.question_text.trim() || + row.questionText.trim() || + `Question #${row.questionId}` + + await updateQuestion(row.questionId, { + question_text: questionText, + question_type: questionType, + difficulty_level: difficulty, + points: detail.points || row.points || 1, + status: nextStatus, + tips: detail.tips.trim() || undefined, + explanation: detail.explanation.trim() || undefined, + options: + detail.options.length > 0 + ? detail.options.map((o, idx) => ({ + option_order: o.option_order || idx + 1, + option_text: o.option_text, + is_correct: o.is_correct, + })) + : undefined, + }) + + setQuestions((prev) => + prev.map((q) => + q.questionId === row.questionId ? { ...q, status: nextStatus } : q, + ), + ) + toast.success( + nextStatus === "PUBLISHED" + ? "Question published for the placement test" + : "Question set to draft (hidden from the app)", + ) + } catch (e) { + notifyApiError(e, "Failed to update question status") + } finally { + setStatusUpdatingId(null) + } + } + + if (loading) { + return ( +
+ +
+ ) + } + + if (!setDetail) { + return ( +
+

Could not load placement assessment

+ +
+ ) + } + + const published = status === "PUBLISHED" + + return ( +
+
+
+
+ Content +
+

+ Initial placement assessment +

+

+ Manage the single learner placement test, its questions, and the A1–C2 score thresholds used + when grading submissions. +

+
+
+ + {published ? "Published" : "Draft"} + +
+ Live for learners + void handlePublishToggle(!published)} + disabled={savingSet} + aria-label="Publish placement assessment" + /> +
+ +
+
+ +
+ + + +
+
Questions
+
+ {setDetail.question_count ?? questions.length} +
+
+
+
+ + + +
+
Total points
+
{totalPoints}
+
+
+
+
+ +
+ {( + [ + { id: "set", label: "Placement set" }, + { id: "questions", label: "Questions" }, + { id: "thresholds", label: "Score thresholds" }, + ] as const + ).map((item) => ( + + ))} +
+ + {tab === "set" && ( + + + Placement set settings + + + + +