Compare commits

..

10 Commits

Author SHA1 Message Date
d063a82e2c Rebrand admin app for Rezina LMS 2026-10-20 14:55:43 +03:00
07c651fd17 Support free subscription plans and unique billing periods in admin.
Add is_free toggles with paid price validation, client-side period conflict checks, and Free price display aligned with backend subscription rules.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 21:35:53 +03:00
1799488127 Fix scheduled notification actions and speed up payments loading.
Add row actions with view details on scheduled jobs and replace client-side payment fetch-all with server-side pagination and parallel stats queries.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 11:33:26 +03:00
7b22d6d54c Require exam category when creating exam prep catalog courses.
Add IELTS/Duolingo selection to the admin form so catalog course creation satisfies backend validation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 11:03:08 +03:00
687eb964cc Enable skill-based course creation on the courses page.
Wire the skill-based catalog to LMS program/course APIs so admins can create, edit, and manage courses without the proficiency-only guard.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 15:41:56 +03:00
564fbf47a8 Disable Add Practice on Learn English detail pages when a direct practice exists.
Prefetch parent-scoped practices on course and module load and use has_practice from list APIs so the header button disables before opening the Practice tab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 17:05:47 +03:00
8649348120 Always show practice story fields on step 1 and add rich text editors.
Remove lesson-only field hiding from ContextStep and use TipTap for story description and quick tips in create/edit practice flows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 15:08:26 +03:00
1f25ff9e4e Show title and description fields when creating Learn English lesson practices.
Stop auto-filling lesson title and require story fields in the create/edit flow so lesson practices match module and course practice authoring.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 14:58:47 +03:00
bc0fc8e3e5 Fix attach-practice success back navigation for lesson context.
Show Back to Lessons and return to the lesson practices page when backTo=lesson.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 19:19:12 +03:00
c98efdc6c9 Fix practice unlink to remove only direct parent links across Learn English and Exam Prep.
Use server-side pagination and search for activity logs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 18:23:06 +03:00
60 changed files with 2529 additions and 903 deletions

View File

@ -1,10 +1,10 @@
# Yimaru Admin Panel # Rezina Admin Panel
Web admin console for **Yimaru Academy**. Team members manage LMS content (Learn English + Duolingo/IELTS), learners, subscriptions, payments, notifications, RBAC, analytics, and support workflows against the [Yimaru Backend](https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd) API. Web admin console for **Rezina Academy**. Team members manage LMS content (Learn English + Duolingo/IELTS), learners, subscriptions, payments, notifications, RBAC, analytics, and support workflows against the [Rezina Backend](https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd) API.
| | | | | |
|---|---| |---|---|
| **Package** | `yimaru-admin` | | **Package** | `rezina-admin` |
| **UI** | React 19 + TypeScript + Vite 7 | | **UI** | React 19 + TypeScript + Vite 7 |
| **Styling** | Tailwind CSS 3 + brand design tokens | | **Styling** | Tailwind CSS 3 + brand design tokens |
| **Routing** | React Router DOM 7 | | **Routing** | React Router DOM 7 |
@ -79,7 +79,7 @@ Companion backend docs: see Backend `README.md` and `docs/*-admin-panel-integrat
- **Node.js** 18+ (20 LTS recommended) - **Node.js** 18+ (20 LTS recommended)
- **npm** (lockfile: `package-lock.json`) - **npm** (lockfile: `package-lock.json`)
- Running **Yimaru Backend** with CORS / network access from the Vite origin - Running **Rezina Backend** with CORS / network access from the Vite origin
- Team account with appropriate RBAC permissions - Team account with appropriate RBAC permissions
--- ---
@ -88,7 +88,7 @@ Companion backend docs: see Backend `README.md` and `docs/*-admin-panel-integrat
```bash ```bash
git clone https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git git clone https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git
cd Yimaru-Admin cd Rezina-Admin
npm install npm install
@ -210,7 +210,7 @@ Always check `AppRoutes.tsx` for the canonical path list when adding pages.
## Project structure ## Project structure
``` ```
Yimaru-Admin/ Rezina-Admin/
├── public/ # Static assets ├── public/ # Static assets
├── docs/ # Front-end integration notes (e.g. course management) ├── docs/ # Front-end integration notes (e.g. course management)
├── src/ ├── src/
@ -382,15 +382,15 @@ Configure hosting env with production `VITE_API_BASE_URL` at **build time** (Vit
| Repo | Role | | Repo | Role |
|------|------| |------|------|
| [Yimaru-BackEnd](https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd) | REST API, migrations, Swagger | | [Rezina-BackEnd](https://gitea.yaltopia.com/Yimaru/Yimaru-BackEnd) | REST API, migrations, Swagger |
| [Yimaru-Admin](https://gitea.yaltopia.com/Yimaru/Yimaru-Admin) | This admin SPA | | [Rezina-Admin](https://gitea.yaltopia.com/Yimaru/Yimaru-Admin) | This admin SPA |
--- ---
## License ## License
Proprietary — Yaltopia / Yimaru Academy. Internal use only unless otherwise licensed. Proprietary — Yaltopia / Rezina Academy. Internal use only unless otherwise licensed.
--- ---
Developed by **Yaltopia Tech** for **Yimaru Academy**. Developed by **Yaltopia Tech** for **Rezina Academy**.

View File

@ -1,6 +1,6 @@
# Course Management API Integration Guide # Course Management API Integration Guide
This document describes the Course Management related APIs used by the admin frontend (`Yimaru-Admin`) and how to integrate them safely. This document describes the Course Management related APIs used by the admin frontend (`Rezina-Admin`) and how to integrate them safely.
It is based on: It is based on:
- `src/api/courses.api.ts` - `src/api/courses.api.ts`

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Generate Yimaru Admin Panel Developer Documentation (.docx).""" """Generate Rezina Admin Panel Developer Documentation (.docx)."""
from datetime import date from datetime import date
from pathlib import Path from pathlib import Path
@ -9,7 +9,7 @@ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.oxml.ns import qn from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor from docx.shared import Inches, Pt, RGBColor
OUT = Path(__file__).resolve().parent / "Yimaru_Admin_Developer_Documentation.docx" OUT = Path(__file__).resolve().parent / "Rezina_Admin_Developer_Documentation.docx"
def set_run_font(run, name="Calibri", size=11, bold=False, italic=False, color=None): def set_run_font(run, name="Calibri", size=11, bold=False, italic=False, color=None):
@ -126,11 +126,11 @@ def build():
# Title # Title
for _ in range(3): for _ in range(3):
doc.add_paragraph() doc.add_paragraph()
add_para(doc, "Yimaru Admin Panel", size=28, bold=True, align=WD_ALIGN_PARAGRAPH.CENTER, space_after=6) add_para(doc, "Rezina 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, "Developer Documentation", size=20, bold=True, align=WD_ALIGN_PARAGRAPH.CENTER, space_after=18)
add_para( add_para(
doc, doc,
"A practical guide for engineers building and maintaining the Yimaru Academy admin SPA", "A practical guide for engineers building and maintaining the Rezina Academy admin SPA",
size=12, size=12,
italic=True, italic=True,
align=WD_ALIGN_PARAGRAPH.CENTER, align=WD_ALIGN_PARAGRAPH.CENTER,
@ -138,7 +138,7 @@ def build():
) )
add_para( add_para(
doc, doc,
f"Package: yimaru-admin (React 19 · TypeScript · Vite 7)\n" f"Package: rezina-admin (React 19 · TypeScript · Vite 7)\n"
f"Document generated {date.today().isoformat()}\n" f"Document generated {date.today().isoformat()}\n"
f"Audience: Frontend / full-stack developers working on the admin console\n" f"Audience: Frontend / full-stack developers working on the admin console\n"
f"Source: https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git", f"Source: https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git",
@ -148,7 +148,7 @@ def build():
) )
add_para( add_para(
doc, doc,
"Internal / proprietary — Yaltopia Tech · Yimaru Academy", "Internal / proprietary — Yaltopia Tech · Rezina Academy",
size=9, size=9,
italic=True, italic=True,
align=WD_ALIGN_PARAGRAPH.CENTER, align=WD_ALIGN_PARAGRAPH.CENTER,
@ -159,10 +159,10 @@ def build():
add_heading_custom(doc, "1. Introduction", 1) add_heading_custom(doc, "1. Introduction", 1)
add_para( add_para(
doc, doc,
"The Yimaru Admin Panel is the staff-facing web app for Yimaru Academy. Content " "The Rezina Admin Panel is the staff-facing web app for Rezina Academy. Content "
"managers reorder courses at midnight, support agents triage issues, finance peeks at " "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 " "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.", "not own business rules; it talks to Rezina-Backend over HTTPS and presents them safely.",
) )
add_para( add_para(
doc, doc,
@ -273,7 +273,7 @@ main.tsx → App.tsx (session bootstrap) → AppRoutes
[ [
"Node.js 18+ (20 LTS recommended)", "Node.js 18+ (20 LTS recommended)",
"npm (package-lock.json is the source of truth)", "npm (package-lock.json is the source of truth)",
"A running Yimaru Backend reachable from the browser", "A running Rezina Backend reachable from the browser",
"A team account with the permissions you need to test", "A team account with the permissions you need to test",
], ],
) )
@ -281,7 +281,7 @@ main.tsx → App.tsx (session bootstrap) → AppRoutes
add_numbered( add_numbered(
doc, doc,
[ [
"git clone https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git && cd Yimaru-Admin", "git clone https://gitea.yaltopia.com/Yimaru/Yimaru-Admin.git && cd Rezina-Admin",
"npm install", "npm install",
"Create .env with VITE_API_BASE_URL (and VITE_GOOGLE_CLIENT_ID if testing Google login)", "Create .env with VITE_API_BASE_URL (and VITE_GOOGLE_CLIENT_ID if testing Google login)",
"npm run dev — usually http://localhost:5173", "npm run dev — usually http://localhost:5173",
@ -626,7 +626,7 @@ npm run build
[ [
"This repo README.md", "This repo README.md",
"docs/course-management-api-integration.md (if present in docs/)", "docs/course-management-api-integration.md (if present in docs/)",
"Backend README + docs/Yimaru_Backend_Developer_Documentation.docx", "Backend README + docs/Rezina_Backend_Developer_Documentation.docx",
"Backend docs/team-member-invitation-admin-panel-integration.md", "Backend docs/team-member-invitation-admin-panel-integration.md",
"Backend docs/team-member-refresh-token-admin-panel-integration.md", "Backend docs/team-member-refresh-token-admin-panel-integration.md",
"Backend docs/csv-export-admin-panel-integration.md", "Backend docs/csv-export-admin-panel-integration.md",
@ -652,7 +652,7 @@ npm run build
) )
add_para( add_para(
doc, doc,
"— Yaltopia engineering, for Yimaru Academy admin developers", "— Yaltopia engineering, for Rezina Academy admin developers",
space_before=16, space_before=16,
italic=True, italic=True,
) )

View File

@ -1,4 +1,4 @@
"""Generate Yimaru Admin UAT document from template.""" """Generate Rezina Admin UAT document from template."""
from __future__ import annotations from __future__ import annotations
import copy import copy
@ -58,16 +58,16 @@ def replace_document() -> None:
tables = [Table(child, doc) for child in doc.element.body if child.tag.split("}")[-1] == "tbl"] tables = [Table(child, doc) for child in doc.element.body if child.tag.split("}")[-1] == "tbl"]
paragraph_updates: dict[int, str] = { paragraph_updates: dict[int, str] = {
0: "UAT Document: Yimaru Admin Panel", 0: "UAT Document: Rezina Admin Panel",
1: "1. UAT Objective", 1: "1. UAT Objective",
2: ( 2: (
"To confirm that the Yimaru Admin Panel meets business requirements, role-based access " "To confirm that the Rezina Admin Panel meets business requirements, role-based access "
"expectations, security standards, and operational readiness before production release. " "expectations, security standards, and operational readiness before production release. "
"This panel is used by internal teams to manage learners, learning content, subscriptions, " "This panel is used by internal teams to manage learners, learning content, subscriptions, "
"notifications, payments, and platform operations for the Yimaru LMS mobile application." "notifications, payments, and platform operations for the Rezina LMS mobile application."
), ),
3: "2. Scope", 3: "2. Scope",
4: "This UAT covers the Yimaru Admin Panel web application, including:", 4: "This UAT covers the Rezina Admin Panel web application, including:",
5: "Authentication & team onboarding", 5: "Authentication & team onboarding",
6: "Dashboard and analytics", 6: "Dashboard and analytics",
7: "User management (learners, groups, deletion requests)", 7: "User management (learners, groups, deletion requests)",
@ -103,7 +103,7 @@ def replace_document() -> None:
41: "Production deployment readiness is confirmed", 41: "Production deployment readiness is confirmed",
42: "7. UAT Test Cases", 42: "7. UAT Test Cases",
43: "A. Authentication, Onboarding & Public Pages", 43: "A. Authentication, Onboarding & Public Pages",
46: "B. Yimaru Admin Panel — Core Modules (incl. bulk & scheduled notifications)", 46: "B. Rezina Admin Panel — Core Modules (incl. bulk & scheduled notifications)",
49: "8. Cross-System UAT Tests", 49: "8. Cross-System UAT Tests",
52: "9. Defect Log", 52: "9. Defect Log",
55: "10. Sign-Off", 55: "10. Sign-Off",
@ -137,7 +137,7 @@ def replace_document() -> None:
tables[1], tables[1],
[ [
["Environment", "UAT / Staging"], ["Environment", "UAT / Staging"],
["Application", "Yimaru Admin Panel (React + Vite SPA)"], ["Application", "Rezina Admin Panel (React + Vite SPA)"],
["Admin URL", "<staging-admin-url>"], ["Admin URL", "<staging-admin-url>"],
["API Backend", "<staging-api-url>"], ["API Backend", "<staging-api-url>"],
["Browsers", "Chrome (latest), Microsoft Edge, Firefox, Safari"], ["Browsers", "Chrome (latest), Microsoft Edge, Firefox, Safari"],

View File

@ -4,10 +4,10 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Yimaru Admin</title> <title>Rezina Admin</title>
<script> <script>
(function () { (function () {
var key = "yimaru-admin-theme"; var key = "rezina-admin-theme";
var stored = localStorage.getItem(key); var stored = localStorage.getItem(key);
var root = document.documentElement; var root = document.documentElement;
var systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches; var systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;

653
package-lock.json generated
View File

@ -1,11 +1,11 @@
{ {
"name": "yimaru-admin", "name": "rezina-admin",
"version": "0.0.0", "version": "0.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "yimaru-admin", "name": "rezina-admin",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
@ -17,6 +17,9 @@
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@tiptap/extension-placeholder": "^3.30.2",
"@tiptap/react": "^3.30.2",
"@tiptap/starter-kit": "^3.30.2",
"axios": "^1.13.2", "axios": "^1.13.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
@ -94,6 +97,7 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5", "@babel/generator": "^7.28.5",
@ -362,6 +366,7 @@
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
@ -1011,6 +1016,7 @@
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz", "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz",
"integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==", "integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@floating-ui/core": "^1.7.3", "@floating-ui/core": "^1.7.3",
"@floating-ui/utils": "^0.2.10" "@floating-ui/utils": "^0.2.10"
@ -2690,6 +2696,453 @@
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@tiptap/core": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.30.2.tgz",
"integrity": "sha512-QbZC/s1OOqcoUdkhIY16TjR/gCtR0qAk9e4bJwUqOJqZuv5ozqCL5hzWm22jjTPp6c6Ei2tPd6t30VwfIKW4lQ==",
"license": "MIT",
"peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-blockquote": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.30.2.tgz",
"integrity": "sha512-BOkwhZenek7vzXBOgKppSrlx4YryBdAYu1p1MXKn0R9A9eNmE2HVhmm0gG49+E8BhsE/TG8wKVclwET42JJiIg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-bold": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.30.2.tgz",
"integrity": "sha512-MsvJhPgYejY2D9MhwYJv8AmscozvLBI8qtJ7YLdYZBWkMR4bgmxHq5+xqEfBsao9bOMMwBon9p3+P+/Tq5ReWA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-bubble-menu": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.30.2.tgz",
"integrity": "sha512-oS0WiWNXHKpiPYMkcnHm1j7iEvufTGGtLFtcJJd3olb5OS6V2acoXVDL0nNJDmRQ32K3QXut3fbRcMseMxT+lw==",
"license": "MIT",
"optional": true,
"dependencies": {
"@floating-ui/dom": "^1.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-bullet-list": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.30.2.tgz",
"integrity": "sha512-+awIL/TUz4aB3rL68igU1rWfaaoBIAkPcakkktkRq8gYf0bd9eSb48P6kHkpx/3q+JyK7g9vsnltLNHNh6twnA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extension-list": "3.30.2"
}
},
"node_modules/@tiptap/extension-code": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.30.2.tgz",
"integrity": "sha512-r8EZk3R9yGpF6v5xxafAU1HwrD/e+RpbfnmVi2TeB/ZHAsVO62fW96E32G0t6IdaCtOFtAd85hkDAaOfCT4yGg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-code-block": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.30.2.tgz",
"integrity": "sha512-9otGKaQZmePHrLXFtCtz+BYDn5z4sSumTkUqQIQHz0gVxwPoTi7g51RedwxvViTb/zu2XV5ROXYLHIxKxypMPg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-document": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.30.2.tgz",
"integrity": "sha512-+xIv67V+/2L1uvz98FAT5W7kWEfHwfNV3MD7b4UsKPU0lhcCWuVOXy0JB8yYmdNExqpI7xT9g3MWzREoBvBQSg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-dropcursor": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.30.2.tgz",
"integrity": "sha512-nyRKUmItATnKI9AiRChmjhcBbCEsNxRu+AaCz+cx8EvnAcNHsVRdNYL5PmBs3WlNA/Et4Eb2DG0hVQDnNF61eg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extensions": "3.30.2"
}
},
"node_modules/@tiptap/extension-floating-menu": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.30.2.tgz",
"integrity": "sha512-A8PLvvh8W6PUMrqh+EpBerxm+Ucr0irGxJvwAnzYQmNGNIJ9U4OVgw4OcEU+9JH0gMmEzDcHzMPP2s/s1lIcyw==",
"license": "MIT",
"optional": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@floating-ui/dom": "^1.0.0",
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-gapcursor": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.30.2.tgz",
"integrity": "sha512-7Xk0ut6FM+RAsvKxDN3bAtk7zvYZ6Aa8pawJ6s7dLAmLR9JwrZevlcL4FSrj4bR7rqKOj92RYCFxzgTEbWimag==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extensions": "3.30.2"
}
},
"node_modules/@tiptap/extension-hard-break": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.30.2.tgz",
"integrity": "sha512-IxSNgmG3d4OZdUTeebrOI7SxdIWXXJqlcGiSNDabWqxipUitfy3mZ3gDDE6G01koKxZRbhz4KIplAZlpxnTFSg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-heading": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.30.2.tgz",
"integrity": "sha512-PblDvgSJ05p1t6hzyPi02xeiBjB0M2abReoGEImqSWCy79UqnAGacgsZo4EeEawtJV1NEP8chhvmX+nRtzdT1A==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-horizontal-rule": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.30.2.tgz",
"integrity": "sha512-j8aswLTsuEdJKC62DF+kw0EgvIRL7QMUyAVp2fdjR0qgM0ZVlEwCC4qIEq3kK9tFVU4kRtQ5BSj/jn6QwrlbCA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-italic": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.30.2.tgz",
"integrity": "sha512-pp8uaiuXsUbLm5rYzR1jlWbwm1mAahRajdHwAKBtthFRB2rDvC7ZWhKaCSoKhZvfIDRmu9/B67+uAHoutL0dCA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-link": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.30.2.tgz",
"integrity": "sha512-jwdcymKcrbFpj5hRAuGVLCq8FieVkGFnENyroYmvkad+XAt8ZLy/MTFYRN6SK3ukH6PZMY7H4iObGtciQaC5nw==",
"license": "MIT",
"dependencies": {
"linkifyjs": "^4.3.3"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-list": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.30.2.tgz",
"integrity": "sha512-MIUpo1Bd9Rf1Qg+TNYNwDZ4xsfFeQahjU9Xhy6UcaszKQzbAM7KCzn5BObNytK1NdcqNHsC8Wj5vFvMKEzrXdw==",
"license": "MIT",
"peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/extension-list-item": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.30.2.tgz",
"integrity": "sha512-HWgRCRlGxulE+hN1VUcnWD6P2NE08VBgGtcaxOfdXVqaI93BCK6AhRQZGpLsfKgajLk+5DXTBraaitwnBqzCxg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extension-list": "3.30.2"
}
},
"node_modules/@tiptap/extension-list-keymap": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.30.2.tgz",
"integrity": "sha512-TTve3WOlQaYu1ahMqsQ/T0wzaxfgZvcOl3/OuPyInOi8QtxXhqGhFjmYe5jOr56G9W2QDuFWVsZecVwfDte9zg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extension-list": "3.30.2"
}
},
"node_modules/@tiptap/extension-ordered-list": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.30.2.tgz",
"integrity": "sha512-Z7OO1HcF0idda1n6vodXeQ3h2ylN9JR4IfIGUYkar5Xl9JusK8PDETTBQZQn//96p49I2d+GoWsD2LXPtjHXXg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extension-list": "3.30.2"
}
},
"node_modules/@tiptap/extension-paragraph": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.30.2.tgz",
"integrity": "sha512-ulEu3LNt+kPVAWEnrhoz13Fs8Q/v/8NUxQbAeteuBchQ8joxJXuWExhpy1fUfZir5+b+W5z7/NesgPjZQfv47w==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-placeholder": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-placeholder/-/extension-placeholder-3.30.2.tgz",
"integrity": "sha512-Bj1seUvPCoRrD/LpzMoKD+jQIjxuc+oq931GpPq4wobSUUbD4pF/0NMwpCLpiHO19QnTQz8+9p2dqPdlc44LHA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/extensions": "3.30.2"
}
},
"node_modules/@tiptap/extension-strike": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.30.2.tgz",
"integrity": "sha512-fBLxMXz6hYIURzLOD+/L6aVATztsKham00ANWmGi13vN0hx2lQMYZffN+gR+QqiCDfMQxBXzrf5a7tJuDiQHLQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-text": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.30.2.tgz",
"integrity": "sha512-n/iZnirgRmXet6f97kolAnP3j8DsgLSiTbz/KLWc8eBYiFmkjRzkuisOm5xuGdfGIxwpB4x3tlSF4ef4DLnbRg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extension-underline": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.30.2.tgz",
"integrity": "sha512-SZiTMnvqXcnrtJX+X25ZbYsuDO83haGOVMBD/O+mAWYNYXhaSc5Rkph5czzItxrd+Yyp/vs4PiwD7XTNbfqmpA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2"
}
},
"node_modules/@tiptap/extensions": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.30.2.tgz",
"integrity": "sha512-2LqAHXk26QDsryW+beECxYeBzv5Ylk4GuB3cOmfghS7/G37R2W+Te3TkUK7BT0EWoDryvBT57/5q0DEFIhfZZg==",
"license": "MIT",
"peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2"
}
},
"node_modules/@tiptap/pm": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.30.2.tgz",
"integrity": "sha512-BJN8tUx4ppFN3R3cV/FJfrJbJkvo1lj4uciq+nwpjwzdRvFzqIuglWf+HLcJ6CwlYpLOHp7ArgkBg4Q5e60Gog==",
"license": "MIT",
"peer": true,
"dependencies": {
"prosemirror-changeset": "^2.4.1",
"prosemirror-commands": "^1.7.1",
"prosemirror-dropcursor": "^1.8.2",
"prosemirror-gapcursor": "^1.4.1",
"prosemirror-history": "^1.5.0",
"prosemirror-inputrules": "^1.5.1",
"prosemirror-keymap": "^1.2.3",
"prosemirror-model": "^1.25.11",
"prosemirror-schema-list": "^1.5.1",
"prosemirror-state": "^1.4.4",
"prosemirror-tables": "^1.8.5",
"prosemirror-transform": "^1.12.0",
"prosemirror-view": "^1.41.9"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
}
},
"node_modules/@tiptap/react": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/react/-/react-3.30.2.tgz",
"integrity": "sha512-7hGaTstpUeTmQ008mCPkjz+GSlChWhucgy+PeX0z93v4+nh7qM5F+0lh+kJ9zo6Os5abO7v36GtgHRZdQI6+FQ==",
"license": "MIT",
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"fast-equals": "^5.3.3",
"use-sync-external-store": "^1.4.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"optionalDependencies": {
"@tiptap/extension-bubble-menu": "^3.30.2",
"@tiptap/extension-floating-menu": "^3.30.2"
},
"peerDependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/pm": "3.30.2",
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/@tiptap/starter-kit": {
"version": "3.30.2",
"resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.30.2.tgz",
"integrity": "sha512-fJSrhW1CyD4sjYA20evSP4Cp13B/HhbxCdM974K0xpHOVqvCtNU9w2s9hfq9mg2yGoU7MSNHKNYMkJjIi2/Xyw==",
"license": "MIT",
"dependencies": {
"@tiptap/core": "3.30.2",
"@tiptap/extension-blockquote": "3.30.2",
"@tiptap/extension-bold": "3.30.2",
"@tiptap/extension-bullet-list": "3.30.2",
"@tiptap/extension-code": "3.30.2",
"@tiptap/extension-code-block": "3.30.2",
"@tiptap/extension-document": "3.30.2",
"@tiptap/extension-dropcursor": "3.30.2",
"@tiptap/extension-gapcursor": "3.30.2",
"@tiptap/extension-hard-break": "3.30.2",
"@tiptap/extension-heading": "3.30.2",
"@tiptap/extension-horizontal-rule": "3.30.2",
"@tiptap/extension-italic": "3.30.2",
"@tiptap/extension-link": "3.30.2",
"@tiptap/extension-list": "3.30.2",
"@tiptap/extension-list-item": "3.30.2",
"@tiptap/extension-list-keymap": "3.30.2",
"@tiptap/extension-ordered-list": "3.30.2",
"@tiptap/extension-paragraph": "3.30.2",
"@tiptap/extension-strike": "3.30.2",
"@tiptap/extension-text": "3.30.2",
"@tiptap/extension-underline": "3.30.2",
"@tiptap/extensions": "3.30.2",
"@tiptap/pm": "3.30.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
}
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@ -2818,6 +3271,7 @@
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==", "integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~7.16.0" "undici-types": "~7.16.0"
} }
@ -2826,8 +3280,8 @@
"version": "19.2.7", "version": "19.2.7",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz",
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==", "integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
"dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"csstype": "^3.2.2" "csstype": "^3.2.2"
} }
@ -2836,8 +3290,8 @@
"version": "19.2.3", "version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"peerDependencies": { "peerDependencies": {
"@types/react": "^19.2.0" "@types/react": "^19.2.0"
} }
@ -2893,6 +3347,7 @@
"integrity": "sha512-6/cmF2piao+f6wSxUsJLZjck7OQsYyRtcOZS02k7XINSNlz93v6emM8WutDQSXnroG2xwYlEVHJI+cPA7CPM3Q==", "integrity": "sha512-6/cmF2piao+f6wSxUsJLZjck7OQsYyRtcOZS02k7XINSNlz93v6emM8WutDQSXnroG2xwYlEVHJI+cPA7CPM3Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.50.0", "@typescript-eslint/scope-manager": "8.50.0",
"@typescript-eslint/types": "8.50.0", "@typescript-eslint/types": "8.50.0",
@ -3144,6 +3599,7 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@ -3382,6 +3838,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.9.0", "baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759", "caniuse-lite": "^1.0.30001759",
@ -3642,7 +4099,6 @@
"version": "3.2.3", "version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/custom-error-instance": { "node_modules/custom-error-instance": {
@ -3979,6 +4435,7 @@
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@ -4170,6 +4627,15 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-equals": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.1.tgz",
"integrity": "sha512-DjlFSM5Pk9cGcL0q5QXl66eGzx0N6szNgaswwc5ZphlBohjTVJSnGgI+rJVOgOi65qUoQnDZN4nDqi33udtydQ==",
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/fast-glob": { "node_modules/fast-glob": {
"version": "3.3.3", "version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
@ -4816,6 +5282,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/linkifyjs": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz",
"integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==",
"license": "MIT"
},
"node_modules/locate-path": { "node_modules/locate-path": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@ -5100,6 +5572,12 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/orderedmap": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
"integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
"license": "MIT"
},
"node_modules/p-limit": { "node_modules/p-limit": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
@ -5185,6 +5663,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@ -5238,6 +5717,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"nanoid": "^3.3.11", "nanoid": "^3.3.11",
"picocolors": "^1.1.1", "picocolors": "^1.1.1",
@ -5395,6 +5875,145 @@
"signal-exit": "^3.0.2" "signal-exit": "^3.0.2"
} }
}, },
"node_modules/prosemirror-changeset": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.1.tgz",
"integrity": "sha512-96WBLhOaYhJ+kPhLg3uW359Tz6I/MfcrQfL4EGv4SrcqKEMC1gmoGrXHecPE8eOwTVCJ4IwgfzM8fFad25wNfw==",
"license": "MIT",
"dependencies": {
"prosemirror-transform": "^1.0.0"
}
},
"node_modules/prosemirror-commands": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz",
"integrity": "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==",
"license": "MIT",
"dependencies": {
"prosemirror-model": "^1.0.0",
"prosemirror-state": "^1.0.0",
"prosemirror-transform": "^1.10.2"
}
},
"node_modules/prosemirror-dropcursor": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.3.tgz",
"integrity": "sha512-FoYbsJR8gK+DGlqhNoE29Loa38eIZPzQRIb1VMaDNBoo4OLP6vVof/jR8qFY/6XvUd6Dhug8MDCHl2a/h8RTfQ==",
"license": "MIT",
"dependencies": {
"prosemirror-state": "^1.0.0",
"prosemirror-transform": "^1.1.0",
"prosemirror-view": "^1.1.0"
}
},
"node_modules/prosemirror-gapcursor": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz",
"integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==",
"license": "MIT",
"dependencies": {
"prosemirror-keymap": "^1.0.0",
"prosemirror-model": "^1.0.0",
"prosemirror-state": "^1.0.0",
"prosemirror-view": "^1.0.0"
}
},
"node_modules/prosemirror-history": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz",
"integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==",
"license": "MIT",
"dependencies": {
"prosemirror-state": "^1.2.2",
"prosemirror-transform": "^1.0.0",
"prosemirror-view": "^1.31.0",
"rope-sequence": "^1.3.0"
}
},
"node_modules/prosemirror-inputrules": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz",
"integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==",
"license": "MIT",
"dependencies": {
"prosemirror-state": "^1.0.0",
"prosemirror-transform": "^1.0.0"
}
},
"node_modules/prosemirror-keymap": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",
"integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",
"license": "MIT",
"dependencies": {
"prosemirror-state": "^1.0.0",
"w3c-keyname": "^2.2.0"
}
},
"node_modules/prosemirror-model": {
"version": "1.25.11",
"resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.11.tgz",
"integrity": "sha512-QWg9RhnpLlogAmp3p96uEFrE5txQpFynd4vhBAELkwgOCWQs/X0yCzB3/hrHqiPwf91RG5KyWq6553zs9JqIOQ==",
"license": "MIT",
"dependencies": {
"orderedmap": "^2.0.0"
}
},
"node_modules/prosemirror-schema-list": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz",
"integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==",
"license": "MIT",
"dependencies": {
"prosemirror-model": "^1.0.0",
"prosemirror-state": "^1.0.0",
"prosemirror-transform": "^1.7.3"
}
},
"node_modules/prosemirror-state": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
"integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
"license": "MIT",
"dependencies": {
"prosemirror-model": "^1.0.0",
"prosemirror-transform": "^1.0.0",
"prosemirror-view": "^1.27.0"
}
},
"node_modules/prosemirror-tables": {
"version": "1.8.5",
"resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz",
"integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==",
"license": "MIT",
"dependencies": {
"prosemirror-keymap": "^1.2.3",
"prosemirror-model": "^1.25.4",
"prosemirror-state": "^1.4.4",
"prosemirror-transform": "^1.10.5",
"prosemirror-view": "^1.41.4"
}
},
"node_modules/prosemirror-transform": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz",
"integrity": "sha512-GxboyN4AMIsoHNtz5uf2r2Ru551i5hWeCMD6E2Ib4Eogqoub0NflniaBPVQ4MrGE5yZ8JV9tUHg9qcZTTrcN4w==",
"license": "MIT",
"dependencies": {
"prosemirror-model": "^1.21.0"
}
},
"node_modules/prosemirror-view": {
"version": "1.42.2",
"resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.2.tgz",
"integrity": "sha512-Pdg0l5kXm8aLDquFAnQFTCITg0q44sLqBlHlpsVLD9segdOao8TOfQdAhCrCXyVgPSRr6UDDROOIWA3bIrN9YQ==",
"license": "MIT",
"dependencies": {
"prosemirror-model": "^1.25.8",
"prosemirror-state": "^1.0.0",
"prosemirror-transform": "^1.1.0"
}
},
"node_modules/proxy-from-env": { "node_modules/proxy-from-env": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
@ -5443,6 +6062,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@ -5452,6 +6072,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"scheduler": "^0.27.0" "scheduler": "^0.27.0"
}, },
@ -5463,13 +6084,15 @@
"version": "19.2.5", "version": "19.2.5",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.5.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.5.tgz",
"integrity": "sha512-Dn0t8IQhCmeIT3wu+Apm1/YVsJXsGWi6k4sPdnBIdqMVtHtv0IGi6dcpNpNkNac0zB2uUAqNX3MHzN8c+z2rwQ==", "integrity": "sha512-Dn0t8IQhCmeIT3wu+Apm1/YVsJXsGWi6k4sPdnBIdqMVtHtv0IGi6dcpNpNkNac0zB2uUAqNX3MHzN8c+z2rwQ==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/react-redux": { "node_modules/react-redux": {
"version": "9.2.0", "version": "9.2.0",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/use-sync-external-store": "^0.0.6", "@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0" "use-sync-external-store": "^1.4.0"
@ -5675,7 +6298,8 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/redux-thunk": { "node_modules/redux-thunk": {
"version": "3.1.0", "version": "3.1.0",
@ -5812,6 +6436,12 @@
"fsevents": "~2.3.2" "fsevents": "~2.3.2"
} }
}, },
"node_modules/rope-sequence": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz",
"integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==",
"license": "MIT"
},
"node_modules/run-parallel": { "node_modules/run-parallel": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
@ -6158,6 +6788,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@ -6335,6 +6966,7 @@
"integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==", "integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.27.0", "esbuild": "^0.27.0",
"fdir": "^6.5.0", "fdir": "^6.5.0",
@ -6404,6 +7036,12 @@
} }
} }
}, },
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/which": { "node_modules/which": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@ -6472,6 +7110,7 @@
"integrity": "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw==", "integrity": "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"
} }

View File

@ -1,5 +1,5 @@
{ {
"name": "yimaru-admin", "name": "rezina-admin",
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
@ -19,6 +19,9 @@
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@tiptap/extension-placeholder": "^3.30.2",
"@tiptap/react": "^3.30.2",
"@tiptap/starter-kit": "^3.30.2",
"axios": "^1.13.2", "axios": "^1.13.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",

View File

@ -3,7 +3,7 @@ import { AppRoutes } from "./app/AppRoutes"
import { useTheme } from "./contexts/ThemeContext" import { useTheme } from "./contexts/ThemeContext"
import { clearTeamSession } from "./lib/teamAuthStorage" import { clearTeamSession } from "./lib/teamAuthStorage"
const SESSION_KEY = "yimaru_session_active" const SESSION_KEY = "rezina_session_active"
/** /**
* Clear persisted team tokens when this browser tab session is new. * Clear persisted team tokens when this browser tab session is new.
@ -37,16 +37,16 @@ function AppToaster() {
duration={4200} duration={4200}
toastOptions={{ toastOptions={{
classNames: { classNames: {
toast: "yimaru-toast", toast: "rezina-toast",
title: "yimaru-toast__title", title: "rezina-toast__title",
description: "yimaru-toast__description", description: "rezina-toast__description",
actionButton: "yimaru-toast__action", actionButton: "rezina-toast__action",
cancelButton: "yimaru-toast__cancel", cancelButton: "rezina-toast__cancel",
closeButton: "yimaru-toast__close", closeButton: "rezina-toast__close",
success: "yimaru-toast--success", success: "rezina-toast--success",
error: "yimaru-toast--error", error: "rezina-toast--error",
warning: "yimaru-toast--warning", warning: "rezina-toast--warning",
info: "yimaru-toast--info", info: "rezina-toast--info",
}, },
}} }}
/> />

View File

@ -114,6 +114,7 @@ function buildQueryParams(filters?: ActivityLogFilters): Record<string, string |
if (filters?.resource_id != null) params.resource_id = filters.resource_id if (filters?.resource_id != null) params.resource_id = filters.resource_id
if (filters?.after?.trim()) params.after = filters.after.trim() if (filters?.after?.trim()) params.after = filters.after.trim()
if (filters?.before?.trim()) params.before = filters.before.trim() if (filters?.before?.trim()) params.before = filters.before.trim()
if (filters?.search?.trim()) params.search = filters.search.trim()
return params return params
} }

View File

@ -26,6 +26,7 @@ function normalizeSubscriptionPlan(raw: unknown): SubscriptionPlan | null {
price: Number(raw.price ?? 0), price: Number(raw.price ?? 0),
currency: String(raw.currency ?? "ETB"), currency: String(raw.currency ?? "ETB"),
is_lifetime: Boolean(raw.is_lifetime ?? false), is_lifetime: Boolean(raw.is_lifetime ?? false),
is_free: Boolean(raw.is_free ?? false),
is_active: Boolean(raw.is_active ?? true), is_active: Boolean(raw.is_active ?? true),
created_at: String(raw.created_at ?? ""), created_at: String(raw.created_at ?? ""),
} }

View File

@ -10,7 +10,7 @@ export function BrandLogo({
return ( return (
<img <img
src={logoSrc} src={logoSrc}
alt="Yimaru Academy" alt="Rezina Academy"
className={`${className} ${variant === "dark" ? "brightness-0" : ""}`} className={`${className} ${variant === "dark" ? "brightness-0" : ""}`}
/> />
); );

View File

@ -25,13 +25,13 @@ function getLevelAccentClass(level: string) {
switch (level) { switch (level) {
case "error": case "error":
case "critical": case "critical":
return "yimaru-realtime-popup--error" return "rezina-realtime-popup--error"
case "warning": case "warning":
return "yimaru-realtime-popup--warning" return "rezina-realtime-popup--warning"
case "success": case "success":
return "yimaru-realtime-popup--success" return "rezina-realtime-popup--success"
default: default:
return "yimaru-realtime-popup--info" return "rezina-realtime-popup--info"
} }
} }
@ -53,20 +53,20 @@ export function showNotificationRealtimePopup(
(toastId) => ( (toastId) => (
<div <div
className={cn( className={cn(
"yimaru-realtime-popup pointer-events-auto", "rezina-realtime-popup pointer-events-auto",
getLevelAccentClass(notification.level), getLevelAccentClass(notification.level),
)} )}
role="status" role="status"
aria-live="polite" aria-live="polite"
> >
<div className="yimaru-realtime-popup__header"> <div className="rezina-realtime-popup__header">
<div className="yimaru-realtime-popup__meta"> <div className="rezina-realtime-popup__meta">
<span className="yimaru-realtime-popup__type"> <span className="rezina-realtime-popup__type">
{formatNotificationTypeLabel(notification.type)} {formatNotificationTypeLabel(notification.type)}
</span> </span>
<span className="yimaru-realtime-popup__dot" aria-hidden /> <span className="rezina-realtime-popup__dot" aria-hidden />
<time <time
className="yimaru-realtime-popup__time" className="rezina-realtime-popup__time"
dateTime={notification.timestamp} dateTime={notification.timestamp}
> >
{formatNotificationTimestamp(notification.timestamp)} {formatNotificationTimestamp(notification.timestamp)}
@ -74,7 +74,7 @@ export function showNotificationRealtimePopup(
</div> </div>
<button <button
type="button" type="button"
className="yimaru-realtime-popup__close" className="rezina-realtime-popup__close"
onClick={() => toast.dismiss(toastId)} onClick={() => toast.dismiss(toastId)}
aria-label="Dismiss notification" aria-label="Dismiss notification"
> >
@ -82,19 +82,19 @@ export function showNotificationRealtimePopup(
</button> </button>
</div> </div>
<div className="yimaru-realtime-popup__body"> <div className="rezina-realtime-popup__body">
<div className={cn("yimaru-realtime-popup__icon", cfg.bg)}> <div className={cn("rezina-realtime-popup__icon", cfg.bg)}>
<Icon className={cn("h-4 w-4", cfg.color)} /> <Icon className={cn("h-4 w-4", cfg.color)} />
</div> </div>
<div className="yimaru-realtime-popup__content"> <div className="rezina-realtime-popup__content">
<p className="yimaru-realtime-popup__title">{title}</p> <p className="rezina-realtime-popup__title">{title}</p>
{showMessage ? ( {showMessage ? (
<p className="yimaru-realtime-popup__message">{message}</p> <p className="rezina-realtime-popup__message">{message}</p>
) : null} ) : null}
<button <button
type="button" type="button"
className="yimaru-realtime-popup__action" className="rezina-realtime-popup__action"
onClick={() => { onClick={() => {
toast.dismiss(toastId) toast.dismiss(toastId)
options?.onOpen?.(notification) options?.onOpen?.(notification)
@ -111,7 +111,7 @@ export function showNotificationRealtimePopup(
position: "bottom-right", position: "bottom-right",
duration: 8000, duration: 8000,
unstyled: true, unstyled: true,
className: "yimaru-realtime-popup-host", className: "rezina-realtime-popup-host",
}, },
) )
} }

View File

@ -14,7 +14,7 @@ export function SidebarLogo({ collapsed }: SidebarLogoProps) {
<span className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-500"> <span className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-500">
<img <img
src={logoSymbolSrc} src={logoSymbolSrc}
alt="Yimaru" alt="Rezina"
className="h-6 w-6" className="h-6 w-6"
/> />
</span> </span>

View File

@ -0,0 +1,33 @@
import { cn } from "../../lib/utils"
import { looksLikeHtml, stripHtml } from "../../lib/richText"
export interface RichTextContentProps {
html?: string | null
className?: string
emptyLabel?: string
}
export function RichTextContent({
html,
className,
emptyLabel = "—",
}: RichTextContentProps) {
const trimmed = html?.trim() ?? ""
if (!trimmed) {
return <span className={cn("text-grayScale-400", className)}>{emptyLabel}</span>
}
if (looksLikeHtml(trimmed)) {
return (
<div
className={cn(
"prose prose-sm max-w-none text-grayScale-700 prose-p:my-1 prose-ul:my-1 prose-ol:my-1",
className,
)}
dangerouslySetInnerHTML={{ __html: trimmed }}
/>
)
}
return <span className={className}>{stripHtml(trimmed)}</span>
}

View File

@ -0,0 +1,185 @@
import { useEffect, type ReactNode } from "react"
import { EditorContent, useEditor } from "@tiptap/react"
import Placeholder from "@tiptap/extension-placeholder"
import StarterKit from "@tiptap/starter-kit"
import {
Bold,
Italic,
List,
ListOrdered,
Redo2,
Undo2,
} from "lucide-react"
import { cn } from "../../lib/utils"
import { richTextPlainLength } from "../../lib/richText"
export interface RichTextEditorProps {
value?: string
onChange: (html: string) => void
placeholder?: string
maxLength?: number
className?: string
editorClassName?: string
disabled?: boolean
}
function ToolbarButton({
active,
disabled,
onClick,
label,
children,
}: {
active?: boolean
disabled?: boolean
onClick: () => void
label: string
children: ReactNode
}) {
return (
<button
type="button"
aria-label={label}
title={label}
disabled={disabled}
onClick={onClick}
className={cn(
"inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-grayScale-600 transition-colors",
"hover:bg-grayScale-100 hover:text-grayScale-900 disabled:cursor-not-allowed disabled:opacity-40",
active && "border-brand-200 bg-brand-50 text-brand-700",
)}
>
{children}
</button>
)
}
export function RichTextEditor({
value = "",
onChange,
placeholder = "Write here…",
maxLength,
className,
editorClassName,
disabled = false,
}: RichTextEditorProps) {
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: false,
codeBlock: false,
blockquote: false,
horizontalRule: false,
}),
Placeholder.configure({ placeholder }),
],
content: value || "",
editable: !disabled,
onUpdate: ({ editor: currentEditor }) => {
const html = currentEditor.getHTML()
if (maxLength != null && richTextPlainLength(html) > maxLength) {
currentEditor.commands.setContent(value || "", { emitUpdate: false })
return
}
onChange(html === "<p></p>" ? "" : html)
},
editorProps: {
attributes: {
class: cn(
"min-h-[120px] px-4 py-3 text-sm leading-relaxed text-grayScale-800 outline-none",
"prose prose-sm max-w-none prose-p:my-2 prose-ul:my-2 prose-ol:my-2",
editorClassName,
),
},
},
})
useEffect(() => {
if (!editor) return
const current = editor.getHTML()
const normalizedCurrent = current === "<p></p>" ? "" : current
const normalizedValue = value || ""
if (normalizedCurrent !== normalizedValue) {
editor.commands.setContent(normalizedValue || "", { emitUpdate: false })
}
}, [editor, value])
useEffect(() => {
if (!editor) return
editor.setEditable(!disabled)
}, [editor, disabled])
const plainLength = richTextPlainLength(value)
const atLimit = maxLength != null && plainLength >= maxLength
return (
<div
className={cn(
"overflow-hidden rounded-xl border border-grayScale-200 bg-white focus-within:border-brand-400 focus-within:ring-2 focus-within:ring-brand-100",
disabled && "opacity-60",
className,
)}
>
<div className="flex flex-wrap items-center gap-1 border-b border-grayScale-100 bg-grayScale-50/80 px-2 py-2">
<ToolbarButton
label="Bold"
disabled={disabled || !editor}
active={editor?.isActive("bold")}
onClick={() => editor?.chain().focus().toggleBold().run()}
>
<Bold className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton
label="Italic"
disabled={disabled || !editor}
active={editor?.isActive("italic")}
onClick={() => editor?.chain().focus().toggleItalic().run()}
>
<Italic className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton
label="Bullet list"
disabled={disabled || !editor}
active={editor?.isActive("bulletList")}
onClick={() => editor?.chain().focus().toggleBulletList().run()}
>
<List className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton
label="Numbered list"
disabled={disabled || !editor}
active={editor?.isActive("orderedList")}
onClick={() => editor?.chain().focus().toggleOrderedList().run()}
>
<ListOrdered className="h-4 w-4" />
</ToolbarButton>
<div className="mx-1 h-6 w-px bg-grayScale-200" />
<ToolbarButton
label="Undo"
disabled={disabled || !editor || !editor.can().undo()}
onClick={() => editor?.chain().focus().undo().run()}
>
<Undo2 className="h-4 w-4" />
</ToolbarButton>
<ToolbarButton
label="Redo"
disabled={disabled || !editor || !editor.can().redo()}
onClick={() => editor?.chain().focus().redo().run()}
>
<Redo2 className="h-4 w-4" />
</ToolbarButton>
{maxLength != null ? (
<span
className={cn(
"ml-auto pr-2 text-xs font-medium",
atLimit ? "text-amber-700" : "text-grayScale-400",
)}
>
{plainLength} / {maxLength}
</span>
) : null}
</div>
<EditorContent editor={editor} />
</div>
)
}

View File

@ -186,8 +186,8 @@
top: 1.25rem; top: 1.25rem;
} }
.yimaru-toast[data-sonner-toast] { .rezina-toast[data-sonner-toast] {
--yimaru-toast-accent: #9e2891; --rezina-toast-accent: #9e2891;
width: var(--width); width: var(--width);
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
@ -195,7 +195,7 @@
padding: 0.875rem 1rem 0.875rem 1rem; padding: 0.875rem 1rem 0.875rem 1rem;
border-radius: 0.75rem; border-radius: 0.75rem;
border: 1px solid var(--gs-200); border: 1px solid var(--gs-200);
border-left: 3px solid var(--yimaru-toast-accent); border-left: 3px solid var(--rezina-toast-accent);
background: var(--gs-50); background: var(--gs-50);
color: hsl(var(--foreground)); color: hsl(var(--foreground));
box-shadow: box-shadow:
@ -206,46 +206,46 @@
letter-spacing: -0.01em; letter-spacing: -0.01em;
} }
html.dark .yimaru-toast[data-sonner-toast] { html.dark .rezina-toast[data-sonner-toast] {
box-shadow: box-shadow:
0 1px 2px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.25),
0 16px 40px rgba(0, 0, 0, 0.45); 0 16px 40px rgba(0, 0, 0, 0.45);
} }
.yimaru-toast[data-sonner-toast] [data-icon] { .rezina-toast[data-sonner-toast] [data-icon] {
margin-top: 0.1rem; margin-top: 0.1rem;
width: 1.125rem; width: 1.125rem;
height: 1.125rem; height: 1.125rem;
flex-shrink: 0; flex-shrink: 0;
color: var(--yimaru-toast-accent); color: var(--rezina-toast-accent);
} }
.yimaru-toast[data-sonner-toast] [data-icon] svg { .rezina-toast[data-sonner-toast] [data-icon] svg {
width: 1.125rem; width: 1.125rem;
height: 1.125rem; height: 1.125rem;
} }
.yimaru-toast[data-sonner-toast] [data-content] { .rezina-toast[data-sonner-toast] [data-content] {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
gap: 0.2rem; gap: 0.2rem;
} }
.yimaru-toast__title { .rezina-toast__title {
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 600; font-weight: 600;
color: hsl(var(--foreground)); color: hsl(var(--foreground));
letter-spacing: -0.015em; letter-spacing: -0.015em;
} }
.yimaru-toast__description { .rezina-toast__description {
font-size: 0.8125rem; font-size: 0.8125rem;
font-weight: 400; font-weight: 400;
color: var(--gs-500); color: var(--gs-500);
line-height: 1.45; line-height: 1.45;
} }
.yimaru-toast__close { .rezina-toast__close {
position: absolute !important; position: absolute !important;
top: 0.55rem !important; top: 0.55rem !important;
right: 0.55rem !important; right: 0.55rem !important;
@ -264,14 +264,14 @@
border-color 0.15s ease; border-color 0.15s ease;
} }
.yimaru-toast__close:hover { .rezina-toast__close:hover {
background: var(--gs-100) !important; background: var(--gs-100) !important;
border-color: var(--gs-200) !important; border-color: var(--gs-200) !important;
color: var(--gs-600) !important; color: var(--gs-600) !important;
opacity: 1; opacity: 1;
} }
.yimaru-toast__action { .rezina-toast__action {
margin-top: 0.35rem; margin-top: 0.35rem;
height: 1.75rem; height: 1.75rem;
padding: 0 0.75rem; padding: 0 0.75rem;
@ -282,7 +282,7 @@
font-weight: 600; font-weight: 600;
} }
.yimaru-toast__cancel { .rezina-toast__cancel {
margin-top: 0.35rem; margin-top: 0.35rem;
height: 1.75rem; height: 1.75rem;
padding: 0 0.75rem; padding: 0 0.75rem;
@ -293,23 +293,23 @@
font-weight: 500; font-weight: 500;
} }
.yimaru-toast--success { .rezina-toast--success {
--yimaru-toast-accent: #059669; --rezina-toast-accent: #059669;
} }
.yimaru-toast--error { .rezina-toast--error {
--yimaru-toast-accent: #dc2626; --rezina-toast-accent: #dc2626;
} }
.yimaru-toast--warning { .rezina-toast--warning {
--yimaru-toast-accent: #d97706; --rezina-toast-accent: #d97706;
} }
.yimaru-toast--info { .rezina-toast--info {
--yimaru-toast-accent: #9e2891; --rezina-toast-accent: #9e2891;
} }
.yimaru-toast[data-sonner-toast][data-styled="true"] { .rezina-toast[data-sonner-toast][data-styled="true"] {
padding-right: 2.25rem; padding-right: 2.25rem;
} }
@ -318,7 +318,7 @@
right: 1.25rem; right: 1.25rem;
} }
[data-sonner-toast].yimaru-realtime-popup-host { [data-sonner-toast].rezina-realtime-popup-host {
padding: 0; padding: 0;
margin: 0; margin: 0;
border: none; border: none;
@ -332,12 +332,12 @@
height 400ms ease; height 400ms ease;
} }
[data-sonner-toast].yimaru-realtime-popup-host[data-mounted="true"] { [data-sonner-toast].rezina-realtime-popup-host[data-mounted="true"] {
--y: translate(0, 0); --y: translate(0, 0);
opacity: 1; opacity: 1;
} }
[data-sonner-toast].yimaru-realtime-popup-host[data-removed="true"][data-front="true"][data-swipe-out="false"] { [data-sonner-toast].rezina-realtime-popup-host[data-removed="true"][data-front="true"][data-swipe-out="false"] {
--y: translate(115%, 115%); --y: translate(115%, 115%);
opacity: 0; opacity: 0;
transition: transition:
@ -345,18 +345,18 @@
opacity 280ms ease; opacity 280ms ease;
} }
[data-sonner-toast].yimaru-realtime-popup-host[data-removed="true"][data-front="false"][data-swipe-out="false"] { [data-sonner-toast].rezina-realtime-popup-host[data-removed="true"][data-front="false"][data-swipe-out="false"] {
--y: translate(60%, 60%); --y: translate(60%, 60%);
opacity: 0; opacity: 0;
} }
.yimaru-realtime-popup { .rezina-realtime-popup {
--yimaru-popup-accent: #9e2891; --rezina-popup-accent: #9e2891;
width: min(380px, calc(100vw - 2rem)); width: min(380px, calc(100vw - 2rem));
overflow: hidden; overflow: hidden;
border-radius: 0.75rem; border-radius: 0.75rem;
border: 1px solid var(--gs-200); border: 1px solid var(--gs-200);
border-left: 3px solid var(--yimaru-popup-accent); border-left: 3px solid var(--rezina-popup-accent);
background: #fff; background: #fff;
color: hsl(var(--foreground)); color: hsl(var(--foreground));
box-shadow: box-shadow:
@ -364,30 +364,30 @@
0 12px 32px rgba(15, 23, 42, 0.12); 0 12px 32px rgba(15, 23, 42, 0.12);
} }
html.dark .yimaru-realtime-popup { html.dark .rezina-realtime-popup {
background: hsl(var(--card)); background: hsl(var(--card));
box-shadow: box-shadow:
0 1px 2px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.25),
0 16px 40px rgba(0, 0, 0, 0.45); 0 16px 40px rgba(0, 0, 0, 0.45);
} }
.yimaru-realtime-popup--success { .rezina-realtime-popup--success {
--yimaru-popup-accent: #059669; --rezina-popup-accent: #059669;
} }
.yimaru-realtime-popup--error { .rezina-realtime-popup--error {
--yimaru-popup-accent: #dc2626; --rezina-popup-accent: #dc2626;
} }
.yimaru-realtime-popup--warning { .rezina-realtime-popup--warning {
--yimaru-popup-accent: #d97706; --rezina-popup-accent: #d97706;
} }
.yimaru-realtime-popup--info { .rezina-realtime-popup--info {
--yimaru-popup-accent: #9e2891; --rezina-popup-accent: #9e2891;
} }
.yimaru-realtime-popup__header { .rezina-realtime-popup__header {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@ -397,27 +397,27 @@
background: var(--gs-50); background: var(--gs-50);
} }
html.dark .yimaru-realtime-popup__header { html.dark .rezina-realtime-popup__header {
background: hsl(var(--muted) / 0.35); background: hsl(var(--muted) / 0.35);
border-bottom-color: hsl(var(--border)); border-bottom-color: hsl(var(--border));
} }
.yimaru-realtime-popup__meta { .rezina-realtime-popup__meta {
display: flex; display: flex;
min-width: 0; min-width: 0;
align-items: center; align-items: center;
gap: 0.375rem; gap: 0.375rem;
} }
.yimaru-realtime-popup__type { .rezina-realtime-popup__type {
font-size: 0.6875rem; font-size: 0.6875rem;
font-weight: 600; font-weight: 600;
letter-spacing: 0.04em; letter-spacing: 0.04em;
text-transform: uppercase; text-transform: uppercase;
color: var(--yimaru-popup-accent); color: var(--rezina-popup-accent);
} }
.yimaru-realtime-popup__dot { .rezina-realtime-popup__dot {
width: 0.2rem; width: 0.2rem;
height: 0.2rem; height: 0.2rem;
flex-shrink: 0; flex-shrink: 0;
@ -425,14 +425,14 @@
background: var(--gs-300); background: var(--gs-300);
} }
.yimaru-realtime-popup__time { .rezina-realtime-popup__time {
font-size: 0.6875rem; font-size: 0.6875rem;
font-weight: 500; font-weight: 500;
color: var(--gs-500); color: var(--gs-500);
white-space: nowrap; white-space: nowrap;
} }
.yimaru-realtime-popup__close { .rezina-realtime-popup__close {
display: grid; display: grid;
place-items: center; place-items: center;
width: 1.5rem; width: 1.5rem;
@ -448,24 +448,24 @@
border-color 0.15s ease; border-color 0.15s ease;
} }
.yimaru-realtime-popup__close:hover { .rezina-realtime-popup__close:hover {
background: #fff; background: #fff;
border-color: var(--gs-200); border-color: var(--gs-200);
color: var(--gs-600); color: var(--gs-600);
} }
html.dark .yimaru-realtime-popup__close:hover { html.dark .rezina-realtime-popup__close:hover {
background: hsl(var(--background)); background: hsl(var(--background));
} }
.yimaru-realtime-popup__body { .rezina-realtime-popup__body {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
gap: 0.75rem; gap: 0.75rem;
padding: 0.875rem 0.875rem 1rem; padding: 0.875rem 0.875rem 1rem;
} }
.yimaru-realtime-popup__icon { .rezina-realtime-popup__icon {
display: grid; display: grid;
place-items: center; place-items: center;
width: 2.5rem; width: 2.5rem;
@ -474,12 +474,12 @@
border-radius: 0.625rem; border-radius: 0.625rem;
} }
.yimaru-realtime-popup__content { .rezina-realtime-popup__content {
min-width: 0; min-width: 0;
flex: 1; flex: 1;
} }
.yimaru-realtime-popup__title { .rezina-realtime-popup__title {
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 600; font-weight: 600;
line-height: 1.35; line-height: 1.35;
@ -487,7 +487,7 @@
color: hsl(var(--foreground)); color: hsl(var(--foreground));
} }
.yimaru-realtime-popup__message { .rezina-realtime-popup__message {
margin-top: 0.25rem; margin-top: 0.25rem;
display: -webkit-box; display: -webkit-box;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
@ -498,7 +498,7 @@
color: var(--gs-600); color: var(--gs-600);
} }
.yimaru-realtime-popup__action { .rezina-realtime-popup__action {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 0.25rem; gap: 0.25rem;
@ -508,11 +508,19 @@
background: transparent; background: transparent;
font-size: 0.75rem; font-size: 0.75rem;
font-weight: 600; font-weight: 600;
color: var(--yimaru-popup-accent); color: var(--rezina-popup-accent);
transition: opacity 0.15s ease; transition: opacity 0.15s ease;
} }
.yimaru-realtime-popup__action:hover { .rezina-realtime-popup__action:hover {
opacity: 0.8; opacity: 0.8;
} }
} }
.tiptap p.is-editor-empty:first-child::before {
color: rgb(148 163 184);
content: attr(data-placeholder);
float: left;
height: 0;
pointer-events: none;
}

View File

@ -118,7 +118,7 @@ export function AppLayout() {
rel="noopener noreferrer" rel="noopener noreferrer"
className="font-semibold text-brand-500 transition-colors hover:text-brand-600" className="font-semibold text-brand-500 transition-colors hover:text-brand-600"
> >
Yimaru Academy Rezina Academy
</a> </a>
<span aria-hidden>·</span> <span aria-hidden>·</span>
<span>© {new Date().getFullYear()}</span> <span>© {new Date().getFullYear()}</span>

View File

@ -1,4 +1,4 @@
/** Default business timezone for Yimaru (East Africa Time, UTC+3, no DST). */ /** Default business timezone for Rezina (East Africa Time, UTC+3, no DST). */
export const APP_TIMEZONE = "Africa/Addis_Ababa" export const APP_TIMEZONE = "Africa/Addis_Ababa"
export const APP_TIMEZONE_LABEL = "EAT" export const APP_TIMEZONE_LABEL = "EAT"
/** Fixed offset used when building RFC3339 bounds from calendar days. */ /** Fixed offset used when building RFC3339 bounds from calendar days. */

View File

@ -1,6 +1,6 @@
const STORAGE_KEY = "yimaru:notification-popup-enabled" const STORAGE_KEY = "rezina:notification-popup-enabled"
export const NOTIFICATION_POPUP_PREFERENCE_EVENT = "yimaru:notification-popup-preference" export const NOTIFICATION_POPUP_PREFERENCE_EVENT = "rezina:notification-popup-preference"
export function getNotificationPopupEnabled(): boolean { export function getNotificationPopupEnabled(): boolean {
try { try {

View File

@ -4,7 +4,7 @@ import { getAccessToken, TEAM_SESSION_UPDATED_EVENT } from "./teamAuthStorage"
const RECONNECT_MS = 5000 const RECONNECT_MS = 5000
export const NOTIFICATION_REALTIME_EVENT = "yimaru:notification-realtime" export const NOTIFICATION_REALTIME_EVENT = "rezina:notification-realtime"
function getWsUrl() { function getWsUrl() {
const base = import.meta.env.VITE_API_BASE_URL as string const base = import.meta.env.VITE_API_BASE_URL as string

View File

@ -2,23 +2,15 @@ import {
deleteExamPrepPractice, deleteExamPrepPractice,
deleteParentLinkedPractice, deleteParentLinkedPractice,
} from "../api/courses.api" } from "../api/courses.api"
import type { ParentContextPractice, PracticeParent } from "../types/course.types" import type { ParentContextPractice } from "../types/course.types"
import { parentsFromPractice } from "./practiceParents"
import { import {
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listCourseContextUnlinkParents, listPracticeUnlinkParentsForScope,
listModuleContextUnlinkParents, type PracticeUnlinkScope,
resolveCourseContextUnlinkParent,
resolveModuleContextUnlinkParent,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "./practiceParentUnlink" } from "./practiceParentUnlink"
export type PracticeUnlinkContext = export type PracticeUnlinkContext = PracticeUnlinkScope
| { scope: "course"; courseId: number; moduleIds: number[]; lessonIds?: number[] }
| { scope: "module"; moduleId: number; lessonIds: number[] }
| { scope: "lesson"; lessonId: number }
| { scope: "unit"; unitId: number }
| { scope: "catalog_course"; catalogCourseId: number }
export type BulkPracticeActionResult = { export type BulkPracticeActionResult = {
succeeded: number succeeded: number
@ -26,76 +18,11 @@ export type BulkPracticeActionResult = {
failed: number failed: number
} }
export function resolvePracticeUnlinkParent(
practice: ParentContextPractice,
context: PracticeUnlinkContext,
): PracticeParent | null {
switch (context.scope) {
case "course":
return resolveCourseContextUnlinkParent(
practice,
context.courseId,
context.moduleIds,
context.lessonIds ?? [],
)
case "module":
return resolveModuleContextUnlinkParent(
practice,
context.moduleId,
context.lessonIds,
)
case "lesson":
return (
parentsFromPractice(practice).find(
(p) =>
p.parent_kind === "LESSON" && p.parent_id === context.lessonId,
) ?? null
)
case "unit":
return (
parentsFromPractice(practice).find(
(p) => p.parent_kind === "UNIT" && p.parent_id === context.unitId,
) ?? null
)
case "catalog_course":
return (
parentsFromPractice(practice).find(
(p) =>
p.parent_kind === "CATALOG_COURSE" &&
p.parent_id === context.catalogCourseId,
) ?? null
)
}
}
export function listPracticeUnlinkParents( export function listPracticeUnlinkParents(
practice: ParentContextPractice, practice: ParentContextPractice,
context: PracticeUnlinkContext, context: PracticeUnlinkContext,
): PracticeParent[] { ) {
switch (context.scope) { return listPracticeUnlinkParentsForScope(practice, context)
case "course":
return listCourseContextUnlinkParents(
practice,
context.courseId,
context.moduleIds,
context.lessonIds ?? [],
)
case "module":
return listModuleContextUnlinkParents(
practice,
context.moduleId,
context.lessonIds,
)
case "lesson": {
const parent = resolvePracticeUnlinkParent(practice, context)
return parent ? [parent] : []
}
case "unit":
case "catalog_course": {
const parent = resolvePracticeUnlinkParent(practice, context)
return parent ? [parent] : []
}
}
} }
export async function bulkUnlinkPractices(opts: { export async function bulkUnlinkPractices(opts: {
@ -188,7 +115,7 @@ export function formatBulkPracticeActionToast(
kind: "info", kind: "info",
message: message:
action === "unlink" action === "unlink"
? "Selected practices were already removed from this location." ? "Selected practices are not directly linked to this location (they may appear via a child module or lesson)."
: "No practices were deleted.", : "No practices were deleted.",
} }
} }
@ -206,7 +133,7 @@ export function formatBulkPracticeActionToast(
if (action === "unlink") { if (action === "unlink") {
let message = `Removed ${succeeded} practice${succeeded === 1 ? "" : "s"} from ${locationLabel}.` let message = `Removed ${succeeded} practice${succeeded === 1 ? "" : "s"} from ${locationLabel}.`
if (skipped > 0) { if (skipped > 0) {
message += ` ${skipped} ${skipped === 1 ? "was" : "were"} already removed or could not be matched.` message += ` ${skipped} ${skipped === 1 ? "was" : "were"} not directly linked here.`
} }
if (failed > 0) { if (failed > 0) {
message += ` ${failed} failed.` message += ` ${failed} failed.`

View File

@ -27,8 +27,6 @@ export interface PracticeEditInput {
preservedQuestionSet: PreservedQuestionSetFields preservedQuestionSet: PreservedQuestionSetFields
questions: PracticeEditQuestionInput[] questions: PracticeEditQuestionInput[]
definitions: QuestionTypeDefinition[] definitions: QuestionTypeDefinition[]
isLearnEnglishLessonPractice: boolean
lessonDefaultTitle?: string
parents?: PracticeParent[] parents?: PracticeParent[]
parentsChanged?: boolean parentsChanged?: boolean
} }
@ -43,8 +41,6 @@ export async function executePracticeUpdate(
preservedQuestionSet: opts.preservedQuestionSet, preservedQuestionSet: opts.preservedQuestionSet,
questions: opts.questions, questions: opts.questions,
definitions: opts.definitions, definitions: opts.definitions,
isLearnEnglishLessonPractice: opts.isLearnEnglishLessonPractice,
lessonDefaultTitle: opts.lessonDefaultTitle,
}) })
if (opts.isExamPrep) { if (opts.isExamPrep) {
@ -75,8 +71,6 @@ export interface SyncStimulusBlocksAfterCreateInput {
preservedQuestionSet: PreservedQuestionSetFields preservedQuestionSet: PreservedQuestionSetFields
questions: PracticeEditQuestionInput[] questions: PracticeEditQuestionInput[]
definitions: QuestionTypeDefinition[] definitions: QuestionTypeDefinition[]
isLearnEnglishLessonPractice: boolean
lessonDefaultTitle?: string
} }
/** After multi-step create, apply authoring profile + stimulus blocks via full PUT. */ /** After multi-step create, apply authoring profile + stimulus blocks via full PUT. */
@ -109,8 +103,6 @@ export async function syncStimulusBlocksAfterCreate(
preservedQuestionSet: opts.preservedQuestionSet, preservedQuestionSet: opts.preservedQuestionSet,
questions: questionsWithIds, questions: questionsWithIds,
definitions: opts.definitions, definitions: opts.definitions,
isLearnEnglishLessonPractice: opts.isLearnEnglishLessonPractice,
lessonDefaultTitle: opts.lessonDefaultTitle,
}) })
if (opts.isExamPrep) { if (opts.isExamPrep) {

View File

@ -740,8 +740,6 @@ export interface BuildPracticeFullUpdateInput {
preservedQuestionSet: PreservedQuestionSetFields preservedQuestionSet: PreservedQuestionSetFields
questions: PracticeEditQuestionInput[] questions: PracticeEditQuestionInput[]
definitions: QuestionTypeDefinition[] definitions: QuestionTypeDefinition[]
isLearnEnglishLessonPractice: boolean
lessonDefaultTitle?: string
} }
export function buildPracticeFullUpdateRequest( export function buildPracticeFullUpdateRequest(
@ -764,16 +762,9 @@ export function buildPracticeFullUpdateRequest(
if (err) throw new Error(err) if (err) throw new Error(err)
} }
const lessonTitle = opts.lessonDefaultTitle?.trim() || "Lesson practice" const practiceTitle = opts.formData.title.trim() || "Untitled practice"
const practiceTitle = opts.isLearnEnglishLessonPractice const storyDescription = opts.formData.description.trim()
? lessonTitle const storyImage = opts.formData.storyImageUrl.trim()
: opts.formData.title.trim() || "Untitled practice"
const storyDescription = opts.isLearnEnglishLessonPractice
? ""
: opts.formData.description.trim()
const storyImage = opts.isLearnEnglishLessonPractice
? ""
: opts.formData.storyImageUrl.trim()
const byId = new Map(opts.definitions.map((d) => [d.id, d])) const byId = new Map(opts.definitions.map((d) => [d.id, d]))
const toUpdate = opts.questions const toUpdate = opts.questions
@ -868,12 +859,8 @@ export function buildPracticeFullUpdateRequest(
authoring_profile: opts.formData.authoringProfile, authoring_profile: opts.formData.authoringProfile,
}, },
question_set: { question_set: {
title: opts.isLearnEnglishLessonPractice title: opts.formData.title.trim() || "Practice set",
? lessonTitle description: opts.formData.description.trim() || null,
: opts.formData.title.trim() || "Practice set",
description: opts.isLearnEnglishLessonPractice
? null
: opts.formData.description.trim() || null,
time_limit_minutes: opts.preservedQuestionSet.timeLimitMinutes, time_limit_minutes: opts.preservedQuestionSet.timeLimitMinutes,
passing_score: opts.preservedQuestionSet.passingScore, passing_score: opts.preservedQuestionSet.passingScore,
shuffle_questions: opts.formData.shuffleQuestions, shuffle_questions: opts.formData.shuffleQuestions,

View File

@ -45,91 +45,210 @@ export function isPracticeParentUnlinkNotLinkedError(err: unknown): boolean {
return msg.includes("not linked") return msg.includes("not linked")
} }
/** Parent row to DELETE when removing a practice from a module's practice tab. */ function directParentsMatching(
export function resolveModuleContextUnlinkParent(
practice: ParentContextPractice, practice: ParentContextPractice,
moduleId: number, kind: PracticeParent["parent_kind"],
lessonIdsInModule: number[], parentId: number,
): PracticeParent | null {
return (
listModuleContextUnlinkParents(practice, moduleId, lessonIdsInModule)[0] ??
null
)
}
/** All parent rows to remove when detaching a practice from a module practice tab. */
export function listModuleContextUnlinkParents(
practice: ParentContextPractice,
moduleId: number,
lessonIdsInModule: number[],
): PracticeParent[] { ): PracticeParent[] {
const parents = parentsFromPractice(practice) return dedupeParents(
const lessonIds = new Set(lessonIdsInModule.filter((id) => id > 0)) parentsFromPractice(practice).filter(
const targets: PracticeParent[] = [] (parent) => parent.parent_kind === kind && parent.parent_id === parentId,
),
for (const parent of parents) {
if (parent.parent_kind === "COURSE") continue
if (parent.parent_kind === "MODULE" && parent.parent_id === moduleId) {
targets.push(parent)
} else if (
parent.parent_kind === "LESSON" &&
lessonIds.has(parent.parent_id)
) {
targets.push(parent)
}
}
return dedupeParents(targets)
}
/** Parent row to DELETE when removing a practice from a course's practice tab. */
export function resolveCourseContextUnlinkParent(
practice: ParentContextPractice,
courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[] = [],
): PracticeParent | null {
return (
listCourseContextUnlinkParents(
practice,
courseId,
moduleIdsInCourse,
lessonIdsInCourse,
)[0] ?? null
) )
} }
/** All parent rows to remove when detaching a practice from a course practice tab. */ /** Learn English — course practice tab (direct COURSE link only). */
export function listCourseContextUnlinkParents( export function listCourseContextUnlinkParents(
practice: ParentContextPractice, practice: ParentContextPractice,
courseId: number, courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[] = [],
): PracticeParent[] { ): PracticeParent[] {
const parents = parentsFromPractice(practice) return directParentsMatching(practice, "COURSE", courseId)
}
export function resolveCourseContextUnlinkParent(
practice: ParentContextPractice,
courseId: number,
): PracticeParent | null {
return listCourseContextUnlinkParents(practice, courseId)[0] ?? null
}
export function hasCourseDirectPracticeLink(
practice: ParentContextPractice,
courseId: number,
): boolean {
return listCourseContextUnlinkParents(practice, courseId).length > 0
}
/** Learn English — module practice tab (direct MODULE link only). */
export function listModuleContextUnlinkParents(
practice: ParentContextPractice,
moduleId: number,
): PracticeParent[] {
return directParentsMatching(practice, "MODULE", moduleId)
}
export function resolveModuleContextUnlinkParent(
practice: ParentContextPractice,
moduleId: number,
): PracticeParent | null {
return listModuleContextUnlinkParents(practice, moduleId)[0] ?? null
}
export function hasModuleDirectPracticeLink(
practice: ParentContextPractice,
moduleId: number,
): boolean {
return listModuleContextUnlinkParents(practice, moduleId).length > 0
}
/** Learn English / Exam Prep — lesson practice tab (direct LESSON link only). */
export function listLessonContextUnlinkParents(
practice: ParentContextPractice,
lessonId: number,
): PracticeParent[] {
return directParentsMatching(practice, "LESSON", lessonId)
}
export function hasLessonDirectPracticeLink(
practice: ParentContextPractice,
lessonId: number,
): boolean {
return listLessonContextUnlinkParents(practice, lessonId).length > 0
}
/** Exam Prep — unit practice tab (direct UNIT link only). */
export function listUnitContextUnlinkParents(
practice: ParentContextPractice,
unitId: number,
): PracticeParent[] {
return directParentsMatching(practice, "UNIT", unitId)
}
export function hasUnitDirectPracticeLink(
practice: ParentContextPractice,
unitId: number,
): boolean {
return listUnitContextUnlinkParents(practice, unitId).length > 0
}
/** Exam Prep — catalog course practice tab (direct CATALOG_COURSE link only). */
export function listCatalogCourseContextUnlinkParents(
practice: ParentContextPractice,
catalogCourseId: number,
): PracticeParent[] {
return directParentsMatching(practice, "CATALOG_COURSE", catalogCourseId)
}
export function hasCatalogCourseDirectPracticeLink(
practice: ParentContextPractice,
catalogCourseId: number,
): boolean {
return listCatalogCourseContextUnlinkParents(practice, catalogCourseId).length > 0
}
export function isPracticeLinkedViaDescendantInCourse(
practice: ParentContextPractice,
courseId: number,
moduleIdsInCourse: number[],
lessonIdsInCourse: number[],
): boolean {
if (hasCourseDirectPracticeLink(practice, courseId)) return false
const moduleIds = new Set(moduleIdsInCourse.filter((id) => id > 0)) const moduleIds = new Set(moduleIdsInCourse.filter((id) => id > 0))
const lessonIds = new Set(lessonIdsInCourse.filter((id) => id > 0)) const lessonIds = new Set(lessonIdsInCourse.filter((id) => id > 0))
const targets: PracticeParent[] = [] return parentsFromPractice(practice).some(
(parent) =>
(parent.parent_kind === "MODULE" && moduleIds.has(parent.parent_id)) ||
(parent.parent_kind === "LESSON" && lessonIds.has(parent.parent_id)),
)
}
for (const parent of parents) { export function isPracticeLinkedViaLessonInModule(
if (parent.parent_kind === "COURSE" && parent.parent_id === courseId) { practice: ParentContextPractice,
targets.push(parent) moduleId: number,
} else if ( lessonIdsInModule: number[],
parent.parent_kind === "MODULE" && ): boolean {
moduleIds.has(parent.parent_id) if (hasModuleDirectPracticeLink(practice, moduleId)) return false
) { const lessonIds = new Set(lessonIdsInModule.filter((id) => id > 0))
targets.push(parent) return parentsFromPractice(practice).some(
} else if ( (parent) =>
parent.parent_kind === "LESSON" && parent.parent_kind === "LESSON" && lessonIds.has(parent.parent_id),
(lessonIds.size === 0 || lessonIds.has(parent.parent_id)) )
) { }
if (lessonIds.size > 0) {
targets.push(parent) export type PracticeUnlinkScope =
} | { scope: "course"; courseId: number; moduleIds?: number[]; lessonIds?: number[] }
} | { scope: "module"; moduleId: number; lessonIds?: number[] }
| { scope: "lesson"; lessonId: number }
| { scope: "unit"; unitId: number }
| { scope: "catalog_course"; catalogCourseId: number }
export function listPracticeUnlinkParentsForScope(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): PracticeParent[] {
switch (context.scope) {
case "course":
return listCourseContextUnlinkParents(practice, context.courseId)
case "module":
return listModuleContextUnlinkParents(practice, context.moduleId)
case "lesson":
return listLessonContextUnlinkParents(practice, context.lessonId)
case "unit":
return listUnitContextUnlinkParents(practice, context.unitId)
case "catalog_course":
return listCatalogCourseContextUnlinkParents(
practice,
context.catalogCourseId,
)
} }
}
return dedupeParents(targets) export function hasDirectPracticeLinkForScope(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): boolean {
return listPracticeUnlinkParentsForScope(practice, context).length > 0
}
export function practiceUnlinkBlockedMessage(
practice: ParentContextPractice,
context: PracticeUnlinkScope,
): string | null {
if (hasDirectPracticeLinkForScope(practice, context)) return null
switch (context.scope) {
case "course": {
if (
isPracticeLinkedViaDescendantInCourse(
practice,
context.courseId,
context.moduleIds ?? [],
context.lessonIds ?? [],
)
) {
return "This practice is linked to a module or lesson, not this course. Open that location to unlink it."
}
return "This practice is not linked to this course."
}
case "module": {
if (
isPracticeLinkedViaLessonInModule(
practice,
context.moduleId,
context.lessonIds ?? [],
)
) {
return "This practice is linked to a lesson, not this module. Open the lesson to unlink it."
}
return "This practice is not linked to this module."
}
case "lesson":
return "This practice is not linked to this lesson."
case "unit":
return "This practice is not linked to this unit."
case "catalog_course":
return "This practice is not linked to this catalog course."
}
} }
export async function unlinkPracticeFromParent(opts: { export async function unlinkPracticeFromParent(opts: {

18
src/lib/richText.ts Normal file
View File

@ -0,0 +1,18 @@
export function stripHtml(html: string): string {
if (!html.trim()) return ""
const doc = new DOMParser().parseFromString(html, "text/html")
return (doc.body.textContent ?? "").replace(/\u00a0/g, " ").trim()
}
export function hasRichTextContent(html: string | undefined | null): boolean {
return stripHtml(html ?? "").length > 0
}
export function richTextPlainLength(html: string | undefined | null): number {
return stripHtml(html ?? "").length
}
export function looksLikeHtml(value: string | undefined | null): boolean {
const trimmed = value?.trim() ?? ""
return /<[^>]+>/.test(trimmed)
}

View File

@ -20,6 +20,64 @@ export const LIFETIME_DURATION_DEFAULT = {
duration_unit: "YEAR" as SubscriptionPlanDurationUnit, duration_unit: "YEAR" as SubscriptionPlanDurationUnit,
} }
export const DUPLICATE_SUBSCRIPTION_PLAN_PERIOD_MESSAGE =
"Only one plan is allowed per category and billing period. A free plan and a paid plan cannot share the same period—edit the existing plan or change category or duration."
export type SubscriptionPlanPeriodCandidate = {
category: string
is_lifetime: boolean
duration_value: number
duration_unit: SubscriptionPlanDurationUnit
}
function normalizedPeriod(
candidate: SubscriptionPlanPeriodCandidate,
): SubscriptionPlanPeriodCandidate {
if (candidate.is_lifetime) {
return {
category: candidate.category,
is_lifetime: true,
duration_value: LIFETIME_DURATION_DEFAULT.duration_value,
duration_unit: LIFETIME_DURATION_DEFAULT.duration_unit,
}
}
return {
...candidate,
duration_unit: String(candidate.duration_unit).toUpperCase() as SubscriptionPlanDurationUnit,
}
}
export function sameSubscriptionPlanPeriod(
a: SubscriptionPlanPeriodCandidate,
b: SubscriptionPlanPeriodCandidate,
): boolean {
const left = normalizedPeriod(a)
const right = normalizedPeriod(b)
return (
left.category === right.category &&
left.is_lifetime === right.is_lifetime &&
left.duration_value === right.duration_value &&
left.duration_unit === right.duration_unit
)
}
export function findConflictingSubscriptionPlan(
plans: SubscriptionPlan[],
candidate: SubscriptionPlanPeriodCandidate,
excludePlanId?: number,
): SubscriptionPlan | undefined {
return plans.find(
(plan) =>
plan.id !== excludePlanId &&
sameSubscriptionPlanPeriod(candidate, {
category: plan.category,
is_lifetime: plan.is_lifetime,
duration_value: plan.duration_value,
duration_unit: plan.duration_unit,
}),
)
}
/** True when a plan is configured as one-time (never expires). */ /** True when a plan is configured as one-time (never expires). */
export function isLifetimePlan( export function isLifetimePlan(
plan: Pick<SubscriptionPlan, "is_lifetime"> | { is_lifetime?: boolean | null } | null | undefined, plan: Pick<SubscriptionPlan, "is_lifetime"> | { is_lifetime?: boolean | null } | null | undefined,
@ -64,7 +122,10 @@ export function formatPlanDuration(
return `${v} ${word}` return `${v} ${word}`
} }
export function formatPlanPrice(plan: Pick<SubscriptionPlan, "price" | "currency">): string { export function formatPlanPrice(
plan: Pick<SubscriptionPlan, "price" | "currency" | "is_free">,
): string {
if (plan.is_free) return "Free"
const amount = Number(plan.price) const amount = Number(plan.price)
const formatted = Number.isFinite(amount) const formatted = Number.isFinite(amount)
? amount.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 }) ? amount.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })
@ -94,6 +155,7 @@ export function planToUpdatePayload(
price: plan.price, price: plan.price,
currency: plan.currency, currency: plan.currency,
is_lifetime: plan.is_lifetime, is_lifetime: plan.is_lifetime,
is_free: plan.is_free,
is_active: plan.is_active, is_active: plan.is_active,
...overrides, ...overrides,
} }

View File

@ -7,7 +7,7 @@ const KEYS = {
memberId: "member_id", memberId: "member_id",
} as const } as const
export const TEAM_SESSION_UPDATED_EVENT = "yimaru:team-session-updated" export const TEAM_SESSION_UPDATED_EVENT = "rezina:team-session-updated"
function dispatchSessionUpdated() { function dispatchSessionUpdated() {
window.dispatchEvent(new Event(TEAM_SESSION_UPDATED_EVENT)) window.dispatchEvent(new Event(TEAM_SESSION_UPDATED_EVENT))

View File

@ -1,7 +1,7 @@
export type ThemeMode = "light" | "dark" | "system" export type ThemeMode = "light" | "dark" | "system"
export type ResolvedTheme = "light" | "dark" export type ResolvedTheme = "light" | "dark"
export const THEME_STORAGE_KEY = "yimaru-admin-theme" export const THEME_STORAGE_KEY = "rezina-admin-theme"
const MEDIA_QUERY = "(prefers-color-scheme: dark)" const MEDIA_QUERY = "(prefers-color-scheme: dark)"

View File

@ -4,12 +4,12 @@ export function AboutPage() {
return ( return (
<InfoLayout <InfoLayout
title="About" title="About"
subtitle="Yimaru Academy provides modern, structured learning experiences and the administration tools to manage courses, question sets, speaking practices, and learner progress at scale." subtitle="Rezina Academy provides modern, structured learning experiences and the administration tools to manage courses, question sets, speaking practices, and learner progress at scale."
> >
<section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm"> <section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm">
<h2 className="text-lg font-semibold text-grayScale-700">What is Yimaru Academy?</h2> <h2 className="text-lg font-semibold text-grayScale-700">What is Rezina Academy?</h2>
<p className="text-sm leading-relaxed text-grayScale-600"> <p className="text-sm leading-relaxed text-grayScale-600">
Yimaru Academy is a digital learning platform focused on high-quality content delivery, Rezina Academy is a digital learning platform focused on high-quality content delivery,
measurable learner outcomes, and efficient administration for training teams. measurable learner outcomes, and efficient administration for training teams.
</p> </p>
</section> </section>

View File

@ -4,7 +4,7 @@ export function AccountDeletionPage() {
return ( return (
<InfoLayout <InfoLayout
title="Account Deletion" title="Account Deletion"
subtitle="Guidance on requesting and processing account deletion within Yimaru Academy." subtitle="Guidance on requesting and processing account deletion within Rezina Academy."
> >
<section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm"> <section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm">
<h2 className="text-lg font-semibold text-grayScale-700">Before Deletion</h2> <h2 className="text-lg font-semibold text-grayScale-700">Before Deletion</h2>
@ -18,7 +18,7 @@ export function AccountDeletionPage() {
<h2 className="text-lg font-semibold text-grayScale-700">Deletion Steps</h2> <h2 className="text-lg font-semibold text-grayScale-700">Deletion Steps</h2>
<ol className="list-decimal space-y-2 pl-5 text-sm leading-relaxed text-grayScale-600"> <ol className="list-decimal space-y-2 pl-5 text-sm leading-relaxed text-grayScale-600">
<li> <li>
Launch the <strong>Yimaru mobile app</strong> and <strong>sign in</strong> to the account you want to remove. Launch the <strong>Rezina mobile app</strong> and <strong>sign in</strong> to the account you want to remove.
</li> </li>
<li> <li>
Open your <strong>Profile</strong> area from the main menu or bottom navigation bar. Open your <strong>Profile</strong> area from the main menu or bottom navigation bar.

View File

@ -4,7 +4,7 @@ export function PrivacyPage() {
return ( return (
<InfoLayout <InfoLayout
title="Privacy Policy" title="Privacy Policy"
subtitle="This policy explains how Yimaru Academy handles personal, educational, and operational data across learning and administration workflows." subtitle="This policy explains how Rezina Academy handles personal, educational, and operational data across learning and administration workflows."
> >
<section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm"> <section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm">
<h2 className="text-lg font-semibold text-grayScale-700">Data We Process</h2> <h2 className="text-lg font-semibold text-grayScale-700">Data We Process</h2>

View File

@ -4,7 +4,7 @@ export function TermsPage() {
return ( return (
<InfoLayout <InfoLayout
title="Terms and Conditions" title="Terms and Conditions"
subtitle="These terms define acceptable use of Yimaru Academy services, administration interfaces, and related learning operations." subtitle="These terms define acceptable use of Rezina Academy services, administration interfaces, and related learning operations."
> >
<section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm"> <section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm">
<h2 className="text-lg font-semibold text-grayScale-700">1. Acceptable Use</h2> <h2 className="text-lg font-semibold text-grayScale-700">1. Acceptable Use</h2>
@ -25,7 +25,7 @@ export function TermsPage() {
<section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm"> <section className="space-y-3 rounded-xl border border-[#ece4f7] bg-gradient-to-br from-white to-[#fcf8ff] p-5 shadow-sm">
<h2 className="text-lg font-semibold text-grayScale-700">3. Service and Policy Updates</h2> <h2 className="text-lg font-semibold text-grayScale-700">3. Service and Policy Updates</h2>
<p className="text-sm leading-relaxed text-grayScale-600"> <p className="text-sm leading-relaxed text-grayScale-600">
Yimaru Academy may update features, controls, and policies to improve reliability and Rezina Academy may update features, controls, and policies to improve reliability and
security. Continued platform use indicates acceptance of updated terms. security. Continued platform use indicates acceptance of updated terms.
</p> </p>
</section> </section>

View File

@ -155,7 +155,7 @@ export function AcceptInvitePage() {
<div className="relative z-10 max-w-md px-12 text-center"> <div className="relative z-10 max-w-md px-12 text-center">
<BrandLogo variant="light" className="mx-auto mb-8 h-16" /> <BrandLogo variant="light" className="mx-auto mb-8 h-16" />
<p className="text-base leading-relaxed text-white/70"> <p className="text-base leading-relaxed text-white/70">
You have been invited to join the Yimaru admin panel. Verify your invitation, You have been invited to join the Rezina admin panel. Verify your invitation,
then complete setup to activate your account. then complete setup to activate your account.
</p> </p>
</div> </div>

View File

@ -159,7 +159,7 @@ export function ForgotPasswordPage() {
)} )}
<p className="mt-10 text-center text-xs text-grayScale-400"> <p className="mt-10 text-center text-xs text-grayScale-400">
© {new Date().getFullYear()} Yimaru Academy · All rights reserved © {new Date().getFullYear()} Rezina Academy · All rights reserved
</p> </p>
</div> </div>
</div> </div>

View File

@ -412,7 +412,7 @@ export function LoginPage() {
{/* Footer */} {/* Footer */}
<div className="mt-10 text-center text-xs text-grayScale-400"> <div className="mt-10 text-center text-xs text-grayScale-400">
<p>© {new Date().getFullYear()} Yimaru Academy · All rights reserved</p> <p>© {new Date().getFullYear()} Rezina Academy · All rights reserved</p>
</div> </div>
</div> </div>
</div> </div>

View File

@ -325,7 +325,7 @@ export function ResetPasswordPage() {
) : null} ) : null}
<p className="mt-10 text-center text-xs text-grayScale-400"> <p className="mt-10 text-center text-xs text-grayScale-400">
© {new Date().getFullYear()} Yimaru Academy · All rights reserved © {new Date().getFullYear()} Rezina Academy · All rights reserved
</p> </p>
</div> </div>
</div> </div>

View File

@ -26,6 +26,7 @@ import {
formatPracticeParentsSummary, formatPracticeParentsSummary,
validatePracticeParents, validatePracticeParents,
} from "../../lib/practiceParents"; } from "../../lib/practiceParents";
import { hasRichTextContent } from "../../lib/richText";
import { ContextStep } from "./components/practice-steps/ContextStep"; import { ContextStep } from "./components/practice-steps/ContextStep";
import { ScenarioStep } from "./components/practice-steps/ScenarioStep"; import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
@ -102,8 +103,6 @@ export function AddPracticeFlow() {
const lid = lessonId ? Number(lessonId) : NaN; const lid = lessonId ? Number(lessonId) : NaN;
return Number.isFinite(lid) && lid > 0; return Number.isFinite(lid) && lid > 0;
}, [lessonId]); }, [lessonId]);
/** Learn English lesson practices skip story fields; exam prep lessons use the full form. */
const isLearnEnglishLessonPractice = isLessonPractice && !isExamPrep;
const parentContext = useMemo((): { const parentContext = useMemo((): {
kind: PracticeParentKind; kind: PracticeParentKind;
@ -386,10 +385,7 @@ export function AddPracticeFlow() {
return; return;
} }
const createParents = buildCreatePracticeParentsPayload(parents); const createParents = buildCreatePracticeParentsPayload(parents);
if ( if (!formData.title.trim() || !hasRichTextContent(formData.description)) {
!isLearnEnglishLessonPractice &&
(!formData.title.trim() || !formData.description.trim())
) {
toast.error("Title and story description are required", { toast.error("Title and story description are required", {
description: "Complete the first step before publishing.", description: "Complete the first step before publishing.",
}); });
@ -451,10 +447,6 @@ export function AddPracticeFlow() {
return; return;
} }
const lessonDefaultTitle =
lessonTitleDisplay?.trim() ||
(lessonId ? `Lesson ${lessonId} practice` : "Lesson practice");
const useExamPrepLessonApi = const useExamPrepLessonApi =
isExamPrep && isExamPrep &&
isLessonPractice && isLessonPractice &&
@ -491,22 +483,12 @@ export function AddPracticeFlow() {
examPrepUnitId: useExamPrepUnitApi ? parentContext!.id : undefined, examPrepUnitId: useExamPrepUnitApi ? parentContext!.id : undefined,
isExamPrep, isExamPrep,
status, status,
questionSetTitle: isLearnEnglishLessonPractice questionSetTitle: formData.title.trim() || "Practice set",
? lessonDefaultTitle questionSetDescription: formData.description.trim() || null,
: formData.title.trim() || "Practice set",
questionSetDescription: isLearnEnglishLessonPractice
? null
: formData.description.trim() || null,
shuffleQuestions: formData.shuffleQuestions, shuffleQuestions: formData.shuffleQuestions,
practiceTitle: isLearnEnglishLessonPractice practiceTitle: formData.title.trim() || "Untitled practice",
? lessonDefaultTitle storyDescription: formData.description.trim(),
: formData.title.trim() || "Untitled practice", storyImage: formData.storyImageUrl.trim(),
storyDescription: isLearnEnglishLessonPractice
? ""
: formData.description.trim(),
storyImage: isLearnEnglishLessonPractice
? ""
: formData.storyImageUrl.trim(),
quickTips: formData.tips.trim(), quickTips: formData.tips.trim(),
personaName: persona?.name ?? null, personaName: persona?.name ?? null,
personaId, personaId,
@ -528,8 +510,6 @@ export function AddPracticeFlow() {
}, },
questions: mappedQuestions, questions: mappedQuestions,
definitions: typeDefinitions, definitions: typeDefinitions,
isLearnEnglishLessonPractice,
lessonDefaultTitle,
}); });
} }
toast.success("Practice created successfully"); toast.success("Practice created successfully");
@ -652,7 +632,6 @@ export function AddPracticeFlow() {
setFormData={setFormData} setFormData={setFormData}
nextStep={nextStep} nextStep={nextStep}
onCancel={goBack} onCancel={goBack}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
parentSummary={parentSummary} parentSummary={parentSummary}
/> />
@ -688,7 +667,6 @@ export function AddPracticeFlow() {
formData={formData} formData={formData}
selectedPersona={selectedPersona} selectedPersona={selectedPersona}
personas={personas} personas={personas}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
programLabel={programLabel} programLabel={programLabel}
courseLabel={courseId ? `Course ${courseId}` : null} courseLabel={courseId ? `Course ${courseId}` : null}
@ -755,7 +733,6 @@ export function AddPracticeFlow() {
formData={formData} formData={formData}
selectedPersona={selectedPersona} selectedPersona={selectedPersona}
personas={personas} personas={personas}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
programLabel={programLabel} programLabel={programLabel}
courseLabel={courseId ? `Course ${courseId}` : null} courseLabel={courseId ? `Course ${courseId}` : null}

View File

@ -69,8 +69,10 @@ import { PublishPracticeButton } from "./components/PublishPracticeButton";
import { DisplayValue } from "../../lib/displayValue" import { DisplayValue } from "../../lib/displayValue"
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents" import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents"
import { import {
hasCourseDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listCourseContextUnlinkParents, listCourseContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink" } from "../../lib/practiceParentUnlink"
import { SearchHighlight } from "../../components/SearchHighlight" import { SearchHighlight } from "../../components/SearchHighlight"
@ -204,6 +206,7 @@ export function CourseDetailPage() {
const [practicesLoadError, setPracticesLoadError] = useState<string | null>( const [practicesLoadError, setPracticesLoadError] = useState<string | null>(
null, null,
); );
const [directPracticesLoaded, setDirectPracticesLoaded] = useState(false);
const [publishStatusPracticeId, setPublishStatusPracticeId] = useState< const [publishStatusPracticeId, setPublishStatusPracticeId] = useState<
number | null number | null
>(null); >(null);
@ -351,14 +354,27 @@ export function CourseDetailPage() {
setPractices([]); setPractices([]);
setPracticesLoadError("Failed to load practices. Please try again."); setPracticesLoadError("Failed to load practices. Please try again.");
} finally { } finally {
setDirectPracticesLoaded(true);
setPracticesLoading(false); setPracticesLoading(false);
} }
}, [courseIdNum]); }, [courseIdNum]);
useEffect(() => { useEffect(() => {
if (activeTab !== "practice") return;
void loadCoursePractices(); void loadCoursePractices();
}, [activeTab, loadCoursePractices]); }, [loadCoursePractices]);
const courseHasDirectPractice = useMemo(() => {
if (practices.length > 0) return true;
if (directPracticesLoaded) return false;
return (
Boolean(course?.has_practice) || Number(course?.practice_count ?? 0) > 0
);
}, [
course?.has_practice,
course?.practice_count,
directPracticesLoaded,
practices.length,
]);
const filteredModules = useMemo( const filteredModules = useMemo(
() => () =>
@ -453,22 +469,27 @@ export function CourseDetailPage() {
if (!practiceToUnlink || !Number.isFinite(courseIdNum) || courseIdNum < 1) { if (!practiceToUnlink || !Number.isFinite(courseIdNum) || courseIdNum < 1) {
return []; return [];
} }
return listCourseContextUnlinkParents( return listCourseContextUnlinkParents(practiceToUnlink, courseIdNum);
practiceToUnlink, }, [courseIdNum, practiceToUnlink]);
courseIdNum,
courseModuleIds, const courseUnlinkContext = useMemo(
courseLessonIds, () => ({
); scope: "course" as const,
}, [ courseId: courseIdNum,
courseIdNum, moduleIds: courseModuleIds,
courseLessonIds, lessonIds: courseLessonIds,
courseModuleIds, }),
practiceToUnlink, [courseIdNum, courseLessonIds, courseModuleIds],
]); );
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink || practiceUnlinkParents.length === 0) { if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error("This practice is not linked to this course."); toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, courseUnlinkContext) ??
"This practice is not linked to this course."
: "This practice is not linked to this course.",
);
return; return;
} }
setUnlinkingPractice(true); setUnlinkingPractice(true);
@ -675,9 +696,9 @@ export function CourseDetailPage() {
backTo: "modules", backTo: "modules",
}} }}
parentLabel={displayTitle} parentLabel={displayTitle}
disabled={practices.length > 0} disabled={courseHasDirectPractice}
title={ title={
practices.length > 0 ? learnEnglishPracticeLimitHint : undefined courseHasDirectPractice ? learnEnglishPracticeLimitHint : undefined
} }
> >
<Calendar className="h-4 w-4" /> <Calendar className="h-4 w-4" />
@ -939,6 +960,7 @@ export function CourseDetailPage() {
moduleName: module.name, moduleName: module.name,
moduleDescription: moduleDescription:
module.description?.trim() ?? "", module.description?.trim() ?? "",
moduleHasPractice: Boolean(module.has_practice),
}, },
}, },
) )
@ -984,12 +1006,7 @@ export function CourseDetailPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={practiceSearch} searchQuery={practiceSearch}
locationLabel={displayTitle} locationLabel={displayTitle}
unlinkContext={{ unlinkContext={courseUnlinkContext}
scope: "course",
courseId: courseIdNum,
moduleIds: courseModuleIds,
lessonIds: courseLessonIds,
}}
publishStatusUpdatingId={publishStatusPracticeId} publishStatusUpdatingId={publishStatusPracticeId}
onReload={loadCoursePractices} onReload={loadCoursePractices}
unlinkActionLabel="Remove from course" unlinkActionLabel="Remove from course"
@ -1005,7 +1022,16 @@ export function CourseDetailPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasCourseDirectPracticeLink(practice, courseIdNum)) {
toast.info(
practiceUnlinkBlockedMessage(practice, courseUnlinkContext) ??
"This practice is not directly linked to this course.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
) : ( ) : (

View File

@ -45,6 +45,7 @@ import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
import { ReviewStep } from "./components/practice-steps/ReviewStep"; import { ReviewStep } from "./components/practice-steps/ReviewStep";
import { personaIdNumber } from "./components/practice-steps/constants"; import { personaIdNumber } from "./components/practice-steps/constants";
import { useActivePersonas } from "../../hooks/useActivePersonas"; import { useActivePersonas } from "../../hooks/useActivePersonas";
import { hasRichTextContent } from "../../lib/richText";
const STEP_LABELS = ["Practice", "Persona", "Questions", "Review"] as const; const STEP_LABELS = ["Practice", "Persona", "Questions", "Review"] as const;
@ -448,10 +449,7 @@ export function EditPracticeFlow() {
toast.error("Invalid practice", { description: "Missing practice id in the URL." }); toast.error("Invalid practice", { description: "Missing practice id in the URL." });
return; return;
} }
if ( if (!formData.title.trim() || !hasRichTextContent(formData.description)) {
!isLearnEnglishLessonPractice &&
(!formData.title.trim() || !formData.description.trim())
) {
toast.error("Title and story description are required", { toast.error("Title and story description are required", {
description: "Complete the first step before saving.", description: "Complete the first step before saving.",
}); });
@ -510,10 +508,6 @@ export function EditPracticeFlow() {
return; return;
} }
const lessonDefaultTitle =
lessonTitleDisplay?.trim() ||
(lessonId ? `Lesson ${lessonId} practice` : "Lesson practice");
if (!isExamPrep) { if (!isExamPrep) {
const parentsErr = validatePracticeParents(formData.parents, { const parentsErr = validatePracticeParents(formData.parents, {
required: !parentsOptional, required: !parentsOptional,
@ -544,8 +538,6 @@ export function EditPracticeFlow() {
}, },
questions: mappedQuestions, questions: mappedQuestions,
definitions: typeDefinitions, definitions: typeDefinitions,
isLearnEnglishLessonPractice,
lessonDefaultTitle,
parents: dedupeParents(formData.parents), parents: dedupeParents(formData.parents),
parentsChanged: !practiceParentsEqual( parentsChanged: !practiceParentsEqual(
formData.parents, formData.parents,
@ -631,7 +623,6 @@ export function EditPracticeFlow() {
setFormData={setFormData} setFormData={setFormData}
nextStep={nextStep} nextStep={nextStep}
onCancel={() => goBack()} onCancel={() => goBack()}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
parentSummary={reviewParentSummary} parentSummary={reviewParentSummary}
showParentsEditor={!isLearnEnglishLessonPractice} showParentsEditor={!isLearnEnglishLessonPractice}
@ -683,7 +674,6 @@ export function EditPracticeFlow() {
formData={formData} formData={formData}
selectedPersona={selectedPersona} selectedPersona={selectedPersona}
personas={personas} personas={personas}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
programLabel={programLabel} programLabel={programLabel}
courseLabel={courseId ? `Course ${courseId}` : null} courseLabel={courseId ? `Course ${courseId}` : null}
@ -748,7 +738,6 @@ export function EditPracticeFlow() {
formData={formData} formData={formData}
selectedPersona={selectedPersona} selectedPersona={selectedPersona}
personas={personas} personas={personas}
isLessonPractice={isLearnEnglishLessonPractice}
lessonTitle={lessonTitleDisplay} lessonTitle={lessonTitleDisplay}
programLabel={programLabel} programLabel={programLabel}
courseLabel={courseId ? `Course ${courseId}` : null} courseLabel={courseId ? `Course ${courseId}` : null}

View File

@ -16,7 +16,10 @@ import {
parentsFromPractice, parentsFromPractice,
} from "../../lib/practiceParents"; } from "../../lib/practiceParents";
import { import {
hasLessonDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listLessonContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink"; } from "../../lib/practiceParentUnlink";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
@ -33,7 +36,6 @@ import type {
ExamPrepLessonPractice, ExamPrepLessonPractice,
GetExamPrepLessonPracticesResponse, GetExamPrepLessonPracticesResponse,
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../types/course.types"; } from "../../types/course.types";
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar"; import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
@ -85,6 +87,7 @@ export function LessonPracticesPage() {
}>(); }>();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const lessonTitle = searchParams.get("lessonTitle")?.trim() || ""; const lessonTitle = searchParams.get("lessonTitle")?.trim() || "";
const lessonHasPracticeHint = searchParams.get("hasPractice") === "1";
const isExamPrep = Boolean(programType?.trim()); const isExamPrep = Boolean(programType?.trim());
const backHref = isExamPrep const backHref = isExamPrep
@ -105,6 +108,7 @@ export function LessonPracticesPage() {
const [listSearch, setListSearch] = useState(""); const [listSearch, setListSearch] = useState("");
const [publishStatusFilter, setPublishStatusFilter] = const [publishStatusFilter, setPublishStatusFilter] =
useState<PublishStatusFilter>("all"); useState<PublishStatusFilter>("all");
const [practicesLoaded, setPracticesLoaded] = useState(false);
const filteredPractices = useMemo( const filteredPractices = useMemo(
() => () =>
@ -163,6 +167,7 @@ export function LessonPracticesPage() {
setLoadError("Could not load practices for this lesson."); setLoadError("Could not load practices for this lesson.");
notifyApiError(error, "Failed to load practices"); notifyApiError(error, "Failed to load practices");
} finally { } finally {
setPracticesLoaded(true);
setLoading(false); setLoading(false);
} }
}, [isExamPrep, lid, validLesson]); }, [isExamPrep, lid, validLesson]);
@ -174,6 +179,18 @@ export function LessonPracticesPage() {
const displayTitle = const displayTitle =
lessonTitle || (validLesson ? `Lesson #${lid}` : "Lesson practices"); lessonTitle || (validLesson ? `Lesson #${lid}` : "Lesson practices");
const lessonHasDirectPractice = useMemo(() => {
if (!isExamPrep && (practices.length > 0 || totalCount > 0)) return true;
if (!isExamPrep && practicesLoaded) return false;
return !isExamPrep && lessonHasPracticeHint;
}, [
isExamPrep,
lessonHasPracticeHint,
practices.length,
practicesLoaded,
totalCount,
]);
const practicePathOptions = useMemo( const practicePathOptions = useMemo(
() => ({ () => ({
isExamPrep, isExamPrep,
@ -243,20 +260,35 @@ export function LessonPracticesPage() {
} }
}; };
const lessonParent = useMemo( const lessonUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "LESSON", parent_id: lid }), () => ({ scope: "lesson" as const, lessonId: lid }),
[lid], [lid],
); );
const practiceUnlinkParents = useMemo(() => {
if (!practiceToUnlink) return [];
return listLessonContextUnlinkParents(practiceToUnlink, lid);
}, [lid, practiceToUnlink]);
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return; if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, lessonUnlinkContext) ??
"This practice is not linked to this lesson."
: "This practice is not linked to this lesson.",
);
return;
}
setUnlinking(true); setUnlinking(true);
try { try {
await unlinkPracticeFromParent({ for (const parent of practiceUnlinkParents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: lessonParent, practiceId: practiceToUnlink.id,
isExamPrep, parent,
}); isExamPrep,
});
}
toast.success(`Practice removed from ${displayTitle}`); toast.success(`Practice removed from ${displayTitle}`);
setPracticeToUnlink(null); setPracticeToUnlink(null);
await load(); await load();
@ -345,11 +377,9 @@ export function LessonPracticesPage() {
className="rounded-[6px] bg-brand-500 font-semibold hover:bg-brand-600" className="rounded-[6px] bg-brand-500 font-semibold hover:bg-brand-600"
pathOptions={practicePathOptions} pathOptions={practicePathOptions}
parentLabel={displayTitle} parentLabel={displayTitle}
disabled={!isExamPrep && practices.length >= 1} disabled={lessonHasDirectPractice}
title={ title={
!isExamPrep && practices.length >= 1 lessonHasDirectPractice ? learnEnglishPracticeLimitHint : undefined
? learnEnglishPracticeLimitHint
: undefined
} }
> >
<Calendar className="h-4 w-4" /> <Calendar className="h-4 w-4" />
@ -417,7 +447,7 @@ export function LessonPracticesPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={displayTitle} locationLabel={displayTitle}
unlinkContext={{ scope: "lesson", lessonId: lid }} unlinkContext={lessonUnlinkContext}
isExamPrep={isExamPrep} isExamPrep={isExamPrep}
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -430,7 +460,16 @@ export function LessonPracticesPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasLessonDirectPracticeLink(practice, lid)) {
toast.info(
practiceUnlinkBlockedMessage(practice, lessonUnlinkContext) ??
"This practice is not directly linked to this lesson.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -121,17 +121,19 @@ export function LinkExistingPracticeFlow() {
]) ])
const backLabel = const backLabel =
effectiveBackTo === "module" effectiveBackTo === "lesson"
? "Back to Module" ? "Back to Lessons"
: effectiveBackTo === "unit" : effectiveBackTo === "module"
? "Back to Unit" ? "Back to Module"
: effectiveBackTo === "modules" : effectiveBackTo === "unit"
? "Back to Modules" ? "Back to Unit"
: effectiveBackTo === "courses" : effectiveBackTo === "modules"
? "Back to Course" ? "Back to Modules"
: isExamPrep : effectiveBackTo === "courses"
? "Back to Program" ? "Back to Course"
: "Back to Courses" : isExamPrep
? "Back to Program"
: "Back to Courses"
const backPath = useMemo(() => { const backPath = useMemo(() => {
if (isExamPrep) { if (isExamPrep) {
@ -150,11 +152,36 @@ export function LinkExistingPracticeFlow() {
if (effectiveBackTo === "courses" && programType && courseId) { if (effectiveBackTo === "courses" && programType && courseId) {
return `/new-content/courses/${programType}/${courseId}` return `/new-content/courses/${programType}/${courseId}`
} }
if (
effectiveBackTo === "lesson" &&
programType &&
courseId &&
unitId &&
moduleId &&
lessonId
) {
const titleQuery = lessonTitleRaw?.trim()
? `?lessonTitle=${encodeURIComponent(lessonTitleDisplay || lessonTitleRaw)}`
: ""
return `/new-content/courses/${programType}/${courseId}/${unitId}/${moduleId}/lessons/${lessonId}/practices${titleQuery}`
}
if (programType) { if (programType) {
return `/new-content/courses/${programType}` return `/new-content/courses/${programType}`
} }
return "/new-content" return "/new-content"
} }
if (
effectiveBackTo === "lesson" &&
level &&
courseId &&
moduleId &&
lessonId
) {
const titleQuery = lessonTitleRaw?.trim()
? `?lessonTitle=${encodeURIComponent(lessonTitleDisplay || lessonTitleRaw)}`
: ""
return `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/lessons/${lessonId}/practices${titleQuery}`
}
if (effectiveBackTo === "module" && level && courseId && moduleId) { if (effectiveBackTo === "module" && level && courseId && moduleId) {
return `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}` return `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}`
} }
@ -169,6 +196,9 @@ export function LinkExistingPracticeFlow() {
courseId, courseId,
unitId, unitId,
moduleId, moduleId,
lessonId,
lessonTitleRaw,
lessonTitleDisplay,
level, level,
]) ])

View File

@ -19,6 +19,7 @@ import type {
ParentContextPractice, ParentContextPractice,
PracticeParent, PracticeParent,
PracticePublishStatus, PracticePublishStatus,
TopLevelCourseModuleItem,
TopLevelModuleLessonItem, TopLevelModuleLessonItem,
} from "../../types/course.types"; } from "../../types/course.types";
import { unwrapPracticesPage } from "../../lib/parentContextPractice"; import { unwrapPracticesPage } from "../../lib/parentContextPractice";
@ -28,8 +29,10 @@ import {
} from "../../lib/fetchAllOffsetPages"; } from "../../lib/fetchAllOffsetPages";
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents"; import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents";
import { import {
hasModuleDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
listModuleContextUnlinkParents, listModuleContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../lib/practiceParentUnlink"; } from "../../lib/practiceParentUnlink";
import { Button } from "../../components/ui/button"; import { Button } from "../../components/ui/button";
@ -69,6 +72,7 @@ const LESSON_THUMB_GRADIENTS = [
type ModuleDetailState = { type ModuleDetailState = {
moduleName?: string; moduleName?: string;
moduleDescription?: string; moduleDescription?: string;
moduleHasPractice?: boolean;
}; };
export function ModuleDetailPage() { export function ModuleDetailPage() {
@ -134,6 +138,10 @@ export function ModuleDetailPage() {
const [practicesLoadError, setPracticesLoadError] = useState<string | null>( const [practicesLoadError, setPracticesLoadError] = useState<string | null>(
null, null,
); );
const [directPracticesLoaded, setDirectPracticesLoaded] = useState(false);
const [loadedModuleHasPractice, setLoadedModuleHasPractice] = useState<
boolean | null
>(navState?.moduleHasPractice ?? null);
const [publishStatusPracticeId, setPublishStatusPracticeId] = useState< const [publishStatusPracticeId, setPublishStatusPracticeId] = useState<
number | null number | null
>(null); >(null);
@ -191,7 +199,7 @@ export function ModuleDetailPage() {
(async () => { (async () => {
try { try {
const list = await fetchAllOffsetPages(async (offset, limit) => const list = await fetchAllOffsetPages(async (offset, limit) =>
offsetPageFromListEnvelope<{ id: number; name: string; description?: string | null }>( offsetPageFromListEnvelope<TopLevelCourseModuleItem>(
await getTopLevelCourseModules(cid, { limit, offset }), await getTopLevelCourseModules(cid, { limit, offset }),
"modules", "modules",
), ),
@ -202,9 +210,11 @@ export function ModuleDetailPage() {
if (m) { if (m) {
setLoadedModuleName(m.name); setLoadedModuleName(m.name);
setLoadedModuleDescription(m.description ?? ""); setLoadedModuleDescription(m.description ?? "");
setLoadedModuleHasPractice(Boolean(m.has_practice));
} else { } else {
setLoadedModuleName(null); setLoadedModuleName(null);
setLoadedModuleDescription(""); setLoadedModuleDescription("");
setLoadedModuleHasPractice(null);
} }
} else { } else {
setLoadedModuleName(null); setLoadedModuleName(null);
@ -294,14 +304,20 @@ export function ModuleDetailPage() {
setPractices([]); setPractices([]);
setPracticesLoadError("Failed to load practices. Please try again."); setPracticesLoadError("Failed to load practices. Please try again.");
} finally { } finally {
setDirectPracticesLoaded(true);
setPracticesLoading(false); setPracticesLoading(false);
} }
}, [moduleId]); }, [moduleId]);
useEffect(() => { useEffect(() => {
if (activeTab !== "practice") return;
void loadModulePractices(); void loadModulePractices();
}, [activeTab, loadModulePractices]); }, [loadModulePractices]);
const moduleHasDirectPractice = useMemo(() => {
if (practices.length > 0) return true;
if (directPracticesLoaded) return false;
return loadedModuleHasPractice === true;
}, [directPracticesLoaded, loadedModuleHasPractice, practices.length]);
const filteredLessons = useMemo( const filteredLessons = useMemo(
() => () =>
@ -361,19 +377,29 @@ export function ModuleDetailPage() {
[lessons], [lessons],
); );
const moduleUnlinkContext = useMemo(
() => ({
scope: "module" as const,
moduleId: Number(moduleId),
lessonIds: moduleLessonIds,
}),
[moduleId, moduleLessonIds],
);
const practiceUnlinkParents = useMemo((): PracticeParent[] => { const practiceUnlinkParents = useMemo((): PracticeParent[] => {
const mid = Number(moduleId); const mid = Number(moduleId);
if (!practiceToUnlink || !Number.isFinite(mid) || mid < 1) return []; if (!practiceToUnlink || !Number.isFinite(mid) || mid < 1) return [];
return listModuleContextUnlinkParents( return listModuleContextUnlinkParents(practiceToUnlink, mid);
practiceToUnlink, }, [moduleId, practiceToUnlink]);
mid,
moduleLessonIds,
);
}, [moduleId, moduleLessonIds, practiceToUnlink]);
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink || practiceUnlinkParents.length === 0) { if (!practiceToUnlink || practiceUnlinkParents.length === 0) {
toast.error("This practice is not linked to this module."); toast.error(
practiceToUnlink
? practiceUnlinkBlockedMessage(practiceToUnlink, moduleUnlinkContext) ??
"This practice is not linked to this module."
: "This practice is not linked to this module.",
);
return; return;
} }
setUnlinkingPractice(true); setUnlinkingPractice(true);
@ -567,9 +593,9 @@ export function ModuleDetailPage() {
className="rounded-[6px] border-brand-500 text-brand-500 " className="rounded-[6px] border-brand-500 text-brand-500 "
pathOptions={modulePracticePathOptions} pathOptions={modulePracticePathOptions}
parentLabel={displayModuleName} parentLabel={displayModuleName}
disabled={practices.length > 0} disabled={moduleHasDirectPractice}
title={ title={
practices.length > 0 ? learnEnglishPracticeLimitHint : undefined moduleHasDirectPractice ? learnEnglishPracticeLimitHint : undefined
} }
> >
<Calendar className="h-4 w-4" /> <Calendar className="h-4 w-4" />
@ -683,7 +709,7 @@ export function ModuleDetailPage() {
addPracticeDisabled={!!lesson.has_practice} addPracticeDisabled={!!lesson.has_practice}
onViewPractices={() => onViewPractices={() =>
navigate( navigate(
`/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/lessons/${lesson.id}/practices?lessonTitle=${encodeURIComponent(lesson.title ?? "")}`, `/new-content/learn-english/${level}/courses/${courseId}/modules/${moduleId}/lessons/${lesson.id}/practices?lessonTitle=${encodeURIComponent(lesson.title ?? "")}${lesson.has_practice ? "&hasPractice=1" : ""}`,
) )
} }
onTogglePublishStatus={(nextStatus) => onTogglePublishStatus={(nextStatus) =>
@ -752,11 +778,7 @@ export function ModuleDetailPage() {
practices={filteredPractices} practices={filteredPractices}
searchQuery={practiceSearch} searchQuery={practiceSearch}
locationLabel={displayModuleName} locationLabel={displayModuleName}
unlinkContext={{ unlinkContext={moduleUnlinkContext}
scope: "module",
moduleId: Number(moduleId),
lessonIds: moduleLessonIds,
}}
publishStatusUpdatingId={publishStatusPracticeId} publishStatusUpdatingId={publishStatusPracticeId}
onReload={loadModulePractices} onReload={loadModulePractices}
unlinkActionLabel="Remove from module" unlinkActionLabel="Remove from module"
@ -772,7 +794,17 @@ export function ModuleDetailPage() {
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
const mid = Number(moduleId);
if (!hasModuleDirectPracticeLink(practice, mid)) {
toast.info(
practiceUnlinkBlockedMessage(practice, moduleUnlinkContext) ??
"This practice is not directly linked to this module.",
);
return;
}
setPracticeToUnlink(practice);
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
) : ( ) : (

View File

@ -22,15 +22,23 @@ import {
DialogClose, DialogClose,
} from "../../components/ui/dialog"; } from "../../components/ui/dialog";
import { Input } from "../../components/ui/input"; import { Input } from "../../components/ui/input";
import { Textarea } from "../../components/ui/textarea";
import { toast } from "sonner"; import { toast } from "sonner";
import { ResolvedImage } from "../../components/media/ResolvedImage"; import { ResolvedImage } from "../../components/media/ResolvedImage";
import { import {
createExamPrepCatalogCourse, createExamPrepCatalogCourse,
createProgramCourse,
deleteExamPrepCatalogCourse,
deleteTopLevelCourse,
getExamPrepCatalogCourses, getExamPrepCatalogCourses,
getLearningPrograms,
getProgramCourses,
setExamPrepCatalogCourseAccessTier, setExamPrepCatalogCourseAccessTier,
setExamPrepCatalogCoursePublishStatus, setExamPrepCatalogCoursePublishStatus,
setProgramCourseAccessTier,
setProgramCoursePublishStatus,
updateExamPrepCatalogCourse, updateExamPrepCatalogCourse,
deleteExamPrepCatalogCourse, updateTopLevelCourse,
} from "../../api/courses.api"; } from "../../api/courses.api";
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip"; import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
import { ContentAccessTierChip } from "./components/ContentAccessTierChip"; import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
@ -38,8 +46,11 @@ import { ContentListSearchFilterBar } from "./components/ContentListSearchFilter
import { ContentPageDescription } from "./components/ContentPageDescription"; import { ContentPageDescription } from "./components/ContentPageDescription";
import type { import type {
ContentAccessTier, ContentAccessTier,
ExamPrepCatalogCategory,
ExamPrepCatalogCourseItem, ExamPrepCatalogCourseItem,
LearningProgramListItem,
PracticePublishStatus, PracticePublishStatus,
ProgramCourseListItem,
} from "../../types/course.types"; } from "../../types/course.types";
import { import {
filterBySearchAndPublishStatus, filterBySearchAndPublishStatus,
@ -55,29 +66,39 @@ import {
offsetPageFromListEnvelope, offsetPageFromListEnvelope,
} from "../../lib/fetchAllOffsetPages"; } from "../../lib/fetchAllOffsetPages";
type CourseListRow = {
id: number;
programId?: number;
programName?: string;
category?: ExamPrepCatalogCategory | string | null;
name: string;
description: string;
thumbnail?: string | null;
sortOrder: number;
publishStatus: PracticePublishStatus | string | null;
accessTier: ContentAccessTier | string | null;
unitsCount: number;
modulesCount: number;
lessonsCount: number;
};
export function ProgramDetailPage() { export function ProgramDetailPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { programType } = useParams<{ programType: string }>(); const { programType } = useParams<{ programType: string }>();
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [createName, setCreateName] = useState(""); const [createName, setCreateName] = useState("");
const [createDescription, setCreateDescription] = useState("");
const [createSortOrder, setCreateSortOrder] = useState("");
const [createProgramId, setCreateProgramId] = useState("");
const [createCategory, setCreateCategory] = useState<ExamPrepCatalogCategory | "">("");
const [createThumbnail, setCreateThumbnail] = useState(""); const [createThumbnail, setCreateThumbnail] = useState("");
const [createThumbnailFromUpload, setCreateThumbnailFromUpload] = useState(false); const [createThumbnailFromUpload, setCreateThumbnailFromUpload] = useState(false);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const [uploadingThumbnail, setUploadingThumbnail] = useState(false); const [uploadingThumbnail, setUploadingThumbnail] = useState(false);
const createThumbnailFileInputRef = useRef<HTMLInputElement>(null); const createThumbnailFileInputRef = useRef<HTMLInputElement>(null);
const [createdCourses, setCreatedCourses] = useState< const [createdCourses, setCreatedCourses] = useState<CourseListRow[]>([]);
{ const [learningPrograms, setLearningPrograms] = useState<
id: number; LearningProgramListItem[]
name: string;
description: string;
thumbnail?: string | null;
sortOrder: number;
publishStatus: PracticePublishStatus | string | null;
accessTier: ContentAccessTier | string | null;
unitsCount: number;
modulesCount: number;
lessonsCount: number;
}[]
>([]); >([]);
const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState< const [publishStatusUpdatingId, setPublishStatusUpdatingId] = useState<
number | null number | null
@ -88,6 +109,8 @@ export function ProgramDetailPage() {
const [catalogLoading, setCatalogLoading] = useState(false); const [catalogLoading, setCatalogLoading] = useState(false);
const [editingCourseId, setEditingCourseId] = useState<number | null>(null); const [editingCourseId, setEditingCourseId] = useState<number | null>(null);
const [editName, setEditName] = useState(""); const [editName, setEditName] = useState("");
const [editDescription, setEditDescription] = useState("");
const [editCategory, setEditCategory] = useState<ExamPrepCatalogCategory | "">("");
const [editThumbnail, setEditThumbnail] = useState(""); const [editThumbnail, setEditThumbnail] = useState("");
const [editSortOrder, setEditSortOrder] = useState("1"); const [editSortOrder, setEditSortOrder] = useState("1");
const [savingEdit, setSavingEdit] = useState(false); const [savingEdit, setSavingEdit] = useState(false);
@ -114,48 +137,112 @@ export function ProgramDetailPage() {
const currentProgram = const currentProgram =
programs[programType || "proficiency"] || programs.proficiency; programs[programType || "proficiency"] || programs.proficiency;
const isProficiency = programType === "proficiency";
const isSkillBased = programType === "skill-based";
const loadCatalogCourses = useCallback(async () => { const mapExamPrepCourse = (row: ExamPrepCatalogCourseItem): CourseListRow => ({
if (programType !== "proficiency") return; id: Number(row.id),
category: row.category ?? null,
name: row.name?.trim() || `Course ${row.id}`,
description: row.description?.trim() || "",
thumbnail: row.thumbnail?.trim() || null,
sortOrder: Number(row.sort_order ?? 0),
publishStatus: row.publish_status ?? null,
accessTier: row.access_tier ?? null,
unitsCount: Number(row.units_count ?? 0),
modulesCount: Number(row.modules_count ?? 0),
lessonsCount: Number(row.lessons_count ?? 0),
});
const mapProgramCourse = (
row: ProgramCourseListItem,
programName?: string,
): CourseListRow => ({
id: Number(row.id),
programId: Number(row.program_id),
programName: programName?.trim() || undefined,
name: row.name?.trim() || `Course ${row.id}`,
description: row.description?.trim() || "",
thumbnail: row.thumbnail?.trim() || row.thumbnail_url?.trim() || null,
sortOrder: Number(row.sort_order ?? 0),
publishStatus: row.publish_status ?? null,
accessTier: row.access_tier ?? null,
unitsCount: 0,
modulesCount: Number(row.module_count ?? row.modules_count ?? 0),
lessonsCount: Number(row.lesson_count ?? 0),
});
const loadCourses = useCallback(async () => {
if (!isProficiency && !isSkillBased) return;
setCatalogLoading(true); setCatalogLoading(true);
try { try {
const list = await fetchAllOffsetPages(async (offset, limit) => if (isProficiency) {
offsetPageFromListEnvelope<ExamPrepCatalogCourseItem>( const list = await fetchAllOffsetPages(async (offset, limit) =>
await getExamPrepCatalogCourses({ limit, offset }), offsetPageFromListEnvelope<ExamPrepCatalogCourseItem>(
"catalog_courses", await getExamPrepCatalogCourses({ limit, offset }),
"catalog_courses",
),
);
setCreatedCourses(list.map(mapExamPrepCourse));
setLearningPrograms([]);
return;
}
const programsList = await fetchAllOffsetPages(async (offset, limit) =>
offsetPageFromListEnvelope<LearningProgramListItem>(
await getLearningPrograms({ limit, offset }),
"programs",
), ),
); );
setLearningPrograms(programsList);
const programNameById = new Map(
programsList.map((program) => [program.id, program.name?.trim() || ""]),
);
const coursePages = await Promise.all(
programsList.map((program) =>
fetchAllOffsetPages(async (offset, limit) =>
offsetPageFromListEnvelope<ProgramCourseListItem>(
await getProgramCourses(program.id, { limit, offset }),
"courses",
),
),
),
);
setCreatedCourses( setCreatedCourses(
list.map((row) => ({ coursePages
id: Number(row.id), .flat()
name: row.name?.trim() || `Course ${row.id}`, .map((row) =>
description: row.description?.trim() || "", mapProgramCourse(row, programNameById.get(row.program_id)),
thumbnail: row.thumbnail?.trim() || null, )
sortOrder: Number(row.sort_order ?? 0), .sort((a, b) => a.sortOrder - b.sortOrder || a.id - b.id),
publishStatus: row.publish_status ?? null,
accessTier: row.access_tier ?? null,
unitsCount: Number(row.units_count ?? 0),
modulesCount: Number(row.modules_count ?? 0),
lessonsCount: Number(row.lessons_count ?? 0),
})),
); );
} catch (error) { } catch (error) {
console.error(error); console.error(error);
notifyApiError(error, "Failed to fetch catalog courses"); notifyApiError(
error,
isProficiency ? "Failed to fetch catalog courses" : "Failed to fetch courses",
);
setCreatedCourses([]); setCreatedCourses([]);
if (isSkillBased) {
setLearningPrograms([]);
}
} finally { } finally {
setCatalogLoading(false); setCatalogLoading(false);
} }
}, [programType]); }, [isProficiency, isSkillBased]);
useEffect(() => { useEffect(() => {
void loadCatalogCourses(); void loadCourses();
}, [loadCatalogCourses]); }, [loadCourses]);
const proficiencyCourses = useMemo( const displayCourses = useMemo(
() => [ () =>
...currentProgram.courses, createdCourses.map((course) => ({
...createdCourses.map((course) => ({
id: course.id, id: course.id,
programId: course.programId,
programName: course.programName,
category: course.category,
name: course.name, name: course.name,
description: course.description, description: course.description,
units_count: course.unitsCount, units_count: course.unitsCount,
@ -168,22 +255,25 @@ export function ProgramDetailPage() {
access_tier: course.accessTier, access_tier: course.accessTier,
buttonText: "View Detail", buttonText: "View Detail",
})), })),
], [createdCourses],
[createdCourses, currentProgram.courses],
); );
const [listSearch, setListSearch] = useState(""); const [listSearch, setListSearch] = useState("");
const [publishStatusFilter, setPublishStatusFilter] = const [publishStatusFilter, setPublishStatusFilter] =
useState<PublishStatusFilter>("all"); useState<PublishStatusFilter>("all");
const filteredProficiencyCourses = useMemo( const filteredCourses = useMemo(
() => () =>
filterBySearchAndPublishStatus(proficiencyCourses, { filterBySearchAndPublishStatus(displayCourses, {
search: listSearch, search: listSearch,
publishStatusFilter, publishStatusFilter,
getSearchFields: (c) => [c.name, c.description], getSearchFields: (c) => [
c.name,
c.description,
c.programName ?? "",
],
getPublishStatus: (c) => c.publish_status, getPublishStatus: (c) => c.publish_status,
}), }),
[listSearch, proficiencyCourses, publishStatusFilter], [listSearch, displayCourses, publishStatusFilter],
); );
const handleCoursePublishStatus = async ( const handleCoursePublishStatus = async (
@ -192,9 +282,15 @@ export function ProgramDetailPage() {
) => { ) => {
setPublishStatusUpdatingId(courseId); setPublishStatusUpdatingId(courseId);
try { try {
await setExamPrepCatalogCoursePublishStatus(courseId, { if (isProficiency) {
publish_status: nextStatus, await setExamPrepCatalogCoursePublishStatus(courseId, {
}); publish_status: nextStatus,
});
} else {
await setProgramCoursePublishStatus(courseId, {
publish_status: nextStatus,
});
}
setCreatedCourses((prev) => setCreatedCourses((prev) =>
prev.map((c) => prev.map((c) =>
c.id === courseId ? { ...c, publishStatus: nextStatus } : c, c.id === courseId ? { ...c, publishStatus: nextStatus } : c,
@ -216,9 +312,15 @@ export function ProgramDetailPage() {
) => { ) => {
setAccessTierUpdatingId(courseId); setAccessTierUpdatingId(courseId);
try { try {
await setExamPrepCatalogCourseAccessTier(courseId, { if (isProficiency) {
access_tier: nextTier, await setExamPrepCatalogCourseAccessTier(courseId, {
}); access_tier: nextTier,
});
} else {
await setProgramCourseAccessTier(courseId, {
access_tier: nextTier,
});
}
setCreatedCourses((prev) => setCreatedCourses((prev) =>
prev.map((c) => prev.map((c) =>
c.id === courseId ? { ...c, accessTier: nextTier } : c, c.id === courseId ? { ...c, accessTier: nextTier } : c,
@ -283,11 +385,17 @@ export function ProgramDetailPage() {
return uploadedUrl; return uploadedUrl;
}; };
const clearCreateCourseForm = () => {
setCreateName("");
setCreateDescription("");
setCreateSortOrder("");
setCreateProgramId("");
setCreateCategory("");
setCreateThumbnail("");
setCreateThumbnailFromUpload(false);
};
const handleCreateCourse = async () => { const handleCreateCourse = async () => {
if (programType !== "proficiency") {
toast.error("Create Course is supported only for proficiency catalog.");
return;
}
const name = createName.trim(); const name = createName.trim();
if (!name) { if (!name) {
toast.error("Course name is required"); toast.error("Course name is required");
@ -310,33 +418,51 @@ export function ProgramDetailPage() {
thumbnailToSend = uploadedUrl; thumbnailToSend = uploadedUrl;
} }
const response = await createExamPrepCatalogCourse({ if (isProficiency) {
name, if (createCategory !== "IELTS" && createCategory !== "DUOLINGO") {
description: null, toast.error("Please select an exam category");
thumbnail: thumbnailToSend, return;
}); }
const row = response.data?.data; const response = await createExamPrepCatalogCourse({
if (!row?.id) { name,
throw new Error("Missing created course payload"); description: null,
category: createCategory,
thumbnail: thumbnailToSend,
});
const row = response.data?.data;
if (!row?.id) {
throw new Error("Missing created course payload");
}
} else if (isSkillBased) {
const programId = Number(createProgramId);
if (!Number.isFinite(programId) || programId < 1) {
toast.error("Please select a program");
return;
}
const sortOrderRaw = createSortOrder.trim();
if (!sortOrderRaw) {
toast.error("Sort order is required");
return;
}
const sort_order = Number(sortOrderRaw);
if (!Number.isInteger(sort_order) || sort_order < 0) {
toast.error("Sort order must be a whole number of 0 or greater");
return;
}
await createProgramCourse(programId, {
name,
description: createDescription.trim(),
thumbnail: thumbnailToSend ?? "",
sort_order,
});
} else {
toast.error("Unsupported program type");
return;
} }
setCreatedCourses((prev) => [
{ await loadCourses();
id: row.id,
name: row.name ?? name,
description: row.description?.trim() || "",
thumbnail: row.thumbnail?.trim() || null,
sortOrder: Number(row.sort_order ?? 0),
unitsCount: Number(row.units_count ?? 0),
modulesCount: Number(row.modules_count ?? 0),
lessonsCount: Number(row.lessons_count ?? 0),
},
...prev,
]);
await loadCatalogCourses();
toast.success("Course created"); toast.success("Course created");
setCreateName(""); clearCreateCourseForm();
setCreateThumbnail("");
setCreateThumbnailFromUpload(false);
setCreateOpen(false); setCreateOpen(false);
} catch (error: unknown) { } catch (error: unknown) {
console.error(error); console.error(error);
@ -346,11 +472,17 @@ export function ProgramDetailPage() {
} }
}; };
const openEditCourse = (course: (typeof proficiencyCourses)[number]) => { const openEditCourse = (course: (typeof displayCourses)[number]) => {
const idNum = Number(course.id); const idNum = Number(course.id);
if (!Number.isFinite(idNum)) return; if (!Number.isFinite(idNum)) return;
setEditingCourseId(idNum); setEditingCourseId(idNum);
setEditName(String(course.name ?? "")); setEditName(String(course.name ?? ""));
setEditDescription(String(course.description ?? ""));
setEditCategory(
course.category === "IELTS" || course.category === "DUOLINGO"
? course.category
: "",
);
setEditThumbnail(String(course.thumbnail ?? "")); setEditThumbnail(String(course.thumbnail ?? ""));
setEditSortOrder(String(course.sort_order ?? 1)); setEditSortOrder(String(course.sort_order ?? 1));
}; };
@ -359,6 +491,8 @@ export function ProgramDetailPage() {
if (savingEdit || uploadingEditThumbnail) return; if (savingEdit || uploadingEditThumbnail) return;
setEditingCourseId(null); setEditingCourseId(null);
setEditName(""); setEditName("");
setEditDescription("");
setEditCategory("");
setEditThumbnail(""); setEditThumbnail("");
setEditSortOrder("1"); setEditSortOrder("1");
}; };
@ -406,31 +540,55 @@ export function ProgramDetailPage() {
const minioThumbnail = await resolveThumbnailToMinioUrl(editThumbnail); const minioThumbnail = await resolveThumbnailToMinioUrl(editThumbnail);
const existing = createdCourses.find((c) => c.id === editingCourseId); const existing = createdCourses.find((c) => c.id === editingCourseId);
const preservedDescription = const preservedDescription =
typeof existing?.description === "string" ? existing.description.trim() || null : null; typeof existing?.description === "string"
const response = await updateExamPrepCatalogCourse(editingCourseId, { ? existing.description.trim() || null
name, : null;
description: preservedDescription,
thumbnail: minioThumbnail || null, if (isProficiency) {
sort_order: sortOrderNum, if (editCategory !== "IELTS" && editCategory !== "DUOLINGO") {
}); toast.error("Please select an exam category");
const row = response.data?.data; return;
setCreatedCourses((prev) => }
prev.map((course) => const response = await updateExamPrepCatalogCourse(editingCourseId, {
course.id === editingCourseId name,
? { description: preservedDescription,
...course, category: editCategory,
name: row?.name ?? name, thumbnail: minioThumbnail || null,
description: row?.description?.trim() || preservedDescription || "", sort_order: sortOrderNum,
thumbnail: row?.thumbnail?.trim() || null, });
sortOrder: Number(row?.sort_order ?? sortOrderNum), const row = response.data?.data;
unitsCount: Number(row?.units_count ?? course.unitsCount ?? 0), setCreatedCourses((prev) =>
modulesCount: Number(row?.modules_count ?? course.modulesCount ?? 0), prev.map((course) =>
lessonsCount: Number(row?.lessons_count ?? course.lessonsCount ?? 0), course.id === editingCourseId
} ? {
: course, ...course,
), category: row?.category ?? editCategory,
); name: row?.name ?? name,
await loadCatalogCourses(); description:
row?.description?.trim() || preservedDescription || "",
thumbnail: row?.thumbnail?.trim() || null,
sortOrder: Number(row?.sort_order ?? sortOrderNum),
unitsCount: Number(row?.units_count ?? course.unitsCount ?? 0),
modulesCount: Number(
row?.modules_count ?? course.modulesCount ?? 0,
),
lessonsCount: Number(
row?.lessons_count ?? course.lessonsCount ?? 0,
),
}
: course,
),
);
} else {
await updateTopLevelCourse(editingCourseId, {
name,
description: editDescription.trim(),
thumbnail: minioThumbnail,
sort_order: sortOrderNum,
});
}
await loadCourses();
toast.success("Course updated"); toast.success("Course updated");
closeEditCourse(); closeEditCourse();
} catch (error: unknown) { } catch (error: unknown) {
@ -445,8 +603,12 @@ export function ProgramDetailPage() {
if (!deletingCourseId) return; if (!deletingCourseId) return;
setDeletingCourse(true); setDeletingCourse(true);
try { try {
await deleteExamPrepCatalogCourse(deletingCourseId); if (isProficiency) {
await loadCatalogCourses(); await deleteExamPrepCatalogCourse(deletingCourseId);
} else {
await deleteTopLevelCourse(deletingCourseId);
}
await loadCourses();
toast.success("Course deleted"); toast.success("Course deleted");
setDeletingCourseId(null); setDeletingCourseId(null);
} catch (error: unknown) { } catch (error: unknown) {
@ -517,6 +679,7 @@ export function ProgramDetailPage() {
open={createOpen} open={createOpen}
onOpenChange={(open) => { onOpenChange={(open) => {
if (!open && (creating || uploadingThumbnail)) return; if (!open && (creating || uploadingThumbnail)) return;
if (!open) clearCreateCourseForm();
setCreateOpen(open); setCreateOpen(open);
}} }}
> >
@ -535,6 +698,91 @@ export function ProgramDetailPage() {
</DialogHeader> </DialogHeader>
<div className="min-h-0 flex-1 space-y-8 overflow-y-auto p-8"> <div className="min-h-0 flex-1 space-y-8 overflow-y-auto p-8">
{isProficiency ? (
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Exam Category
</label>
<select
value={createCategory}
onChange={(e) =>
setCreateCategory(e.target.value as ExamPrepCatalogCategory | "")
}
className="h-12 w-full rounded-[8px] border border-grayScale-400 bg-white px-4 text-[15px] text-grayScale-900 focus:outline-none focus:ring-2 focus:ring-brand-500/20"
disabled={creating || uploadingThumbnail}
>
<option value="">Select IELTS or Duolingo…</option>
<option value="IELTS">IELTS</option>
<option value="DUOLINGO">Duolingo</option>
</select>
</div>
) : null}
{isSkillBased ? (
<>
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Program
</label>
{learningPrograms.length === 0 ? (
<p className="text-sm text-grayScale-500">
No learning programs found. Create a program first
from{" "}
<Link
to="/new-content/learn-english"
className="font-semibold text-brand-500 hover:underline"
>
Learn English
</Link>
.
</p>
) : (
<select
value={createProgramId}
onChange={(e) => setCreateProgramId(e.target.value)}
className="h-12 w-full rounded-[8px] border border-grayScale-400 bg-white px-4 text-[15px] text-grayScale-900 focus:outline-none focus:ring-2 focus:ring-brand-500/20"
disabled={creating}
>
<option value="">Select a program…</option>
{learningPrograms.map((program) => (
<option key={program.id} value={String(program.id)}>
{program.name?.trim() || `Program ${program.id}`}
</option>
))}
</select>
)}
</div>
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Description
</label>
<Textarea
value={createDescription}
onChange={(e) => setCreateDescription(e.target.value)}
placeholder="Short summary of the course"
rows={3}
className="min-h-[88px] resize-y rounded-[8px] border-grayScale-400 px-4 text-[15px]"
disabled={creating || uploadingThumbnail}
/>
</div>
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Sort Order
</label>
<Input
type="number"
min={0}
value={createSortOrder}
onChange={(e) => setCreateSortOrder(e.target.value)}
placeholder="e.g. 1"
className="h-12 border-grayScale-400 rounded-[8px] px-4 placeholder:text-grayScale-400 text-[15px] focus:ring-brand-500/20"
disabled={creating}
/>
</div>
</>
) : null}
<div className="space-y-3"> <div className="space-y-3">
<label className="text-[15px] text-grayScale-800"> <label className="text-[15px] text-grayScale-800">
Name Name
@ -542,7 +790,11 @@ export function ProgramDetailPage() {
<Input <Input
value={createName} value={createName}
onChange={(e) => setCreateName(e.target.value)} onChange={(e) => setCreateName(e.target.value)}
placeholder="e.g. TOEFL, IELTS" placeholder={
isSkillBased
? "e.g. English For Professionals"
: "e.g. TOEFL, IELTS"
}
className="h-12 border-grayScale-400 rounded-[8px] px-4 placeholder:text-grayScale-400 text-[15px] focus:ring-brand-500/20" className="h-12 border-grayScale-400 rounded-[8px] px-4 placeholder:text-grayScale-400 text-[15px] focus:ring-brand-500/20"
disabled={creating} disabled={creating}
/> />
@ -625,7 +877,11 @@ export function ProgramDetailPage() {
</DialogClose> </DialogClose>
<Button <Button
className="h-11 px-8 rounded-[6px] bg-brand-500 text-white font-bold hover:bg-brand-600" className="h-11 px-8 rounded-[6px] bg-brand-500 text-white font-bold hover:bg-brand-600"
disabled={creating || uploadingThumbnail} disabled={
creating ||
uploadingThumbnail ||
(isSkillBased && learningPrograms.length === 0)
}
onClick={() => void handleCreateCourse()} onClick={() => void handleCreateCourse()}
> >
{creating ? "Creating..." : "Create Course"} {creating ? "Creating..." : "Create Course"}
@ -654,33 +910,38 @@ export function ProgramDetailPage() {
{/* Cards Grid */} {/* Cards Grid */}
<div className="mt-10 space-y-6"> <div className="mt-10 space-y-6">
{programType === "proficiency" && !catalogLoading && proficiencyCourses.length > 0 ? ( {!catalogLoading && displayCourses.length > 0 ? (
<ContentListSearchFilterBar <ContentListSearchFilterBar
search={listSearch} search={listSearch}
onSearchChange={setListSearch} onSearchChange={setListSearch}
publishStatusFilter={publishStatusFilter} publishStatusFilter={publishStatusFilter}
onPublishStatusFilterChange={setPublishStatusFilter} onPublishStatusFilterChange={setPublishStatusFilter}
searchPlaceholder="Search courses by name or description…" searchPlaceholder={
searchAriaLabel="Search catalog courses" isSkillBased
? "Search courses by name, description, or program…"
: "Search courses by name or description…"
}
searchAriaLabel={
isSkillBased ? "Search skill-based courses" : "Search catalog courses"
}
/> />
) : null} ) : null}
<div className="flex flex-wrap gap-8"> <div className="flex flex-wrap gap-8">
{programType === "proficiency" && catalogLoading ? ( {catalogLoading ? (
<p className="text-sm text-grayScale-500">Loading catalog courses...</p> <p className="text-sm text-grayScale-500">Loading courses...</p>
) : null} ) : null}
{(programType === "proficiency" {displayCourses.length === 0 && !catalogLoading ? (
? proficiencyCourses
: currentProgram.courses
).length === 0 && !catalogLoading ? (
<div className="w-full rounded-xl border border-dashed border-grayScale-200 bg-grayScale-50/50 px-6 py-14 text-center"> <div className="w-full rounded-xl border border-dashed border-grayScale-200 bg-grayScale-50/50 px-6 py-14 text-center">
<p className="text-sm font-medium text-grayScale-600"> <p className="text-sm font-medium text-grayScale-600">
No catalog courses yet {isSkillBased ? "No skill-based courses yet" : "No catalog courses yet"}
</p> </p>
<p className="mt-1 text-sm text-grayScale-400"> <p className="mt-1 text-sm text-grayScale-400">
Create your first Duolingo/IELTS catalog course to start organizing units, modules, and lessons. {isSkillBased
? "Create your first course under a learning program to start organizing modules and lessons."
: "Create your first Duolingo/IELTS catalog course to start organizing units, modules, and lessons."}
</p> </p>
</div> </div>
) : programType === "proficiency" && filteredProficiencyCourses.length === 0 ? ( ) : filteredCourses.length === 0 ? (
<div className="w-full rounded-xl border border-dashed border-grayScale-200 bg-grayScale-50/50 px-6 py-14 text-center"> <div className="w-full rounded-xl border border-dashed border-grayScale-200 bg-grayScale-50/50 px-6 py-14 text-center">
<p className="text-sm font-medium text-grayScale-600"> <p className="text-sm font-medium text-grayScale-600">
No courses match your search or status filter No courses match your search or status filter
@ -692,16 +953,12 @@ export function ProgramDetailPage() {
) : null} ) : null}
</div> </div>
) : ( ) : (
(programType === "proficiency" filteredCourses.map((course: any) => (
? filteredProficiencyCourses
: currentProgram.courses
).map((course: any) => (
<Card <Card
key={course.id} key={course.id}
className="group relative bg-white w-[500px] rounded-[20px] border border-grayScale-100 p-6 flex flex-col items-start shadow-sm hover:shadow-md transition-shadow" className="group relative bg-white w-[500px] rounded-[20px] border border-grayScale-100 p-6 flex flex-col items-start shadow-sm hover:shadow-md transition-shadow"
> >
{programType === "proficiency" ? ( <div className="absolute right-3 top-3 z-10 flex translate-y-1 gap-1 opacity-0 pointer-events-none transition-all duration-300 ease-out group-hover:translate-y-0 group-hover:opacity-100 group-hover:pointer-events-auto">
<div className="absolute right-3 top-3 z-10 flex translate-y-1 gap-1 opacity-0 pointer-events-none transition-all duration-300 ease-out group-hover:translate-y-0 group-hover:opacity-100 group-hover:pointer-events-auto">
<Button <Button
type="button" type="button"
variant="secondary" variant="secondary"
@ -723,7 +980,6 @@ export function ProgramDetailPage() {
<Trash2 className="h-3.5 w-3.5" /> <Trash2 className="h-3.5 w-3.5" />
</Button> </Button>
</div> </div>
) : null}
{/* Logo */} {/* Logo */}
<div className="h-16 flex items-center"> <div className="h-16 flex items-center">
{course.thumbnail ? ( {course.thumbnail ? (
@ -743,25 +999,33 @@ export function ProgramDetailPage() {
{/* Content */} {/* Content */}
<div className="space-y-4 pt-2 flex-1"> <div className="space-y-4 pt-2 flex-1">
{programType === "proficiency" ? ( <div className="flex flex-wrap gap-2">
<div className="flex flex-wrap gap-2"> <ContentPublishStatusChip
<ContentPublishStatusChip publishStatus={course.publish_status}
publishStatus={course.publish_status} updating={publishStatusUpdatingId === Number(course.id)}
updating={publishStatusUpdatingId === Number(course.id)} contentLabel="course"
contentLabel="course" onToggle={(nextStatus) =>
onToggle={(nextStatus) => void handleCoursePublishStatus(Number(course.id), nextStatus)
void handleCoursePublishStatus(Number(course.id), nextStatus) }
} />
/> <ContentAccessTierChip
<ContentAccessTierChip accessTier={course.access_tier}
accessTier={course.access_tier} updating={accessTierUpdatingId === Number(course.id)}
updating={accessTierUpdatingId === Number(course.id)} contentLabel="course"
contentLabel="course" onToggle={(nextTier) =>
onToggle={(nextTier) => void handleCourseAccessTier(Number(course.id), nextTier)
void handleCourseAccessTier(Number(course.id), nextTier) }
} />
/> </div>
</div> {isSkillBased && course.programName ? (
<p className="text-[12px] font-semibold uppercase tracking-wide text-brand-500">
<SearchHighlight text={course.programName} query={listSearch} />
</p>
) : null}
{isProficiency && course.category ? (
<p className="text-[12px] font-semibold uppercase tracking-wide text-brand-500">
{course.category === "DUOLINGO" ? "Duolingo" : course.category}
</p>
) : null} ) : null}
<h3 className="text-[18px] font-medium text-grayScale-900"> <h3 className="text-[18px] font-medium text-grayScale-900">
<SearchHighlight text={course.name} query={listSearch} /> <SearchHighlight text={course.name} query={listSearch} />
@ -773,12 +1037,14 @@ export function ProgramDetailPage() {
{/* Badges/Stats */} {/* Badges/Stats */}
<div className="flex items-center pt-4 gap-4"> <div className="flex items-center pt-4 gap-4">
<div className="h-10 px-4 rounded-[6px] bg-grayScale-100 border border-grayScale-100 flex items-center gap-2 text-grayScale-700"> {isProficiency ? (
<ClipboardList className="h-3 w-3 text-grayScale-400" /> <div className="h-10 px-4 rounded-[6px] bg-grayScale-100 border border-grayScale-100 flex items-center gap-2 text-grayScale-700">
<span className="text-[12px] "> <ClipboardList className="h-3 w-3 text-grayScale-400" />
{Number(course.units_count ?? 0)} Units <span className="text-[12px] ">
</span> {Number(course.units_count ?? 0)} Units
</div> </span>
</div>
) : null}
<div className="h-10 px-4 rounded-[6px] bg-grayScale-100 border border-grayScale-100 flex items-center gap-2 text-grayScale-700"> <div className="h-10 px-4 rounded-[6px] bg-grayScale-100 border border-grayScale-100 flex items-center gap-2 text-grayScale-700">
<ListChecks className="h-3 w-3 text-grayScale-400" /> <ListChecks className="h-3 w-3 text-grayScale-400" />
<span className="text-[12px] "> <span className="text-[12px] ">
@ -796,9 +1062,15 @@ export function ProgramDetailPage() {
{/* Action Button */} {/* Action Button */}
<Button <Button
className="w-full mt-4 h-10 bg-brand-500 text-white rounded-[6px] font-bold flex items-center justify-center gap-2 group/btn" className="w-full mt-4 h-10 bg-brand-500 text-white rounded-[6px] font-bold flex items-center justify-center gap-2 group/btn"
onClick={() => onClick={() => {
navigate(`/new-content/courses/${programType}/${course.id}`) if (isSkillBased && course.programId) {
} navigate(
`/new-content/learn-english/${course.programId}/courses/${course.id}`,
);
return;
}
navigate(`/new-content/courses/${programType}/${course.id}`);
}}
> >
{course.buttonText} {course.buttonText}
<ChevronRight className="h-5 w-5 transition-transform group-hover/btn:translate-x-1" /> <ChevronRight className="h-5 w-5 transition-transform group-hover/btn:translate-x-1" />
@ -834,6 +1106,41 @@ export function ProgramDetailPage() {
/> />
</div> </div>
{isSkillBased ? (
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Description
</label>
<Textarea
value={editDescription}
onChange={(e) => setEditDescription(e.target.value)}
rows={3}
className="min-h-[88px] resize-y rounded-[8px] border-grayScale-400 px-4 text-[15px]"
disabled={savingEdit || uploadingEditThumbnail}
/>
</div>
) : null}
{isProficiency ? (
<div className="space-y-3">
<label className="text-[15px] text-grayScale-800">
Exam Category
</label>
<select
value={editCategory}
onChange={(e) =>
setEditCategory(e.target.value as ExamPrepCatalogCategory | "")
}
className="h-12 w-full rounded-[8px] border border-grayScale-400 bg-white px-4 text-[15px] text-grayScale-900 focus:outline-none focus:ring-2 focus:ring-brand-500/20"
disabled={savingEdit || uploadingEditThumbnail}
>
<option value="">Select IELTS or Duolingo…</option>
<option value="IELTS">IELTS</option>
<option value="DUOLINGO">Duolingo</option>
</select>
</div>
) : null}
<div className="space-y-3"> <div className="space-y-3">
<label className="text-[15px] text-grayScale-800">Sort Order</label> <label className="text-[15px] text-grayScale-800">Sort Order</label>
<Input <Input

View File

@ -12,8 +12,10 @@ import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages" import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import { parentsFromPractice } from "../../../lib/practiceParents" import { parentsFromPractice } from "../../../lib/practiceParents"
import { import {
hasCatalogCourseDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError, listCatalogCourseContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink" } from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
@ -32,7 +34,6 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -149,20 +150,33 @@ export function CatalogCoursePracticesPanel({
} }
} }
const catalogParent = useMemo( const catalogUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "CATALOG_COURSE", parent_id: catalogCourseId }), () => ({ scope: "catalog_course" as const, catalogCourseId }),
[catalogCourseId], [catalogCourseId],
) )
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return if (!practiceToUnlink) return
const parents = listCatalogCourseContextUnlinkParents(
practiceToUnlink,
catalogCourseId,
)
if (parents.length === 0) {
toast.error(
practiceUnlinkBlockedMessage(practiceToUnlink, catalogUnlinkContext) ??
"This practice is not linked to this catalog course.",
)
return
}
setUnlinking(true) setUnlinking(true)
try { try {
await unlinkPracticeFromParent({ for (const parent of parents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: catalogParent, practiceId: practiceToUnlink.id,
isExamPrep: true, parent,
}) isExamPrep: true,
})
}
toast.success(`Practice removed from ${courseName}`) toast.success(`Practice removed from ${courseName}`)
setPracticeToUnlink(null) setPracticeToUnlink(null)
await load() await load()
@ -253,7 +267,7 @@ export function CatalogCoursePracticesPanel({
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={courseName} locationLabel={courseName}
unlinkContext={{ scope: "catalog_course", catalogCourseId }} unlinkContext={catalogUnlinkContext}
isExamPrep isExamPrep
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -266,7 +280,16 @@ export function CatalogCoursePracticesPanel({
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasCatalogCourseDirectPracticeLink(practice, catalogCourseId)) {
toast.info(
practiceUnlinkBlockedMessage(practice, catalogUnlinkContext) ??
"This practice is not directly linked to this catalog course.",
)
return
}
setPracticeToUnlink(practice)
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -12,8 +12,10 @@ import { unwrapPracticesList } from "../../../lib/parentContextPractice"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages" import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import { parentsFromPractice } from "../../../lib/practiceParents" import { parentsFromPractice } from "../../../lib/practiceParents"
import { import {
hasUnitDirectPracticeLink,
isPracticeParentUnlinkNotLinkedError, isPracticeParentUnlinkNotLinkedError,
mapPracticeParentUnlinkError, listUnitContextUnlinkParents,
practiceUnlinkBlockedMessage,
unlinkPracticeFromParent, unlinkPracticeFromParent,
} from "../../../lib/practiceParentUnlink" } from "../../../lib/practiceParentUnlink"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
@ -32,7 +34,6 @@ import {
} from "../../../lib/contentListFilters" } from "../../../lib/contentListFilters"
import type { import type {
ParentContextPractice, ParentContextPractice,
PracticeParent,
PracticePublishStatus, PracticePublishStatus,
} from "../../../types/course.types" } from "../../../types/course.types"
@ -148,20 +149,30 @@ export function UnitPracticesPanel({
} }
} }
const unitParent = useMemo( const unitUnlinkContext = useMemo(
(): PracticeParent => ({ parent_kind: "UNIT", parent_id: unitId }), () => ({ scope: "unit" as const, unitId }),
[unitId], [unitId],
) )
const confirmUnlinkPractice = async () => { const confirmUnlinkPractice = async () => {
if (!practiceToUnlink) return if (!practiceToUnlink) return
const parents = listUnitContextUnlinkParents(practiceToUnlink, unitId)
if (parents.length === 0) {
toast.error(
practiceUnlinkBlockedMessage(practiceToUnlink, unitUnlinkContext) ??
"This practice is not linked to this unit.",
)
return
}
setUnlinking(true) setUnlinking(true)
try { try {
await unlinkPracticeFromParent({ for (const parent of parents) {
practiceId: practiceToUnlink.id, await unlinkPracticeFromParent({
parent: unitParent, practiceId: practiceToUnlink.id,
isExamPrep: true, parent,
}) isExamPrep: true,
})
}
toast.success(`Practice removed from ${unitName}`) toast.success(`Practice removed from ${unitName}`)
setPracticeToUnlink(null) setPracticeToUnlink(null)
await load() await load()
@ -252,7 +263,7 @@ export function UnitPracticesPanel({
practices={filteredPractices} practices={filteredPractices}
searchQuery={listSearch} searchQuery={listSearch}
locationLabel={unitName} locationLabel={unitName}
unlinkContext={{ scope: "unit", unitId }} unlinkContext={unitUnlinkContext}
isExamPrep isExamPrep
publishStatusUpdatingId={publishStatusUpdatingId} publishStatusUpdatingId={publishStatusUpdatingId}
onReload={load} onReload={load}
@ -265,7 +276,16 @@ export function UnitPracticesPanel({
onSaveAsDraft={(practiceId) => onSaveAsDraft={(practiceId) =>
void handlePracticePublishStatus(practiceId, "DRAFT") void handlePracticePublishStatus(practiceId, "DRAFT")
} }
onUnlink={(practice) => setPracticeToUnlink(practice)} onUnlink={(practice) => {
if (!hasUnitDirectPracticeLink(practice, unitId)) {
toast.info(
practiceUnlinkBlockedMessage(practice, unitUnlinkContext) ??
"This practice is not directly linked to this unit.",
)
return
}
setPracticeToUnlink(practice)
}}
onDelete={(practice) => setPracticeToDelete(practice)} onDelete={(practice) => setPracticeToDelete(practice)}
/> />
)} )}

View File

@ -4,12 +4,13 @@ import { ArrowRight, ChevronDown, ChevronUp, Loader2, Upload } from "lucide-reac
import { Button } from "../../../../components/ui/button"; import { Button } from "../../../../components/ui/button";
import { Card } from "../../../../components/ui/card"; import { Card } from "../../../../components/ui/card";
import { Input } from "../../../../components/ui/input"; import { Input } from "../../../../components/ui/input";
import { Textarea } from "../../../../components/ui/textarea"; import { RichTextEditor } from "../../../../components/ui/rich-text-editor";
import { toast } from "sonner"; import { toast } from "sonner";
import { uploadImageFile } from "../../../../api/files.api"; import { uploadImageFile } from "../../../../api/files.api";
import type { PracticeParent, AuthoringProfile } from "../../../../types/course.types"; import type { PracticeParent, AuthoringProfile } from "../../../../types/course.types";
import { PracticeParentsField } from "./PracticeParentsField"; import { PracticeParentsField } from "./PracticeParentsField";
import { formatPracticeParentsSummary } from "../../../../lib/practiceParents"; import { formatPracticeParentsSummary } from "../../../../lib/practiceParents";
import { hasRichTextContent } from "../../../../lib/richText";
interface ContextStepProps { interface ContextStepProps {
formData: { formData: {
@ -24,8 +25,6 @@ interface ContextStepProps {
setFormData: (data: ContextStepProps["formData"]) => void; setFormData: (data: ContextStepProps["formData"]) => void;
nextStep: () => void; nextStep: () => void;
onCancel: () => void; onCancel: () => void;
/** Lesson-linked practice: no title, story description, or story image on step 1. */
isLessonPractice?: boolean;
lessonTitle?: string | null; lessonTitle?: string | null;
parentSummary?: string | null; parentSummary?: string | null;
/** Learn English LMS — show multi-parent picker. */ /** Learn English LMS — show multi-parent picker. */
@ -49,7 +48,6 @@ export function ContextStep({
setFormData, setFormData,
nextStep, nextStep,
onCancel, onCancel,
isLessonPractice = false,
lessonTitle = null, lessonTitle = null,
parentSummary = null, parentSummary = null,
showParentsEditor = false, showParentsEditor = false,
@ -75,16 +73,15 @@ export function ContextStep({
if (!url) throw new Error("Missing image URL from upload"); if (!url) throw new Error("Missing image URL from upload");
setFormData({ ...formData, storyImageUrl: url }); setFormData({ ...formData, storyImageUrl: url });
toast.success("Story image uploaded"); toast.success("Story image uploaded");
} catch { } catch (e) {
notifyApiError(err, "Could not upload story image"); notifyApiError(e, "Could not upload story image");
} finally { } finally {
setUploadingStory(false); setUploadingStory(false);
} }
}; };
const canContinue = isLessonPractice const canContinue =
? true Boolean(formData.title?.trim()) && hasRichTextContent(formData.description);
: Boolean(formData.title?.trim()) && Boolean(formData.description?.trim());
const parentsSummary = const parentsSummary =
formData.parents && formData.parents.length > 0 formData.parents && formData.parents.length > 0
@ -95,22 +92,20 @@ export function ContextStep({
<Card className="overflow-hidden border-grayScale-300 rounded-2xl bg-white animate-in fade-in duration-500"> <Card className="overflow-hidden border-grayScale-300 rounded-2xl bg-white animate-in fade-in duration-500">
<div className="border-b border-grayScale-50 px-8 pt-8 pb-4"> <div className="border-b border-grayScale-50 px-8 pt-8 pb-4">
<h2 className="text-xl font-bold text-grayScale-900 leading-none"> <h2 className="text-xl font-bold text-grayScale-900 leading-none">
{isLessonPractice ? "Practice options" : "Practice details"} Practice details
</h2> </h2>
<p className="text-grayScale-600 text-base mt-3"> <p className="text-grayScale-600 text-base mt-3">
{isLessonPractice ? ( Story fields and question set options used when saving the practice.
{lessonTitle?.trim() ? (
<> <>
Story fields and question set options used when saving the practice. Linked to{" "} {" "}
Linked to{" "}
<span className="font-medium text-grayScale-800"> <span className="font-medium text-grayScale-800">
{lessonTitle?.trim() || "the selected lesson"} {lessonTitle.trim()}
</span> </span>
. .
</> </>
) : ( ) : null}
<>
Story fields and question set options used when saving the practice.
</>
)}
</p> </p>
</div> </div>
@ -194,91 +189,84 @@ export function ContextStep({
) )
) : null} ) : null}
{!isLessonPractice ? ( <div className="space-y-2">
<> <label className="text-sm font-medium text-grayScale-700">
<div className="space-y-2"> Practice title <span className="text-red-500">*</span>
<label className="text-sm font-medium text-grayScale-700"> </label>
Practice title <span className="text-red-500">*</span> <Input
</label> value={formData.title ?? ""}
<Input onChange={(e) =>
value={formData.title ?? ""} setFormData({ ...formData, title: e.target.value })
onChange={(e) => }
setFormData({ ...formData, title: e.target.value }) placeholder={
} lessonTitle?.trim()
placeholder="e.g. Module conversation drill" ? `e.g. ${lessonTitle.trim()} practice`
className="h-11 rounded-xl border-grayScale-200" : "e.g. Module conversation drill"
/> }
</div> className="h-11 rounded-xl border-grayScale-200"
/>
</div>
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium text-grayScale-700"> <label className="text-sm font-medium text-grayScale-700">
Story description <span className="text-red-500">*</span> Story description <span className="text-red-500">*</span>
</label> </label>
<Textarea <RichTextEditor
value={formData.description ?? ""} value={formData.description ?? ""}
onChange={(e) => onChange={(description) => setFormData({ ...formData, description })}
setFormData({ ...formData, description: e.target.value }) placeholder="Short scenario for learners…"
} maxLength={2000}
placeholder="Short scenario for learners…" />
className="min-h-[120px] rounded-xl border-grayScale-200" </div>
maxLength={2000}
/>
</div>
</>
) : null}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium text-grayScale-700"> <label className="text-sm font-medium text-grayScale-700">
Quick tips <span className="text-grayScale-400">(optional)</span> Quick tips <span className="text-grayScale-400">(optional)</span>
</label> </label>
<Textarea <RichTextEditor
value={formData.tips ?? ""} value={formData.tips ?? ""}
onChange={(e) => onChange={(tips) => setFormData({ ...formData, tips })}
setFormData({ ...formData, tips: e.target.value })
}
placeholder="Optional tips shown to learners before they start" placeholder="Optional tips shown to learners before they start"
className="min-h-[80px] rounded-xl border-grayScale-200"
maxLength={1000} maxLength={1000}
editorClassName="min-h-[80px]"
/> />
</div> </div>
{!isLessonPractice ? ( <div className="space-y-2">
<div className="space-y-2"> <label className="text-sm font-medium text-grayScale-700">
<label className="text-sm font-medium text-grayScale-700"> Story image <span className="text-grayScale-400">(optional)</span>
Story image <span className="text-grayScale-400">(optional)</span> </label>
</label> <Input
<Input value={formData.storyImageUrl ?? ""}
value={formData.storyImageUrl ?? ""} onChange={(e) =>
onChange={(e) => setFormData({ ...formData, storyImageUrl: e.target.value })
setFormData({ ...formData, storyImageUrl: e.target.value }) }
} placeholder="https://… or upload"
placeholder="https://… or upload" className="h-11 rounded-xl border-grayScale-200 font-mono text-[13px]"
className="h-11 rounded-xl border-grayScale-200 font-mono text-[13px]" />
/> <input
<input ref={storyFileRef}
ref={storyFileRef} type="file"
type="file" accept="image/*"
accept="image/*" className="hidden"
className="hidden" onChange={handleStoryImageFile}
onChange={handleStoryImageFile} />
/> <Button
<Button type="button"
type="button" variant="outline"
variant="outline" size="sm"
size="sm" disabled={uploadingStory}
disabled={uploadingStory} onClick={() => storyFileRef.current?.click()}
onClick={() => storyFileRef.current?.click()} className="gap-2"
className="gap-2" >
> {uploadingStory ? (
{uploadingStory ? ( <Loader2 className="h-4 w-4 animate-spin" />
<Loader2 className="h-4 w-4 animate-spin" /> ) : (
) : ( <Upload className="h-4 w-4" />
<Upload className="h-4 w-4" /> )}
)} Upload image
Upload image </Button>
</Button> </div>
</div>
) : null}
<label className="flex cursor-pointer items-center gap-3 text-sm text-grayScale-700"> <label className="flex cursor-pointer items-center gap-3 text-sm text-grayScale-700">
<input <input

View File

@ -5,6 +5,7 @@ import { Button } from "../../../../components/ui/button";
import { Card } from "../../../../components/ui/card"; import { Card } from "../../../../components/ui/card";
import { cn } from "../../../../lib/utils"; import { cn } from "../../../../lib/utils";
import { UnassignedLabel, isUnassignedLabel } from "../../../../lib/displayValue" import { UnassignedLabel, isUnassignedLabel } from "../../../../lib/displayValue"
import { RichTextContent } from "../../../../components/ui/rich-text-content";
export type PracticeReviewQuestion = { export type PracticeReviewQuestion = {
id: string; id: string;
@ -278,9 +279,14 @@ export function PracticeSequentialReview({
<Info className="h-4 w-4 text-brand-500" /> <Info className="h-4 w-4 text-brand-500" />
</div> </div>
<div className="rounded-xl border border-grayScale-200 bg-white px-5 py-4 shadow-sm"> <div className="rounded-xl border border-grayScale-200 bg-white px-5 py-4 shadow-sm">
<p className="text-sm leading-relaxed text-grayScale-600"> {isUnassignedLabel(guidanceText) ? (
{isUnassignedLabel(guidanceText) ? <UnassignedLabel /> : guidanceText} <UnassignedLabel />
</p> ) : (
<RichTextContent
html={guidanceText}
className="text-sm leading-relaxed text-grayScale-600"
/>
)}
</div> </div>
</div> </div>

View File

@ -24,7 +24,6 @@ interface ReviewStepProps {
}; };
selectedPersona?: string | null; selectedPersona?: string | null;
personas?: PersonaCardModel[]; personas?: PersonaCardModel[];
isLessonPractice?: boolean;
lessonTitle?: string | null; lessonTitle?: string | null;
programLabel?: string | null; programLabel?: string | null;
courseLabel?: string | null; courseLabel?: string | null;
@ -47,7 +46,6 @@ export function ReviewStep({
formData, formData,
selectedPersona = null, selectedPersona = null,
personas = [], personas = [],
isLessonPractice = false,
lessonTitle = null, lessonTitle = null,
programLabel = null, programLabel = null,
courseLabel = null, courseLabel = null,
@ -83,24 +81,19 @@ export function ReviewStep({
if (moduleLabel?.trim()) { if (moduleLabel?.trim()) {
items.push({ label: "Module", value: moduleLabel.trim() }); items.push({ label: "Module", value: moduleLabel.trim() });
} }
if (isLessonPractice && lessonTitle?.trim()) { if (lessonTitle?.trim()) {
items.push({ label: "Lesson", value: lessonTitle.trim() }); items.push({ label: "Lesson", value: lessonTitle.trim() });
} }
return items; return items;
}, [programLabel, courseLabel, moduleLabel, isLessonPractice, lessonTitle]); }, [programLabel, courseLabel, moduleLabel, lessonTitle]);
const practiceTitle = isLessonPractice const practiceTitle =
? lessonTitle?.trim() || parentSummary || "Lesson practice" formData.title?.trim() || lessonTitle?.trim() || parentSummary || "Untitled Practice";
: formData.title?.trim() || "Untitled Practice";
const guidanceText = const guidanceText =
formData.tips?.trim() || formData.tips?.trim() || formData.description?.trim() || "unassigned";
(!isLessonPractice ? formData.description?.trim() : "") ||
"unassigned";
const thumbnailUrl = isLessonPractice const thumbnailUrl = formData.storyImageUrl?.trim() || null;
? null
: formData.storyImageUrl?.trim() || null;
return ( return (
<PracticeSequentialReview <PracticeSequentialReview

View File

@ -5,9 +5,11 @@ import { Upload, ArrowRight, Loader2 } from "lucide-react";
import { Button } from "../../../../components/ui/button"; import { Button } from "../../../../components/ui/button";
import { Card } from "../../../../components/ui/card"; import { Card } from "../../../../components/ui/card";
import { Input } from "../../../../components/ui/input"; import { Input } from "../../../../components/ui/input";
import { Textarea } from "../../../../components/ui/textarea"; import { RichTextEditor } from "../../../../components/ui/rich-text-editor";
import { toast } from "sonner"; import { toast } from "sonner";
import { uploadImageFile } from "../../../../api/files.api"; import { uploadImageFile } from "../../../../api/files.api";
import { hasRichTextContent } from "../../../../lib/richText";
interface ScenarioStepProps { interface ScenarioStepProps {
formData: any; formData: any;
setFormData: (data: any) => void; setFormData: (data: any) => void;
@ -35,15 +37,15 @@ export function ScenarioStep({
if (!url) throw new Error("Missing URL"); if (!url) throw new Error("Missing URL");
setFormData({ ...formData, storyImageUrl: url }); setFormData({ ...formData, storyImageUrl: url });
toast.success("Story image uploaded"); toast.success("Story image uploaded");
} catch { } catch (e) {
notifyApiError(err, "Could not upload image"); notifyApiError(e, "Could not upload image");
} finally { } finally {
setUploadingBanner(false); setUploadingBanner(false);
} }
}; };
const canContinue = const canContinue =
Boolean(formData.title?.trim()) && Boolean(formData.description?.trim()); Boolean(formData.title?.trim()) && hasRichTextContent(formData.description);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
@ -174,36 +176,24 @@ export function ScenarioStep({
<label className="text-sm font-medium text-grayScale-700"> <label className="text-sm font-medium text-grayScale-700">
Story description <span className="text-red-500">*</span> Story description <span className="text-red-500">*</span>
</label> </label>
<div className="relative"> <RichTextEditor
<Textarea value={formData.description ?? ""}
placeholder="Describe the scenario…" onChange={(description) => setFormData({ ...formData, description })}
className="min-h-[160px] rounded-xl resize-none p-4 border-grayScale-200 focus:border-brand-500 leading-relaxed placeholder:text-grayScale-500 bg-white" placeholder="Describe the scenario…"
maxLength={1000} maxLength={2000}
value={formData.description} editorClassName="min-h-[160px]"
onChange={(e) => />
setFormData({
...formData,
description: e.target.value,
})
}
/>
<div className="absolute bottom-4 right-4 text-xs font-bold text-grayScale-500">
{formData.description.length} / 1000
</div>
</div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium text-grayScale-700"> <label className="text-sm font-medium text-grayScale-700">
Quick tips <span className="text-grayScale-400">(optional)</span> Quick tips <span className="text-grayScale-400">(optional)</span>
</label> </label>
<Textarea <RichTextEditor
value={formData.tips ?? ""} value={formData.tips ?? ""}
onChange={(e) => onChange={(tips) => setFormData({ ...formData, tips })}
setFormData({ ...formData, tips: e.target.value })
}
placeholder="Learner-facing tips (quick_tips)" placeholder="Learner-facing tips (quick_tips)"
className="min-h-[80px] rounded-xl border-grayScale-200"
maxLength={1000} maxLength={1000}
editorClassName="min-h-[80px]"
/> />
</div> </div>
</Card> </Card>

View File

@ -33,9 +33,9 @@ export function InfoLayout({
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"> <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<Link to="/about" className="inline-flex items-center gap-3"> <Link to="/about" className="inline-flex items-center gap-3">
<span className="inline-flex rounded-xl bg-brand-500 p-2 shadow-sm ring-1 ring-brand-400/40"> <span className="inline-flex rounded-xl bg-brand-500 p-2 shadow-sm ring-1 ring-brand-400/40">
<img src={logoSrc} alt="Yimaru Academy" className="h-8 w-auto" /> <img src={logoSrc} alt="Rezina Academy" className="h-8 w-auto" />
</span> </span>
<p className="text-xl font-semibold text-grayScale-700">Yimaru Academy</p> <p className="text-xl font-semibold text-grayScale-700">Rezina Academy</p>
</Link> </Link>
<nav className="flex flex-wrap items-center text-sm font-medium"> <nav className="flex flex-wrap items-center text-sm font-medium">
{footerLinks.map((item, index) => ( {footerLinks.map((item, index) => (
@ -71,7 +71,7 @@ export function InfoLayout({
<main className="space-y-6 pt-6">{children}</main> <main className="space-y-6 pt-6">{children}</main>
<footer className="mt-8 flex justify-center text-xs text-grayScale-400"> <footer className="mt-8 flex justify-center text-xs text-grayScale-400">
© Yimaru Academy. All rights reserved. © Rezina Academy. All rights reserved.
</footer> </footer>
</div> </div>
</div> </div>

View File

@ -5,7 +5,9 @@ import {
CalendarClock, CalendarClock,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
Eye,
Megaphone, Megaphone,
MoreHorizontal,
Plus, Plus,
RefreshCw, RefreshCw,
XCircle, XCircle,
@ -13,12 +15,24 @@ import {
import { toast } from "sonner" import { toast } from "sonner"
import { import {
cancelScheduledNotification, cancelScheduledNotification,
getScheduledNotificationById,
getScheduledNotifications, getScheduledNotifications,
} from "../../api/notifications.api" } from "../../api/notifications.api"
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel" import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
import { Badge } from "../../components/ui/badge" import { Badge } from "../../components/ui/badge"
import { Button } from "../../components/ui/button" import { Button } from "../../components/ui/button"
import { Card, CardContent } from "../../components/ui/card" import { Card, CardContent } from "../../components/ui/card"
import {
Dialog,
DialogContent,
DialogTitle,
} from "../../components/ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../../components/ui/dropdown-menu"
import { Select } from "../../components/ui/select" import { Select } from "../../components/ui/select"
import { SpinnerIcon } from "../../components/ui/spinner-icon" import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { import {
@ -71,6 +85,8 @@ export function ScheduledNotificationsPage() {
const [statusFilter, setStatusFilter] = useState<"" | ScheduledNotificationStatus>("") const [statusFilter, setStatusFilter] = useState<"" | ScheduledNotificationStatus>("")
const [channelFilter, setChannelFilter] = useState<"" | NotificationChannel>("") const [channelFilter, setChannelFilter] = useState<"" | NotificationChannel>("")
const [cancellingId, setCancellingId] = useState<number | null>(null) const [cancellingId, setCancellingId] = useState<number | null>(null)
const [selectedJob, setSelectedJob] = useState<ScheduledNotification | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const totalPages = useMemo( const totalPages = useMemo(
() => Math.max(1, Math.ceil(totalCount / limit)), () => Math.max(1, Math.ceil(totalCount / limit)),
@ -89,11 +105,11 @@ export function ScheduledNotificationsPage() {
}) })
setRows(res.data.scheduled_notifications) setRows(res.data.scheduled_notifications)
setTotalCount(res.data.total_count) setTotalCount(res.data.total_count)
} catch { } catch (error) {
setError(true) setError(true)
setRows([]) setRows([])
setTotalCount(0) setTotalCount(0)
notifyApiError(err, "Failed to load scheduled notifications") notifyApiError(error, "Failed to load scheduled notifications")
} finally { } finally {
setLoading(false) setLoading(false)
} }
@ -116,13 +132,28 @@ export function ScheduledNotificationsPage() {
description: `Job #${job.id} was cancelled.`, description: `Job #${job.id} was cancelled.`,
}) })
await load() await load()
} catch { } catch (error) {
notifyApiError(err, "Failed to cancel scheduled notification") notifyApiError(error, "Failed to cancel scheduled notification")
} finally { } finally {
setCancellingId(null) setCancellingId(null)
} }
} }
const handleViewDetails = async (job: ScheduledNotification) => {
setSelectedJob(job)
setDetailLoading(true)
try {
const res = await getScheduledNotificationById(job.id)
if (res.data) {
setSelectedJob(res.data)
}
} catch (error) {
notifyApiError(error, "Failed to load scheduled notification details")
} finally {
setDetailLoading(false)
}
}
const targetingSummary = (job: ScheduledNotification) => { const targetingSummary = (job: ScheduledNotification) => {
if (job.target_role) return `Role: ${job.target_role}` if (job.target_role) return `Role: ${job.target_role}`
if (job.target_user_ids?.length) { if (job.target_user_ids?.length) {
@ -288,21 +319,39 @@ export function ScheduledNotificationsPage() {
)} )}
</TableCell> </TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
{(job.status === "pending" || job.status === "processing") && ( <div className="flex justify-end">
<Button <DropdownMenu>
variant="outline" <DropdownMenuTrigger asChild>
size="sm" <Button
disabled={cancellingId === job.id} type="button"
onClick={() => void handleCancel(job)} variant="ghost"
> size="sm"
{cancellingId === job.id ? ( className="h-8 w-8 rounded-[6px] p-0 text-grayScale-400 hover:text-grayScale-700"
<SpinnerIcon className="mr-1 h-3.5 w-3.5" alt="" /> >
) : ( <MoreHorizontal className="h-4 w-4" />
<XCircle className="mr-1 h-3.5 w-3.5" /> </Button>
)} </DropdownMenuTrigger>
Cancel <DropdownMenuContent align="end" className="w-44">
</Button> <DropdownMenuItem onClick={() => void handleViewDetails(job)}>
)} <Eye className="mr-2 h-3.5 w-3.5" />
View details
</DropdownMenuItem>
{(job.status === "pending" || job.status === "processing") && (
<DropdownMenuItem
disabled={cancellingId === job.id}
onClick={() => void handleCancel(job)}
>
{cancellingId === job.id ? (
<SpinnerIcon className="mr-2 h-3.5 w-3.5" alt="" />
) : (
<XCircle className="mr-2 h-3.5 w-3.5" />
)}
Cancel job
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
@ -339,6 +388,66 @@ export function ScheduledNotificationsPage() {
)} )}
</CardContent> </CardContent>
</Card> </Card>
<Dialog
open={selectedJob != null}
onOpenChange={(open) => {
if (!open) setSelectedJob(null)
}}
>
<DialogContent className="max-w-lg gap-0 overflow-hidden rounded-2xl border-0 p-0">
{selectedJob ? (
<>
<div className="border-b border-grayScale-100 px-6 py-5 pr-14">
<DialogTitle className="text-base font-bold text-grayScale-900">
Scheduled job #{selectedJob.id}
</DialogTitle>
<div className="mt-2 flex flex-wrap items-center gap-2">
<Badge variant={scheduledStatusBadgeVariant(selectedJob.status)}>
{selectedJob.status}
</Badge>
<span className="text-xs text-grayScale-500">
{channelLabel(selectedJob.channel)}
</span>
</div>
</div>
<div className="space-y-4 px-6 py-5 text-sm">
{detailLoading ? (
<div className="flex items-center gap-2 text-grayScale-500">
<SpinnerIcon className="h-4 w-4" alt="" />
Loading details…
</div>
) : null}
<DetailRow label="Title" value={selectedJob.title || "—"} />
<DetailRow label="Message" value={selectedJob.message} />
<DetailRow label="Audience" value={targetingSummary(selectedJob)} />
<DetailRow
label="Scheduled"
value={formatScheduledAtLabel(selectedJob.scheduled_at)}
/>
{selectedJob.sent_at ? (
<DetailRow label="Sent" value={formatScheduledAtLabel(selectedJob.sent_at)} />
) : null}
{selectedJob.last_error ? (
<DetailRow label="Last error" value={selectedJob.last_error} />
) : null}
{selectedJob.channel === "email" && selectedJob.email_template_slug ? (
<DetailRow label="Template" value={selectedJob.email_template_slug} />
) : null}
</div>
</>
) : null}
</DialogContent>
</Dialog>
</div>
)
}
function DetailRow({ label, value }: { label: string; value: string }) {
return (
<div className="space-y-1">
<p className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">{label}</p>
<p className="whitespace-pre-wrap break-words text-grayScale-700">{value}</p>
</div> </div>
) )
} }

View File

@ -17,7 +17,7 @@ import {
} from "lucide-react" } from "lucide-react"
import { Link } from "react-router-dom" import { Link } from "react-router-dom"
import { toast } from "sonner" import { toast } from "sonner"
import { getAllPayments } from "../../api/payments.api" import { getPayments } from "../../api/payments.api"
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel" import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
import { ExportCsvButton } from "../../components/export/ExportCsvButton" import { ExportCsvButton } from "../../components/export/ExportCsvButton"
import { ExportTruncationWarning } from "../../components/export/ExportTruncationWarning" import { ExportTruncationWarning } from "../../components/export/ExportTruncationWarning"
@ -48,13 +48,12 @@ import {
formatPaymentStatus, formatPaymentStatus,
computePaymentAggregateStats, computePaymentAggregateStats,
paymentCustomerName, paymentCustomerName,
paymentMatchesDateRange,
paymentStatusBadgeVariant, paymentStatusBadgeVariant,
type PaymentAggregateStats, type PaymentAggregateStats,
} from "../../lib/payments" } from "../../lib/payments"
import { paymentListFiltersToExportQuery } from "../../lib/csvExportFilters"
import { SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans" import { SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans"
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export" import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export"
import { paymentListFiltersToExportQuery } from "../../lib/csvExportFilters"
import type { import type {
Payment, Payment,
PaymentPlanCategory, PaymentPlanCategory,
@ -88,35 +87,16 @@ type PaymentListFilters = {
dateTo: string dateTo: string
} }
function paymentMatchesSearch(payment: Payment, query: string): boolean { function buildPaymentsQuery(filters: PaymentListFilters, searchQuery: string) {
const q = query.trim().toLowerCase() return paymentListFiltersToExportQuery({
if (!q) return true status: filters.status || undefined,
const haystack = [ provider: filters.provider || undefined,
String(payment.id), planCategory: filters.planCategory || undefined,
String(payment.user_id), currency: filters.currency || undefined,
String(payment.plan_id), reference: searchQuery.trim() || undefined,
String(payment.subscription_id), dateFrom: filters.dateFrom || undefined,
payment.session_id, dateTo: filters.dateTo || undefined,
payment.transaction_id, })
payment.nonce,
payment.amount,
payment.currency,
payment.payment_method,
payment.status,
payment.plan_name,
payment.plan_category,
formatPaymentPlanCategory(payment.plan_category),
payment.user_email,
payment.user_first_name,
payment.user_last_name,
paymentCustomerName(payment),
formatPaymentMethod(payment.payment_method),
formatPaymentStatus(payment.status),
formatPaymentAmount(payment),
]
.join(" ")
.toLowerCase()
return haystack.includes(q)
} }
function copyText(value: string, label: string) { function copyText(value: string, label: string) {
@ -140,9 +120,12 @@ export function PaymentsPage() {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState(false) const [error, setError] = useState(false)
const [payments, setPayments] = useState<Payment[]>([]) const [payments, setPayments] = useState<Payment[]>([])
const [totalCount, setTotalCount] = useState(0)
const [paymentStats, setPaymentStats] = useState<PaymentAggregateStats>(EMPTY_PAYMENT_STATS)
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
const [searchQuery, setSearchQuery] = useState("") const [searchQuery, setSearchQuery] = useState("")
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("")
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("") const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("") const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("") const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
@ -182,23 +165,95 @@ export function PaymentsPage() {
{ value: dateTo }, { value: dateTo },
]) ])
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()) const hasActiveFilters = activeFilterCount > 0 || Boolean(debouncedSearchQuery.trim())
useEffect(() => {
const timer = window.setTimeout(() => {
setDebouncedSearchQuery(searchQuery)
}, 300)
return () => window.clearTimeout(timer)
}, [searchQuery])
const fetchPayments = useCallback(async () => { const fetchPayments = useCallback(async () => {
setLoading(true) setLoading(true)
setError(false) setError(false)
try { try {
const all = await getAllPayments({}) const baseQuery = buildPaymentsQuery(listFilters, debouncedSearchQuery)
setPayments(all) const offset = (page - 1) * pageSize
const listPromise = getPayments({
...baseQuery,
limit: pageSize,
offset,
})
const statsPromise = (async () => {
if (!statusFilter) {
const [successRes, pendingRes, revenueRes] = await Promise.all([
getPayments({ ...baseQuery, status: "SUCCESS", limit: 1, offset: 0 }),
getPayments({ ...baseQuery, status: "PENDING", limit: 1, offset: 0 }),
getPayments({
...baseQuery,
status: "SUCCESS",
limit: 100,
offset: 0,
}),
])
setPaymentStats({
successfulCount: successRes.data.total_count,
pendingCount: pendingRes.data.total_count,
totalRevenue: computePaymentAggregateStats(revenueRes.data.payments).totalRevenue,
})
return
}
const filteredRes = await getPayments({
...baseQuery,
limit: 1,
offset: 0,
})
const filteredTotal = filteredRes.data.total_count
let totalRevenue = 0
if (statusFilter === "SUCCESS" && filteredTotal > 0) {
const revenueRes = await getPayments({
...baseQuery,
status: "SUCCESS",
limit: Math.min(100, filteredTotal),
offset: 0,
})
totalRevenue = computePaymentAggregateStats(revenueRes.data.payments).totalRevenue
}
setPaymentStats({
successfulCount: statusFilter === "SUCCESS" ? filteredTotal : 0,
pendingCount: statusFilter === "PENDING" ? filteredTotal : 0,
totalRevenue,
})
})()
const [listRes] = await Promise.all([listPromise, statsPromise])
setPayments(listRes.data.payments)
setTotalCount(listRes.data.total_count)
} catch (e) { } catch (e) {
console.error(e) console.error(e)
setError(true) setError(true)
setPayments([]) setPayments([])
setTotalCount(0)
setPaymentStats(EMPTY_PAYMENT_STATS)
notifyApiError(e, "Failed to load payments") notifyApiError(e, "Failed to load payments")
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, []) }, [
debouncedSearchQuery,
statusFilter,
providerFilter,
planCategoryFilter,
currencyFilter,
dateFrom,
dateTo,
page,
pageSize,
])
useEffect(() => { useEffect(() => {
void fetchPayments() void fetchPayments()
@ -207,7 +262,7 @@ export function PaymentsPage() {
useEffect(() => { useEffect(() => {
setPage(1) setPage(1)
}, [ }, [
searchQuery, debouncedSearchQuery,
statusFilter, statusFilter,
providerFilter, providerFilter,
planCategoryFilter, planCategoryFilter,
@ -217,51 +272,11 @@ export function PaymentsPage() {
pageSize, pageSize,
]) ])
const filteredPayments = useMemo(() => {
return payments.filter((payment) => {
if (statusFilter && payment.status !== statusFilter) return false
if (
providerFilter &&
payment.payment_method?.toUpperCase() !== providerFilter.toUpperCase()
) {
return false
}
if (planCategoryFilter && payment.plan_category !== planCategoryFilter) return false
if (
currencyFilter &&
payment.currency?.toUpperCase() !== currencyFilter.toUpperCase()
) {
return false
}
if (!paymentMatchesDateRange(payment, dateFrom, dateTo)) return false
return paymentMatchesSearch(payment, searchQuery)
})
}, [
payments,
statusFilter,
providerFilter,
planCategoryFilter,
currencyFilter,
dateFrom,
dateTo,
searchQuery,
])
const paymentStats: PaymentAggregateStats = useMemo(
() =>
filteredPayments.length
? computePaymentAggregateStats(filteredPayments)
: EMPTY_PAYMENT_STATS,
[filteredPayments],
)
const totalCount = filteredPayments.length
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)) const pageCount = Math.max(1, Math.ceil(totalCount / pageSize))
const safePage = Math.min(page, pageCount) const safePage = Math.min(page, pageCount)
const paginatedPayments = useMemo( const paginatedPayments = payments
() => filteredPayments.slice((safePage - 1) * pageSize, safePage * pageSize),
[filteredPayments, safePage, pageSize], const { successfulCount, totalRevenue, pendingCount } = paymentStats
)
const toggleStatus = (value: PaymentStatus) => { const toggleStatus = (value: PaymentStatus) => {
setStatusFilter((current) => (current === value ? "" : value)) setStatusFilter((current) => (current === value ? "" : value))
@ -286,8 +301,6 @@ export function PaymentsPage() {
setPage(1) setPage(1)
} }
const { successfulCount, totalRevenue, pendingCount } = paymentStats
const pageStart = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 const pageStart = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
const pageEnd = Math.min(safePage * pageSize, totalCount) const pageEnd = Math.min(safePage * pageSize, totalCount)
const canPrev = safePage > 1 const canPrev = safePage > 1

View File

@ -362,6 +362,7 @@ export function SubscriptionPlansTab() {
open={createOpen} open={createOpen}
onOpenChange={setCreateOpen} onOpenChange={setCreateOpen}
onCreated={handleCreated} onCreated={handleCreated}
existingPlans={plans}
/> />
<EditSubscriptionPlanDialog <EditSubscriptionPlanDialog
@ -371,6 +372,7 @@ export function SubscriptionPlansTab() {
if (!open) setPlanToEdit(null) if (!open) setPlanToEdit(null)
}} }}
onUpdated={handleUpdated} onUpdated={handleUpdated}
existingPlans={plans}
/> />
<DeleteSubscriptionPlanDialog <DeleteSubscriptionPlanDialog

View File

@ -18,6 +18,8 @@ import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { Textarea } from "../../../components/ui/textarea" import { Textarea } from "../../../components/ui/textarea"
import { ToggleSwitch } from "../../../components/ui/toggle-switch" import { ToggleSwitch } from "../../../components/ui/toggle-switch"
import { import {
DUPLICATE_SUBSCRIPTION_PLAN_PERIOD_MESSAGE,
findConflictingSubscriptionPlan,
LIFETIME_DURATION_DEFAULT, LIFETIME_DURATION_DEFAULT,
SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_CURRENCIES,
SUBSCRIPTION_DURATION_UNITS, SUBSCRIPTION_DURATION_UNITS,
@ -39,6 +41,7 @@ export interface CreateSubscriptionPlanDraft {
price: string price: string
currency: string currency: string
is_lifetime: boolean is_lifetime: boolean
is_free: boolean
is_active: boolean is_active: boolean
} }
@ -51,6 +54,7 @@ export const EMPTY_SUBSCRIPTION_PLAN_DRAFT: CreateSubscriptionPlanDraft = {
price: "", price: "",
currency: "ETB", currency: "ETB",
is_lifetime: false, is_lifetime: false,
is_free: false,
is_active: true, is_active: true,
} }
@ -68,7 +72,11 @@ function draftToPayload(draft: CreateSubscriptionPlanDraft): CreateSubscriptionP
if (!name) return null if (!name) return null
if (!description) return null if (!description) return null
if (!Number.isFinite(duration_value) || duration_value < 1) return null if (!Number.isFinite(duration_value) || duration_value < 1) return null
if (!Number.isFinite(price) || price < 0) return null if (draft.is_free) {
if (price !== 0) return null
} else if (!Number.isFinite(price) || price <= 0) {
return null
}
return { return {
name, name,
@ -76,9 +84,10 @@ function draftToPayload(draft: CreateSubscriptionPlanDraft): CreateSubscriptionP
category: draft.category, category: draft.category,
duration_value, duration_value,
duration_unit, duration_unit,
price, price: draft.is_free ? 0 : price,
currency: draft.currency, currency: draft.currency,
is_lifetime: draft.is_lifetime, is_lifetime: draft.is_lifetime,
is_free: draft.is_free,
is_active: draft.is_active, is_active: draft.is_active,
} }
} }
@ -87,12 +96,14 @@ type CreateSubscriptionPlanDialogProps = {
open: boolean open: boolean
onOpenChange: (open: boolean) => void onOpenChange: (open: boolean) => void
onCreated: (plan: SubscriptionPlan) => void onCreated: (plan: SubscriptionPlan) => void
existingPlans: SubscriptionPlan[]
} }
export function CreateSubscriptionPlanDialog({ export function CreateSubscriptionPlanDialog({
open, open,
onOpenChange, onOpenChange,
onCreated, onCreated,
existingPlans,
}: CreateSubscriptionPlanDialogProps) { }: CreateSubscriptionPlanDialogProps) {
const [draft, setDraft] = useState<CreateSubscriptionPlanDraft>(EMPTY_SUBSCRIPTION_PLAN_DRAFT) const [draft, setDraft] = useState<CreateSubscriptionPlanDraft>(EMPTY_SUBSCRIPTION_PLAN_DRAFT)
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
@ -112,6 +123,17 @@ export function CreateSubscriptionPlanDialog({
return return
} }
const conflict = findConflictingSubscriptionPlan(existingPlans, {
category: payload.category,
is_lifetime: payload.is_lifetime,
duration_value: payload.duration_value,
duration_unit: payload.duration_unit,
})
if (conflict) {
toast.error(DUPLICATE_SUBSCRIPTION_PLAN_PERIOD_MESSAGE)
return
}
setSaving(true) setSaving(true)
try { try {
const res = await createSubscriptionPlan(payload) const res = await createSubscriptionPlan(payload)
@ -267,20 +289,42 @@ export function CreateSubscriptionPlanDialog({
</div> </div>
)} )}
<label className="flex cursor-pointer items-center justify-between gap-4 rounded-[8px] border border-grayScale-100 bg-grayScale-50/50 px-4 py-3">
<div>
<p className="text-sm font-medium text-grayScale-800">Free subscription</p>
<p className="text-xs text-grayScale-500">
Learners activate instantly with no Chapa or payment gateway checkout
</p>
</div>
<ToggleSwitch
variant="plain"
checked={draft.is_free}
aria-label="Free subscription"
onCheckedChange={() =>
setDraft((d) => ({
...d,
is_free: !d.is_free,
price: !d.is_free ? "0" : d.price,
}))
}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400"> <label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
Price <span className="text-destructive">*</span> Price {!draft.is_free && <span className="text-destructive">*</span>}
</label> </label>
<Input <Input
type="number" type="number"
min={0} min={draft.is_free ? 0 : 0.01}
step="0.01" step="0.01"
value={draft.price} value={draft.is_free ? "0" : draft.price}
onChange={(e) => setDraft((d) => ({ ...d, price: e.target.value }))} onChange={(e) => setDraft((d) => ({ ...d, price: e.target.value }))}
placeholder="5.00" placeholder="5.00"
className="rounded-[6px]" className="rounded-[6px]"
required required={!draft.is_free}
disabled={draft.is_free}
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">

View File

@ -19,6 +19,8 @@ import { SpinnerIcon } from "../../../components/ui/spinner-icon"
import { Textarea } from "../../../components/ui/textarea" import { Textarea } from "../../../components/ui/textarea"
import { ToggleSwitch } from "../../../components/ui/toggle-switch" import { ToggleSwitch } from "../../../components/ui/toggle-switch"
import { import {
DUPLICATE_SUBSCRIPTION_PLAN_PERIOD_MESSAGE,
findConflictingSubscriptionPlan,
formatPlanCategory, formatPlanCategory,
LIFETIME_DURATION_DEFAULT, LIFETIME_DURATION_DEFAULT,
SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_CURRENCIES,
@ -38,6 +40,7 @@ interface EditDraft {
price: string price: string
currency: string currency: string
is_lifetime: boolean is_lifetime: boolean
is_free: boolean
is_active: boolean is_active: boolean
} }
@ -50,6 +53,7 @@ function planToDraft(plan: SubscriptionPlan): EditDraft {
price: String(plan.price), price: String(plan.price),
currency: plan.currency, currency: plan.currency,
is_lifetime: Boolean(plan.is_lifetime), is_lifetime: Boolean(plan.is_lifetime),
is_free: Boolean(plan.is_free),
is_active: plan.is_active, is_active: plan.is_active,
} }
} }
@ -68,16 +72,21 @@ function draftToPayload(draft: EditDraft): UpdateSubscriptionPlanPayload | null
if (!name) return null if (!name) return null
if (!description) return null if (!description) return null
if (!Number.isFinite(duration_value) || duration_value < 1) return null if (!Number.isFinite(duration_value) || duration_value < 1) return null
if (!Number.isFinite(price) || price < 0) return null if (draft.is_free) {
if (price !== 0) return null
} else if (!Number.isFinite(price) || price <= 0) {
return null
}
return { return {
name, name,
description, description,
duration_value, duration_value,
duration_unit, duration_unit,
price, price: draft.is_free ? 0 : price,
currency: draft.currency, currency: draft.currency,
is_lifetime: draft.is_lifetime, is_lifetime: draft.is_lifetime,
is_free: draft.is_free,
is_active: draft.is_active, is_active: draft.is_active,
} }
} }
@ -94,6 +103,7 @@ type EditSubscriptionPlanDialogProps = {
open: boolean open: boolean
onOpenChange: (open: boolean) => void onOpenChange: (open: boolean) => void
onUpdated: (plan: SubscriptionPlan) => void onUpdated: (plan: SubscriptionPlan) => void
existingPlans: SubscriptionPlan[]
} }
export function EditSubscriptionPlanDialog({ export function EditSubscriptionPlanDialog({
@ -101,6 +111,7 @@ export function EditSubscriptionPlanDialog({
open, open,
onOpenChange, onOpenChange,
onUpdated, onUpdated,
existingPlans,
}: EditSubscriptionPlanDialogProps) { }: EditSubscriptionPlanDialogProps) {
const [draft, setDraft] = useState<EditDraft | null>(null) const [draft, setDraft] = useState<EditDraft | null>(null)
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
@ -126,6 +137,21 @@ export function EditSubscriptionPlanDialog({
return return
} }
const conflict = findConflictingSubscriptionPlan(
existingPlans,
{
category: plan.category,
is_lifetime: payload.is_lifetime,
duration_value: payload.duration_value,
duration_unit: payload.duration_unit,
},
plan.id,
)
if (conflict) {
toast.error(DUPLICATE_SUBSCRIPTION_PLAN_PERIOD_MESSAGE)
return
}
setSaving(true) setSaving(true)
try { try {
const res = await updateSubscriptionPlan(plan.id, payload) const res = await updateSubscriptionPlan(plan.id, payload)
@ -283,19 +309,45 @@ export function EditSubscriptionPlanDialog({
</div> </div>
)} )}
<label className="flex cursor-pointer items-center justify-between gap-4 rounded-[8px] border border-grayScale-100 bg-grayScale-50/50 px-4 py-3">
<div>
<p className="text-sm font-medium text-grayScale-800">Free subscription</p>
<p className="text-xs text-grayScale-500">
Learners activate instantly with no Chapa or payment gateway checkout
</p>
</div>
<ToggleSwitch
variant="plain"
checked={draft.is_free}
aria-label="Free subscription"
onCheckedChange={() =>
setDraft((d) =>
d
? {
...d,
is_free: !d.is_free,
price: !d.is_free ? "0" : d.price,
}
: d,
)
}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400"> <label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
Price <span className="text-destructive">*</span> Price {!draft.is_free && <span className="text-destructive">*</span>}
</label> </label>
<Input <Input
type="number" type="number"
min={0} min={draft.is_free ? 0 : 0.01}
step="0.01" step="0.01"
value={draft.price} value={draft.is_free ? "0" : draft.price}
onChange={(e) => setDraft((d) => d && { ...d, price: e.target.value })} onChange={(e) => setDraft((d) => d && { ...d, price: e.target.value })}
className="rounded-[6px]" className="rounded-[6px]"
required required={!draft.is_free}
disabled={draft.is_free}
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">

View File

@ -62,7 +62,6 @@ import { cn } from "../../../lib/utils"
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../../lib/csv-export" import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../../lib/csv-export"
import { activityLogExportQuery } from "../../../lib/csvExportFilters" import { activityLogExportQuery } from "../../../lib/csvExportFilters"
import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination" import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination"
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types" import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types"
import { ActorCell, ActorLabel } from "./ActorLabel" import { ActorCell, ActorLabel } from "./ActorLabel"
import { ActorHoverCard } from "./ActorHoverCard" import { ActorHoverCard } from "./ActorHoverCard"
@ -96,6 +95,7 @@ export function ActivityLogListPanel({
scrollable = false, scrollable = false,
}: ActivityLogListPanelProps) { }: ActivityLogListPanelProps) {
const [logs, setLogs] = useState<ActivityLog[]>([]) const [logs, setLogs] = useState<ActivityLog[]>([])
const [totalCount, setTotalCount] = useState(0)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
@ -105,6 +105,7 @@ export function ActivityLogListPanel({
const [resourceTypeFilter, setResourceTypeFilter] = useState("") const [resourceTypeFilter, setResourceTypeFilter] = useState("")
const [resourceIdFilter, setResourceIdFilter] = useState("") const [resourceIdFilter, setResourceIdFilter] = useState("")
const [searchQuery, setSearchQuery] = useState("") const [searchQuery, setSearchQuery] = useState("")
const [debouncedSearch, setDebouncedSearch] = useState("")
const [dateAfter, setDateAfter] = useState("") const [dateAfter, setDateAfter] = useState("")
const [dateBefore, setDateBefore] = useState("") const [dateBefore, setDateBefore] = useState("")
@ -123,6 +124,7 @@ export function ActivityLogListPanel({
} }
if (dateAfter) filters.after = toRfc3339StartOfDay(dateAfter) if (dateAfter) filters.after = toRfc3339StartOfDay(dateAfter)
if (dateBefore) filters.before = toRfc3339EndOfDay(dateBefore) if (dateBefore) filters.before = toRfc3339EndOfDay(dateBefore)
if (debouncedSearch) filters.search = debouncedSearch
return filters return filters
}, [ }, [
fixedActorId, fixedActorId,
@ -131,6 +133,7 @@ export function ActivityLogListPanel({
resourceIdFilter, resourceIdFilter,
dateAfter, dateAfter,
dateBefore, dateBefore,
debouncedSearch,
]) ])
const exportParams = useMemo( const exportParams = useMemo(
@ -142,21 +145,32 @@ export function ActivityLogListPanel({
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const all = await fetchAllOffsetPages(async (offset, limit) => { const offset = (page - 1) * pageSize
const data = await getActivityLogs({ ...listFilters, limit, offset }) const data = await getActivityLogs({
return { items: data.logs, total_count: data.total_count } ...listFilters,
limit: pageSize,
offset,
}) })
setLogs(all) setLogs(data.logs)
setTotalCount(data.total_count)
} catch (e) { } catch (e) {
console.error("Failed to fetch activity logs:", e) console.error("Failed to fetch activity logs:", e)
setLogs([]) setLogs([])
setTotalCount(0)
const msg = getApiErrorMessage(e, "Failed to load activity logs") const msg = getApiErrorMessage(e, "Failed to load activity logs")
setError(msg) setError(msg)
notifyApiError(e, "Failed to load activity logs") notifyApiError(e, "Failed to load activity logs")
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, [listFilters]) }, [listFilters, page, pageSize])
useEffect(() => {
const timer = window.setTimeout(() => {
setDebouncedSearch(searchQuery.trim())
}, 300)
return () => window.clearTimeout(timer)
}, [searchQuery])
useEffect(() => { useEffect(() => {
void fetchLogs() void fetchLogs()
@ -164,7 +178,16 @@ export function ActivityLogListPanel({
useEffect(() => { useEffect(() => {
setPage(1) setPage(1)
}, [actionFilter, resourceTypeFilter, resourceIdFilter, dateAfter, dateBefore, fixedActorId, pageSize, searchQuery]) }, [
actionFilter,
resourceTypeFilter,
resourceIdFilter,
dateAfter,
dateBefore,
fixedActorId,
pageSize,
debouncedSearch,
])
const handleViewDetail = async (logId: number) => { const handleViewDetail = async (logId: number) => {
setDialogOpen(true) setDialogOpen(true)
@ -202,36 +225,11 @@ export function ActivityLogListPanel({
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()) const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim())
const filteredLogs = useMemo(() => {
const q = searchQuery.trim().toLowerCase()
if (!q) return logs
return logs.filter((log) => {
const haystack = [
log.message,
log.action,
log.actor_name,
log.actor_email,
log.actor_role,
log.resource_type,
log.resource_id != null ? String(log.resource_id) : "",
JSON.stringify(log.metadata ?? {}),
]
.filter(Boolean)
.join(" ")
.toLowerCase()
return haystack.includes(q)
})
}, [logs, searchQuery])
const totalCount = filteredLogs.length
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)) const pageCount = Math.max(1, Math.ceil(totalCount / pageSize))
const safePage = Math.min(page, pageCount) const safePage = Math.min(page, pageCount)
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
const endEntry = Math.min(safePage * pageSize, totalCount) const endEntry = Math.min(safePage * pageSize, totalCount)
const paginatedLogs = useMemo(() => { const paginatedLogs = logs
const start = (safePage - 1) * pageSize
return filteredLogs.slice(start, start + pageSize)
}, [filteredLogs, safePage, pageSize])
const showActorColumn = fixedActorId == null const showActorColumn = fixedActorId == null
const columnCount = showActorColumn ? 6 : 5 const columnCount = showActorColumn ? 6 : 5
@ -287,7 +285,7 @@ export function ActivityLogListPanel({
<p className="text-2xl font-bold text-grayScale-600"> <p className="text-2xl font-bold text-grayScale-600">
{logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : <UnassignedLabel />} {logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : <UnassignedLabel />}
</p> </p>
<p className="text-xs text-grayScale-400">Latest loaded</p> <p className="text-xs text-grayScale-400">Latest on this page</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4"> <div className="flex items-center gap-4 rounded-xl border bg-white p-4">
@ -295,8 +293,8 @@ export function ActivityLogListPanel({
<FileText className="h-5 w-5" /> <FileText className="h-5 w-5" />
</div> </div>
<div> <div>
<p className="text-2xl font-bold text-grayScale-600">{filteredLogs.length}</p> <p className="text-2xl font-bold text-grayScale-600">{paginatedLogs.length}</p>
<p className="text-xs text-grayScale-400">Rows after search</p> <p className="text-xs text-grayScale-400">Rows on this page</p>
</div> </div>
</div> </div>
</div> </div>

View File

@ -47,6 +47,7 @@ export interface ActivityLogFilters {
resource_id?: number resource_id?: number
after?: string after?: string
before?: string before?: string
search?: string
limit?: number limit?: number
offset?: number offset?: number
} }

View File

@ -126,6 +126,8 @@ export interface ProgramCourseListItem {
module_count?: number module_count?: number
lesson_count?: number lesson_count?: number
practice_count?: number practice_count?: number
/** True when this course has a direct COURSE parent practice link. */
has_practice?: boolean
/** Legacy aggregate field names; prefer module_count, lesson_count, practice_count. */ /** Legacy aggregate field names; prefer module_count, lesson_count, practice_count. */
modules_count?: number modules_count?: number
videos_count?: number videos_count?: number
@ -157,10 +159,13 @@ export interface CreateProgramCourseResponse {
} }
/** Exam prep catalog course row (e.g. IELTS / DET cards) */ /** Exam prep catalog course row (e.g. IELTS / DET cards) */
export type ExamPrepCatalogCategory = "IELTS" | "DUOLINGO"
export interface ExamPrepCatalogCourseItem { export interface ExamPrepCatalogCourseItem {
id: number id: number
name: string name: string
description?: string | null description?: string | null
category?: ExamPrepCatalogCategory | string | null
thumbnail?: string | null thumbnail?: string | null
sort_order?: number sort_order?: number
units_count?: number units_count?: number
@ -175,6 +180,7 @@ export interface ExamPrepCatalogCourseItem {
export interface CreateExamPrepCatalogCourseRequest { export interface CreateExamPrepCatalogCourseRequest {
name: string name: string
description?: string | null description?: string | null
category: ExamPrepCatalogCategory
thumbnail?: string | null thumbnail?: string | null
} }
@ -202,6 +208,7 @@ export interface GetExamPrepCatalogCoursesResponse {
export interface UpdateExamPrepCatalogCourseRequest { export interface UpdateExamPrepCatalogCourseRequest {
name: string name: string
description?: string | null description?: string | null
category?: ExamPrepCatalogCategory
thumbnail?: string | null thumbnail?: string | null
sort_order: number sort_order: number
} }
@ -560,6 +567,8 @@ export interface TopLevelCourseModuleItem {
publish_status?: PracticePublishStatus | string | null publish_status?: PracticePublishStatus | string | null
access_tier?: ContentAccessTier | string | null access_tier?: ContentAccessTier | string | null
created_at: string created_at: string
/** True when this module has a direct MODULE parent practice link. */
has_practice?: boolean
} }
export interface GetTopLevelCourseModulesResponse { export interface GetTopLevelCourseModulesResponse {

View File

@ -12,6 +12,7 @@ export interface SubscriptionPlan {
price: number price: number
currency: string currency: string
is_lifetime: boolean is_lifetime: boolean
is_free: boolean
is_active: boolean is_active: boolean
created_at: string created_at: string
} }
@ -25,6 +26,7 @@ export interface CreateSubscriptionPlanPayload {
price: number price: number
currency: string currency: string
is_lifetime: boolean is_lifetime: boolean
is_free: boolean
is_active: boolean is_active: boolean
} }
@ -36,6 +38,7 @@ export interface UpdateSubscriptionPlanPayload {
price: number price: number
currency: string currency: string
is_lifetime: boolean is_lifetime: boolean
is_free: boolean
is_active: boolean is_active: boolean
} }