Redesign makeup academy admin and align content and analytics workflows
This commit is contained in:
parent
15e7e96fee
commit
2daf20288a
|
|
@ -137,7 +137,9 @@ Backend must set `TEAM_INVITE_BASE_URL` / `TEAM_PASSWORD_RESET_BASE_URL` to this
|
||||||
| Script | Command | Description |
|
| Script | Command | Description |
|
||||||
|--------|---------|-------------|
|
|--------|---------|-------------|
|
||||||
| Dev | `npm run dev` | Vite HMR |
|
| Dev | `npm run dev` | Vite HMR |
|
||||||
| Build | `npm run build` | Production bundle (`vite build`) |
|
| Build | `npm run build` | Type check and create the production bundle |
|
||||||
|
| Type check | `npm run typecheck` | Check application and tooling TypeScript |
|
||||||
|
| Learning tests | `npm run test:learning` | API normalization and pagination regression tests |
|
||||||
| Preview | `npm run preview` | Serve production build locally |
|
| Preview | `npm run preview` | Serve production build locally |
|
||||||
| Lint | `npm run lint` | ESLint |
|
| Lint | `npm run lint` | ESLint |
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,8 @@
|
||||||
<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>Rezina Admin</title>
|
<meta name="description" content="Manage makeup artistry courses, students, and academy operations with Rezina Academy." />
|
||||||
|
<title>Rezina Academy | Makeup Artistry Admin</title>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var key = "rezina-admin-theme";
|
var key = "rezina-admin-theme";
|
||||||
|
|
|
||||||
20
package-lock.json
generated
20
package-lock.json
generated
|
|
@ -11,7 +11,8 @@
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@fontsource/inter": "^5.2.8",
|
"@fontsource/cormorant-garamond": "^5.3.0",
|
||||||
|
"@fontsource/dm-sans": "^5.3.0",
|
||||||
"@radix-ui/react-avatar": "^1.1.11",
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
|
@ -1041,10 +1042,19 @@
|
||||||
"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
|
"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@fontsource/inter": {
|
"node_modules/@fontsource/cormorant-garamond": {
|
||||||
"version": "5.2.8",
|
"version": "5.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.2.8.tgz",
|
"resolved": "https://registry.npmjs.org/@fontsource/cormorant-garamond/-/cormorant-garamond-5.3.0.tgz",
|
||||||
"integrity": "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg==",
|
"integrity": "sha512-weuGsCirGVWBWqpt6YUp0yLThTe4G8YO45noq8wxeJCRvEpq5lFrxNMFSTxcyOyV5k5otzJ8guDzYegdYlcLMQ==",
|
||||||
|
"license": "OFL-1.1",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@fontsource/dm-sans": {
|
||||||
|
"version": "5.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@fontsource/dm-sans/-/dm-sans-5.3.0.tgz",
|
||||||
|
"integrity": "sha512-lYJtMXXO28q1z+yz+z8XKd0s4hXaa9QdkETzkyD760sidCv5heI86weYA0sx0Nc4pAMAQTUuyf4gO44cYKKS9g==",
|
||||||
"license": "OFL-1.1",
|
"license": "OFL-1.1",
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/ayuhito"
|
"url": "https://github.com/sponsors/ayuhito"
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,8 @@
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "npm run typecheck && vite build",
|
||||||
|
"typecheck": "tsc -b",
|
||||||
"test:learning": "node --test scripts/learning-integration.test.mjs",
|
"test:learning": "node --test scripts/learning-integration.test.mjs",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
|
|
@ -14,7 +15,8 @@
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@fontsource/inter": "^5.2.8",
|
"@fontsource/cormorant-garamond": "^5.3.0",
|
||||||
|
"@fontsource/dm-sans": "^5.3.0",
|
||||||
"@radix-ui/react-avatar": "^1.1.11",
|
"@radix-ui/react-avatar": "^1.1.11",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import assert from "node:assert/strict"
|
import assert from "node:assert/strict"
|
||||||
import { test } from "node:test"
|
import { test } from "node:test"
|
||||||
|
import { createRequire } from "node:module"
|
||||||
import { build } from "esbuild"
|
import { build } from "esbuild"
|
||||||
|
|
||||||
async function loadModule(path, http = {}) {
|
async function loadModule(path, http = {}) {
|
||||||
|
|
@ -83,3 +84,122 @@ test("user learning activity preserves the course chapter lesson tree", async ()
|
||||||
assert.equal(activity.learning.completions.courses.length, 1)
|
assert.equal(activity.learning.completions.courses.length, 1)
|
||||||
assert.equal("modules" in chapter, false)
|
assert.equal("modules" in chapter, false)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test("offset pagination follows totals even when the server caps page size", async () => {
|
||||||
|
const { fetchAllOffsetPages } = await loadModule("src/lib/fetchAllOffsetPages.ts")
|
||||||
|
const offsets = []
|
||||||
|
const rows = await fetchAllOffsetPages(async (offset) => {
|
||||||
|
offsets.push(offset)
|
||||||
|
return { items: [offset + 1], total_count: 3 }
|
||||||
|
}, 100)
|
||||||
|
assert.deepEqual(rows, [1, 2, 3])
|
||||||
|
assert.deepEqual(offsets, [0, 1, 2])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("offset pagination stops on empty pages and rejects invalid batch sizes", async () => {
|
||||||
|
const { fetchAllOffsetPages } = await loadModule("src/lib/fetchAllOffsetPages.ts")
|
||||||
|
let calls = 0
|
||||||
|
assert.deepEqual(await fetchAllOffsetPages(async () => {
|
||||||
|
calls++
|
||||||
|
return { items: [], total_count: 100 }
|
||||||
|
}), [])
|
||||||
|
assert.equal(calls, 1)
|
||||||
|
for (const size of [0, -1, 1.5, NaN, Infinity]) {
|
||||||
|
await assert.rejects(fetchAllOffsetPages(async () => {
|
||||||
|
assert.fail("invalid sizes must fail before fetching")
|
||||||
|
}, size), RangeError)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("practice fetching continues without a total and preserves filters", async () => {
|
||||||
|
for (const isExamPrep of [false, true]) {
|
||||||
|
const calls = []
|
||||||
|
const { fetchAllPractices } = await loadModule("src/lib/fetchAllPractices.ts", {
|
||||||
|
get: async (path, { params }) => {
|
||||||
|
calls.push(params)
|
||||||
|
assert.equal(path, "/practices")
|
||||||
|
return { data: { data: { practices: Array.from({ length: params.offset === 0 ? 100 : 1 }, (_, i) => ({ id: params.offset + i + 1 })) } } }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const practices = await fetchAllPractices(true, { isExamPrep })
|
||||||
|
assert.equal(practices.length, 101)
|
||||||
|
assert.deepEqual(calls, [{ limit: 100, offset: 0, unlinked_only: true }, { limit: 100, offset: 100, unlinked_only: true }])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test("list envelopes preserve legacy casing and unknown totals", async () => {
|
||||||
|
const { offsetPageFromListEnvelope } = await loadModule("src/lib/fetchAllOffsetPages.ts")
|
||||||
|
assert.deepEqual(offsetPageFromListEnvelope({ data: { Data: { Practices: [{ id: 1 }], TotalCount: "2" } } }, "practices"), { items: [{ id: 1 }], total_count: 2 })
|
||||||
|
assert.deepEqual(offsetPageFromListEnvelope({ data: { data: { practices: [] } } }, "practices"), { items: [], total_count: undefined })
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test("create response IDs support legacy envelopes and reject invalid identifiers", async () => {
|
||||||
|
const { readCreatedEntityId } = await loadModule("src/lib/apiResponse.ts")
|
||||||
|
for (const body of [{ data: { id: 7 } }, { data: { course: { id: "7" } } }, { data: { data: { id: 7 } } }, { course: { id: 7 } }, { id: 7 }]) {
|
||||||
|
assert.equal(readCreatedEntityId(body, "course"), 7)
|
||||||
|
}
|
||||||
|
for (const body of [null, {}, { data: { id: 0 } }, { data: { id: -1 } }, { id: "invalid" }]) {
|
||||||
|
assert.equal(readCreatedEntityId(body, "course"), null)
|
||||||
|
}
|
||||||
|
assert.equal(readCreatedEntityId({ data: { category: { id: 9 } } }, "category"), 9)
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test("subscription plans retain Education and historical categories", async () => {
|
||||||
|
const { parseSubscriptionPlansList } = await loadModule("src/api/subscription-plans.api.ts")
|
||||||
|
const categories = ["EDUCATION", "LEARN_ENGLISH", "IELTS", "DUOLINGO"]
|
||||||
|
const plans = parseSubscriptionPlansList({ data: categories.map((category, i) => ({ id: i + 1, category })) })
|
||||||
|
assert.deepEqual(plans.map((plan) => plan.category), categories)
|
||||||
|
assert.deepEqual(parseSubscriptionPlansList({ data: [{ id: 1, category: "unsupported" }] }), [])
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test("extracted hooks share the same theme and revenue contexts as their components", async () => {
|
||||||
|
const result = await build({
|
||||||
|
stdin: {
|
||||||
|
contents: `
|
||||||
|
import { createElement } from "react"
|
||||||
|
import { renderToStaticMarkup } from "react-dom/server"
|
||||||
|
import { ThemeProvider } from "./src/contexts/ThemeContext"
|
||||||
|
import { useTheme } from "./src/contexts/ThemeContext.shared"
|
||||||
|
import { SensitiveValue } from "./src/components/ui/sensitive-value"
|
||||||
|
import { SensitiveRevealContext } from "./src/components/ui/sensitive-value.shared"
|
||||||
|
function ThemeProbe() { return createElement("span", null, useTheme().theme) }
|
||||||
|
export function renderTheme() {
|
||||||
|
return renderToStaticMarkup(createElement(ThemeProvider, null, createElement(ThemeProbe)))
|
||||||
|
}
|
||||||
|
export function renderRevenue() {
|
||||||
|
return renderToStaticMarkup(createElement(SensitiveRevealContext.Provider, { value: { revealed: true, toggle() {} } }, createElement(SensitiveValue, { showToggle: false }, "42")))
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
resolveDir: process.cwd(),
|
||||||
|
loader: "ts",
|
||||||
|
},
|
||||||
|
bundle: true, write: false, platform: "node", format: "cjs", tsconfig: "tsconfig.app.json",
|
||||||
|
})
|
||||||
|
const module = { exports: {} }
|
||||||
|
new Function("require", "module", "exports", result.outputFiles[0].text)(createRequire(import.meta.url), module, module.exports)
|
||||||
|
assert.equal(module.exports.renderTheme(), "<span>light</span>")
|
||||||
|
assert.match(module.exports.renderRevenue(), /aria-hidden="false"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test("makeup profiles preserve missing, custom, and historical data without inventing preferences", async () => {
|
||||||
|
const profile = await loadModule("src/lib/userProfileFieldDisplay.ts")
|
||||||
|
assert.equal(profile.displayUserLearningGoal("PERSONAL_MAKEUP"), "Develop personal makeup skills")
|
||||||
|
assert.equal(profile.displayUserOccupation("BEAUTY_STUDENT"), "Beauty and makeup student")
|
||||||
|
assert.equal(profile.displayUserLanguageChallenge("BLENDING"), "Blending and application")
|
||||||
|
assert.equal(profile.displayUserLanguageGoal("MAKEUP_FOUNDATIONS"), "Master makeup foundations")
|
||||||
|
assert.equal(profile.displayUserLearningGoal(""), "Not provided")
|
||||||
|
assert.equal(profile.displayUserLanguageChallenge("unknown"), "Not provided")
|
||||||
|
assert.equal(profile.displayUserLearningGoal("Custom artistry goal"), "Custom artistry goal")
|
||||||
|
assert.ok(profile.PROFILE_FILTER_LEARNING_GOALS.every(option => !["EVERYDAY_CONVERSATION", "EXAM_PREP"].includes(option.code)))
|
||||||
|
assert.deepEqual(profile.mergeAnalyticsRowsByDisplayLabel([{label:"",count:3},{label:"PERSONAL_MAKEUP",count:2}], profile.displayUserLearningGoal), [{label:"Not provided",count:3},{label:"Develop personal makeup skills",count:2}])
|
||||||
|
})
|
||||||
|
|
||||||
|
test("new makeup subscriptions default to the supported backend category", async () => {
|
||||||
|
const form = await loadModule("src/pages/settings/components/CreateSubscriptionPlanDialog.shared.ts")
|
||||||
|
assert.equal(form.EMPTY_SUBSCRIPTION_PLAN_DRAFT.category, "EDUCATION")
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { Toaster } from "sonner"
|
import { Toaster } from "sonner"
|
||||||
import { AppRoutes } from "./app/AppRoutes"
|
import { AppRoutes } from "./app/AppRoutes"
|
||||||
import { useTheme } from "./contexts/ThemeContext"
|
import { useTheme } from "./contexts/ThemeContext.shared"
|
||||||
|
|
||||||
import { clearTeamSession } from "./lib/teamAuthStorage"
|
import { clearTeamSession } from "./lib/teamAuthStorage"
|
||||||
|
|
||||||
const SESSION_KEY = "rezina_session_active"
|
const SESSION_KEY = "rezina_session_active"
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import http from "./http";
|
|
||||||
import type {
|
import type {
|
||||||
DashboardData,
|
DashboardData,
|
||||||
DashboardFilters,
|
DashboardFilters,
|
||||||
|
|
@ -6,6 +5,7 @@ import type {
|
||||||
DateCount,
|
DateCount,
|
||||||
LabelCount,
|
LabelCount,
|
||||||
} from "../types/analytics.types";
|
} from "../types/analytics.types";
|
||||||
|
import http from "./http";
|
||||||
|
|
||||||
function buildDashboardQueryParams(filters?: DashboardFilters): Record<string, string | number> {
|
function buildDashboardQueryParams(filters?: DashboardFilters): Record<string, string | number> {
|
||||||
const params: Record<string, string | number> = {};
|
const params: Record<string, string | number> = {};
|
||||||
|
|
@ -173,7 +173,7 @@ function normalizeDashboardResponse(body: unknown): DashboardData {
|
||||||
const usersRaw = pickField(root, "users", "Users");
|
const usersRaw = pickField(root, "users", "Users");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...(root as DashboardData),
|
...(root as unknown as DashboardData),
|
||||||
users: normalizeDashboardUsers(usersRaw, root),
|
users: normalizeDashboardUsers(usersRaw, root),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,141 +1,140 @@
|
||||||
import http from "./http"
|
|
||||||
import type {
|
import type {
|
||||||
GetCourseCategoriesResponse,
|
AccessTierOnlyRequest,
|
||||||
GetCoursesResponse,
|
|
||||||
CreateCourseRequest,
|
|
||||||
UpdateCourseRequest,
|
|
||||||
GetSubCoursesResponse,
|
|
||||||
CreateSubCourseRequest,
|
|
||||||
UpdateSubCourseRequest,
|
|
||||||
UpdateSubCourseStatusRequest,
|
|
||||||
GetSubCourseVideosResponse,
|
|
||||||
CreateSubCourseVideoRequest,
|
|
||||||
UpdateSubCourseVideoRequest,
|
|
||||||
GetPracticesResponse,
|
|
||||||
CreatePracticeRequest,
|
|
||||||
UpdatePracticeRequest,
|
|
||||||
UpdatePracticeStatusRequest,
|
|
||||||
CreatePracticeQuestionRequest,
|
|
||||||
UpdatePracticeQuestionRequest,
|
|
||||||
GetProgramsResponse,
|
|
||||||
GetLevelsResponse,
|
|
||||||
GetModulesResponse,
|
|
||||||
UpdateProgramStatusRequest,
|
|
||||||
CreateProgramRequest,
|
|
||||||
UpdateProgramRequest,
|
|
||||||
CreateLevelRequest,
|
|
||||||
UpdateLevelRequest,
|
|
||||||
UpdateLevelStatusRequest,
|
|
||||||
CreateModuleRequest,
|
|
||||||
UpdateModuleRequest,
|
|
||||||
UpdateModuleStatusRequest,
|
|
||||||
GetQuestionSetsResponse,
|
|
||||||
GetQuestionSetsParams,
|
|
||||||
ExamPrepAssessmentParent,
|
|
||||||
ExamPrepAssessmentLinkRequest,
|
|
||||||
GetQuestionSetDetailResponse,
|
|
||||||
GetQuestionSetQuestionsResponse,
|
|
||||||
GetPracticeQuestionsByPracticeResponse,
|
|
||||||
CreateQuestionSetRequest,
|
|
||||||
CreateQuestionSetResponse,
|
|
||||||
AddQuestionToSetRequest,
|
AddQuestionToSetRequest,
|
||||||
CreateQuestionRequest,
|
|
||||||
CreateQuestionResponse,
|
|
||||||
GetQuestionDetailResponse,
|
|
||||||
GetQuestionsParams,
|
|
||||||
GetQuestionsResponse,
|
|
||||||
CreateVimeoVideoRequest,
|
|
||||||
CreateCourseCategoryRequest,
|
|
||||||
GetCategorySubCategoriesResponse,
|
|
||||||
GetSubCategoryCoursesResponse,
|
|
||||||
GetSubCoursePrerequisitesResponse,
|
|
||||||
AddSubCoursePrerequisiteRequest,
|
AddSubCoursePrerequisiteRequest,
|
||||||
GetLearningPathResponse,
|
CreateCourseCategoryRequest,
|
||||||
GetHumanLanguageLessonsResponse,
|
CreateCourseRequest,
|
||||||
GetHumanLanguageHierarchyResponse,
|
|
||||||
GetCourseHierarchyResponse,
|
|
||||||
CreateHumanLanguageLessonRequest,
|
|
||||||
GetSubModuleLessonsResponse,
|
|
||||||
GetSubModuleLessonDetailResponse,
|
|
||||||
UpdateSubModuleLessonRequest,
|
|
||||||
UpdateSubModuleLessonResponse,
|
|
||||||
GetCourseLevelsForCourseResponse,
|
|
||||||
GetSubModulesByModuleResponse,
|
|
||||||
SubCourse,
|
|
||||||
GetSubCourseEntryAssessmentResponse,
|
|
||||||
ReorderItem,
|
|
||||||
ReorderOrderedIdsRequest,
|
|
||||||
GetVimeoSampleResponse,
|
|
||||||
GetVimeoVideoResponse,
|
|
||||||
VimeoSampleVideo,
|
|
||||||
CreateCourseVideoRequest,
|
CreateCourseVideoRequest,
|
||||||
GetLearningProgramsResponse,
|
|
||||||
UpdateLearningProgramRequest,
|
|
||||||
CreateLearningProgramRequest,
|
|
||||||
CreateLearningProgramResponse,
|
|
||||||
GetProgramCoursesResponse,
|
|
||||||
GetTopLevelCourseModulesResponse,
|
|
||||||
UpdateTopLevelCourseRequest,
|
|
||||||
UpdateTopLevelCourseModuleRequest,
|
|
||||||
CreateTopLevelCourseModuleRequest,
|
|
||||||
CreateTopLevelCourseModuleResponse,
|
|
||||||
CreateProgramCourseRequest,
|
|
||||||
CreateProgramCourseResponse,
|
|
||||||
CreateExamPrepCatalogCourseRequest,
|
|
||||||
CreateExamPrepCatalogCourseResponse,
|
|
||||||
GetExamPrepCatalogCoursesResponse,
|
|
||||||
UpdateExamPrepCatalogCourseRequest,
|
|
||||||
UpdateExamPrepCatalogCourseResponse,
|
|
||||||
CreateExamPrepCatalogUnitRequest,
|
|
||||||
CreateExamPrepCatalogUnitResponse,
|
|
||||||
UpdateExamPrepCatalogUnitRequest,
|
|
||||||
UpdateExamPrepCatalogUnitResponse,
|
|
||||||
GetExamPrepCatalogUnitsResponse,
|
|
||||||
CreateExamPrepUnitModuleRequest,
|
|
||||||
CreateExamPrepUnitModuleResponse,
|
|
||||||
UpdateExamPrepUnitModuleRequest,
|
|
||||||
UpdateExamPrepUnitModuleResponse,
|
|
||||||
GetExamPrepUnitModulesResponse,
|
|
||||||
CreateExamPrepModuleLessonRequest,
|
|
||||||
CreateExamPrepModuleLessonResponse,
|
|
||||||
UpdateExamPrepModuleLessonRequest,
|
|
||||||
UpdateExamPrepModuleLessonResponse,
|
|
||||||
PublishExamPrepModuleLessonRequest,
|
|
||||||
CreateExamPrepLessonPracticeRequest,
|
|
||||||
CreateExamPrepLessonPracticeResponse,
|
|
||||||
CreateExamPrepCatalogCoursePracticeRequest,
|
CreateExamPrepCatalogCoursePracticeRequest,
|
||||||
CreateExamPrepCatalogCoursePracticeResponse,
|
CreateExamPrepCatalogCoursePracticeResponse,
|
||||||
CreateExamPrepUnitPracticeRequest,
|
CreateExamPrepCatalogCourseRequest,
|
||||||
CreateExamPrepUnitPracticeResponse,
|
CreateExamPrepCatalogCourseResponse,
|
||||||
|
CreateExamPrepCatalogUnitRequest,
|
||||||
|
CreateExamPrepCatalogUnitResponse,
|
||||||
|
CreateExamPrepLessonPracticeRequest,
|
||||||
|
CreateExamPrepLessonPracticeResponse,
|
||||||
|
CreateExamPrepModuleLessonRequest,
|
||||||
|
CreateExamPrepModuleLessonResponse,
|
||||||
CreateExamPrepPracticeRequest,
|
CreateExamPrepPracticeRequest,
|
||||||
CreateExamPrepPracticeResponse,
|
CreateExamPrepPracticeResponse,
|
||||||
GetExamPrepUnitPracticesResponse,
|
CreateExamPrepUnitModuleRequest,
|
||||||
GetExamPrepPracticesListResponse,
|
CreateExamPrepUnitModuleResponse,
|
||||||
|
CreateExamPrepUnitPracticeRequest,
|
||||||
|
CreateExamPrepUnitPracticeResponse,
|
||||||
|
CreateHumanLanguageLessonRequest,
|
||||||
|
CreateLearningProgramRequest,
|
||||||
|
CreateLearningProgramResponse,
|
||||||
|
CreateLevelRequest,
|
||||||
|
CreateModuleRequest,
|
||||||
|
CreateParentLinkedPracticeRequest,
|
||||||
|
CreateParentLinkedPracticeResponse,
|
||||||
|
CreatePracticeQuestionRequest,
|
||||||
|
CreatePracticeRequest,
|
||||||
|
CreateProgramCourseRequest,
|
||||||
|
CreateProgramCourseResponse,
|
||||||
|
CreateProgramRequest,
|
||||||
|
CreateQuestionRequest,
|
||||||
|
CreateQuestionResponse,
|
||||||
|
CreateQuestionSetRequest,
|
||||||
|
CreateQuestionSetResponse,
|
||||||
|
CreateSubCourseRequest,
|
||||||
|
CreateSubCourseVideoRequest,
|
||||||
|
CreateTopLevelCourseModuleRequest,
|
||||||
|
CreateTopLevelCourseModuleResponse,
|
||||||
|
CreateTopLevelModuleLessonRequest,
|
||||||
|
CreateTopLevelModuleLessonResponse,
|
||||||
|
CreateVimeoVideoRequest,
|
||||||
|
ExamPrepAssessmentLinkRequest,
|
||||||
|
ExamPrepAssessmentParent,
|
||||||
|
GetCategorySubCategoriesResponse,
|
||||||
|
GetCourseCategoriesResponse,
|
||||||
|
GetCourseHierarchyResponse,
|
||||||
|
GetCourseLevelsForCourseResponse,
|
||||||
|
GetCoursesResponse,
|
||||||
GetExamPrepCatalogCoursePracticesResponse,
|
GetExamPrepCatalogCoursePracticesResponse,
|
||||||
|
GetExamPrepCatalogCoursesResponse,
|
||||||
|
GetExamPrepCatalogUnitsResponse,
|
||||||
GetExamPrepLessonPracticesResponse,
|
GetExamPrepLessonPracticesResponse,
|
||||||
GetExamPrepModuleLessonsResponse,
|
GetExamPrepModuleLessonsResponse,
|
||||||
GetTopLevelModuleLessonsResponse,
|
GetExamPrepPracticesListResponse,
|
||||||
|
GetExamPrepUnitModulesResponse,
|
||||||
|
GetExamPrepUnitPracticesResponse,
|
||||||
|
GetHumanLanguageHierarchyResponse,
|
||||||
|
GetHumanLanguageLessonsResponse,
|
||||||
|
GetLearningPathResponse,
|
||||||
|
GetLearningProgramsResponse,
|
||||||
|
GetLevelsResponse,
|
||||||
|
GetModulesResponse,
|
||||||
|
GetPracticeFullResponse,
|
||||||
|
GetPracticeQuestionsByPracticeResponse,
|
||||||
GetPracticesByParentContextResponse,
|
GetPracticesByParentContextResponse,
|
||||||
GetPracticesListParams,
|
GetPracticesListParams,
|
||||||
GetPracticesListResponse,
|
GetPracticesListResponse,
|
||||||
CreateParentLinkedPracticeRequest,
|
GetPracticesResponse,
|
||||||
CreateParentLinkedPracticeResponse,
|
GetProgramCoursesResponse,
|
||||||
UpdateParentLinkedPracticeRequest,
|
GetProgramsResponse,
|
||||||
GetPracticeFullResponse,
|
GetQuestionDetailResponse,
|
||||||
UpdatePracticeFullRequest,
|
GetQuestionSetDetailResponse,
|
||||||
UpdatePracticeFullResponse,
|
GetQuestionSetQuestionsResponse,
|
||||||
UpdateParentLinkedPracticeResponse,
|
GetQuestionSetsParams,
|
||||||
UpdatePracticeParentsRequest,
|
GetQuestionSetsResponse,
|
||||||
UpdatePracticeParentsResponse,
|
GetQuestionsParams,
|
||||||
|
GetQuestionsResponse,
|
||||||
|
GetSubCategoryCoursesResponse,
|
||||||
|
GetSubCourseEntryAssessmentResponse,
|
||||||
|
GetSubCourseVideosResponse,
|
||||||
|
GetSubCoursesResponse,
|
||||||
|
GetSubModuleLessonDetailResponse,
|
||||||
|
GetSubModuleLessonsResponse,
|
||||||
|
GetSubModulesByModuleResponse,
|
||||||
|
GetTopLevelCourseModulesResponse,
|
||||||
|
GetTopLevelModuleLessonsResponse,
|
||||||
|
GetVimeoSampleResponse,
|
||||||
|
GetVimeoVideoResponse,
|
||||||
PracticeParent,
|
PracticeParent,
|
||||||
|
PublishExamPrepModuleLessonRequest,
|
||||||
PublishParentLinkedPracticeRequest,
|
PublishParentLinkedPracticeRequest,
|
||||||
PublishStatusOnlyRequest,
|
PublishStatusOnlyRequest,
|
||||||
AccessTierOnlyRequest,
|
|
||||||
UpdateTopLevelModuleLessonRequest,
|
|
||||||
PublishTopLevelModuleLessonRequest,
|
PublishTopLevelModuleLessonRequest,
|
||||||
CreateTopLevelModuleLessonRequest,
|
ReorderItem,
|
||||||
CreateTopLevelModuleLessonResponse,
|
ReorderOrderedIdsRequest,
|
||||||
|
SubCourse,
|
||||||
|
UpdateCourseRequest,
|
||||||
|
UpdateExamPrepCatalogCourseRequest,
|
||||||
|
UpdateExamPrepCatalogCourseResponse,
|
||||||
|
UpdateExamPrepCatalogUnitRequest,
|
||||||
|
UpdateExamPrepCatalogUnitResponse,
|
||||||
|
UpdateExamPrepModuleLessonRequest,
|
||||||
|
UpdateExamPrepModuleLessonResponse,
|
||||||
|
UpdateExamPrepUnitModuleRequest,
|
||||||
|
UpdateExamPrepUnitModuleResponse,
|
||||||
|
UpdateLearningProgramRequest,
|
||||||
|
UpdateLevelRequest,
|
||||||
|
UpdateLevelStatusRequest,
|
||||||
|
UpdateModuleRequest,
|
||||||
|
UpdateModuleStatusRequest,
|
||||||
|
UpdateParentLinkedPracticeRequest,
|
||||||
|
UpdateParentLinkedPracticeResponse,
|
||||||
|
UpdatePracticeFullRequest,
|
||||||
|
UpdatePracticeFullResponse,
|
||||||
|
UpdatePracticeParentsRequest,
|
||||||
|
UpdatePracticeParentsResponse,
|
||||||
|
UpdatePracticeQuestionRequest,
|
||||||
|
UpdatePracticeRequest,
|
||||||
|
UpdatePracticeStatusRequest,
|
||||||
|
UpdateProgramRequest,
|
||||||
|
UpdateProgramStatusRequest,
|
||||||
|
UpdateSubCourseRequest,
|
||||||
|
UpdateSubCourseStatusRequest,
|
||||||
|
UpdateSubCourseVideoRequest,
|
||||||
|
UpdateSubModuleLessonRequest,
|
||||||
|
UpdateSubModuleLessonResponse,
|
||||||
|
UpdateTopLevelCourseModuleRequest,
|
||||||
|
UpdateTopLevelCourseRequest,
|
||||||
|
UpdateTopLevelModuleLessonRequest,
|
||||||
|
VimeoSampleVideo
|
||||||
} from "../types/course.types"
|
} from "../types/course.types"
|
||||||
|
import http from "./http"
|
||||||
|
|
||||||
type UnifiedHierarchyRow = {
|
type UnifiedHierarchyRow = {
|
||||||
category_id: number
|
category_id: number
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,11 @@
|
||||||
import http from "./http"
|
import { normalizeMultipleChoiceValue } from "../lib/multipleChoiceSlotValue"
|
||||||
|
import type {
|
||||||
|
CreateQuestionRequest,
|
||||||
|
CreateQuestionSetRequest,
|
||||||
|
QuestionOption,
|
||||||
|
QuestionSetDetail,
|
||||||
|
} from "../types/course.types"
|
||||||
|
import type { DynamicQuestionPayload } from "../types/questionTypeDefinition.types"
|
||||||
import {
|
import {
|
||||||
addQuestionToSet,
|
addQuestionToSet,
|
||||||
createQuestion,
|
createQuestion,
|
||||||
|
|
@ -10,15 +17,8 @@ import {
|
||||||
removeQuestionFromSet,
|
removeQuestionFromSet,
|
||||||
updateQuestionSet,
|
updateQuestionSet,
|
||||||
} from "./courses.api"
|
} from "./courses.api"
|
||||||
|
import http from "./http"
|
||||||
import { unwrapApiPayload } from "./questionTypeDefinitions.api"
|
import { unwrapApiPayload } from "./questionTypeDefinitions.api"
|
||||||
import { normalizeMultipleChoiceValue } from "../lib/multipleChoiceSlotValue"
|
|
||||||
import type {
|
|
||||||
CreateQuestionRequest,
|
|
||||||
CreateQuestionSetRequest,
|
|
||||||
QuestionOption,
|
|
||||||
QuestionSetDetail,
|
|
||||||
} from "../types/course.types"
|
|
||||||
import type { DynamicQuestionPayload } from "../types/questionTypeDefinition.types"
|
|
||||||
|
|
||||||
export type CefrLevel = "A1" | "A2" | "B1" | "B2" | "C1" | "C2"
|
export type CefrLevel = "A1" | "A2" | "B1" | "B2" | "C1" | "C2"
|
||||||
|
|
||||||
|
|
@ -316,7 +316,7 @@ export async function listPlacementQuestions(setId: number): Promise<PlacementQu
|
||||||
return rows.map((raw, index) => {
|
return rows.map((raw, index) => {
|
||||||
const detail = normalizePlacementQuestionDetail(raw)
|
const detail = normalizePlacementQuestionDetail(raw)
|
||||||
const record = isRecord(raw) ? raw : {}
|
const record = isRecord(raw) ? raw : {}
|
||||||
const questionId = detail?.id ?? Number(record.question_id ?? record.id) ?? index
|
const questionId = detail?.id ?? (Number(record.question_id ?? record.id) || index)
|
||||||
return {
|
return {
|
||||||
setItemId: Number(record.id) || index,
|
setItemId: Number(record.id) || index,
|
||||||
questionId,
|
questionId,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import http from "./http"
|
import { isScheduledNotification, parseBulkResponseData } from "../lib/notificationBulk"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||||
import type {
|
import type {
|
||||||
BulkInAppRequest,
|
BulkInAppRequest,
|
||||||
BulkSendResult,
|
BulkSendResult,
|
||||||
|
|
@ -13,8 +14,7 @@ import type {
|
||||||
UnreadCountResponse,
|
UnreadCountResponse,
|
||||||
} from "../types/notification.types"
|
} from "../types/notification.types"
|
||||||
import { isNumericNotificationId } from "../types/notification.types"
|
import { isNumericNotificationId } from "../types/notification.types"
|
||||||
import { isScheduledNotification, parseBulkResponseData } from "../lib/notificationBulk"
|
import http from "./http"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
|
@ -375,6 +375,7 @@ function normalizeScheduledNotification(raw: unknown): ScheduledNotification | n
|
||||||
if (!isRecord(raw)) return null
|
if (!isRecord(raw)) return null
|
||||||
const id = Number(raw.id)
|
const id = Number(raw.id)
|
||||||
if (!id) return null
|
if (!id) return null
|
||||||
|
const target = isRecord(raw.target_raw) ? raw.target_raw : undefined
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
channel: String(raw.channel ?? "") as ScheduledNotification["channel"],
|
channel: String(raw.channel ?? "") as ScheduledNotification["channel"],
|
||||||
|
|
@ -396,16 +397,16 @@ function normalizeScheduledNotification(raw: unknown): ScheduledNotification | n
|
||||||
target_role: raw.target_role != null ? String(raw.target_role) : undefined,
|
target_role: raw.target_role != null ? String(raw.target_role) : undefined,
|
||||||
target_team_member_ids: Array.isArray(raw.target_team_member_ids)
|
target_team_member_ids: Array.isArray(raw.target_team_member_ids)
|
||||||
? raw.target_team_member_ids.map((v) => Number(v))
|
? raw.target_team_member_ids.map((v) => Number(v))
|
||||||
: Array.isArray(raw.target_raw?.team_member_ids)
|
: Array.isArray(target?.team_member_ids)
|
||||||
? (raw.target_raw as { team_member_ids: unknown[] }).team_member_ids.map((v) =>
|
? target.team_member_ids.map((v) =>
|
||||||
Number(v),
|
Number(v),
|
||||||
)
|
)
|
||||||
: undefined,
|
: undefined,
|
||||||
target_team_role:
|
target_team_role:
|
||||||
raw.target_team_role != null
|
raw.target_team_role != null
|
||||||
? String(raw.target_team_role)
|
? String(raw.target_team_role)
|
||||||
: raw.target_raw?.team_role != null
|
: target?.team_role != null
|
||||||
? String((raw.target_raw as { team_role: unknown }).team_role)
|
? String(target.team_role)
|
||||||
: undefined,
|
: undefined,
|
||||||
target_raw: isRecord(raw.target_raw)
|
target_raw: isRecord(raw.target_raw)
|
||||||
? {
|
? {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import http from "./http"
|
|
||||||
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
||||||
import type { GetPaymentsParams, Payment, PaymentsListData, PaymentsListResponse } from "../types/payment.types"
|
import type { GetPaymentsParams, Payment, PaymentsListData, PaymentsListResponse } from "../types/payment.types"
|
||||||
|
import http from "./http"
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
|
@ -108,7 +108,7 @@ export function paymentsFilterParams(
|
||||||
} else if (params.payment_method?.trim()) {
|
} else if (params.payment_method?.trim()) {
|
||||||
next.payment_method = params.payment_method.trim()
|
next.payment_method = params.payment_method.trim()
|
||||||
}
|
}
|
||||||
if (params.plan_category?.trim()) next.plan_category = params.plan_category.trim()
|
if (params.plan_category?.trim()) next.plan_category = params.plan_category
|
||||||
if (params.currency?.trim()) next.currency = params.currency.trim()
|
if (params.currency?.trim()) next.currency = params.currency.trim()
|
||||||
if (params.reference?.trim()) next.reference = params.reference.trim()
|
if (params.reference?.trim()) next.reference = params.reference.trim()
|
||||||
if (params.created_from?.trim()) next.created_from = params.created_from.trim()
|
if (params.created_from?.trim()) next.created_from = params.created_from.trim()
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import http from "./http"
|
|
||||||
import type {
|
import type {
|
||||||
CreateSubscriptionPlanPayload,
|
CreateSubscriptionPlanPayload,
|
||||||
SubscriptionPlan,
|
SubscriptionPlan,
|
||||||
|
|
@ -6,6 +5,7 @@ import type {
|
||||||
SubscriptionPlansListResponse,
|
SubscriptionPlansListResponse,
|
||||||
UpdateSubscriptionPlanPayload,
|
UpdateSubscriptionPlanPayload,
|
||||||
} from "../types/subscription.types"
|
} from "../types/subscription.types"
|
||||||
|
import http from "./http"
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
|
@ -16,11 +16,14 @@ function normalizeSubscriptionPlan(raw: unknown): SubscriptionPlan | null {
|
||||||
const id = Number(raw.id)
|
const id = Number(raw.id)
|
||||||
if (!Number.isFinite(id)) return null
|
if (!Number.isFinite(id)) return null
|
||||||
|
|
||||||
|
const category = raw.category
|
||||||
|
if (category !== "EDUCATION" && category !== "LEARN_ENGLISH" && category !== "IELTS" && category !== "DUOLINGO") return null
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
name: String(raw.name ?? ""),
|
name: String(raw.name ?? ""),
|
||||||
description: String(raw.description ?? ""),
|
description: String(raw.description ?? ""),
|
||||||
category: String(raw.category ?? ""),
|
category,
|
||||||
duration_value: Number(raw.duration_value ?? 0),
|
duration_value: Number(raw.duration_value ?? 0),
|
||||||
duration_unit: String(raw.duration_unit ?? "MONTH"),
|
duration_unit: String(raw.duration_unit ?? "MONTH"),
|
||||||
price: Number(raw.price ?? 0),
|
price: Number(raw.price ?? 0),
|
||||||
|
|
|
||||||
5
src/components/SearchHighlight.shared.ts
Normal file
5
src/components/SearchHighlight.shared.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
|
||||||
|
export function getSearchTokens(query: string): string[] {
|
||||||
|
return query.trim().split(/\s+/).filter(Boolean)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
import { Fragment, useMemo } from "react"
|
import { Fragment, useMemo } from "react"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
import { getSearchTokens } from "./SearchHighlight.shared"
|
||||||
export function getSearchTokens(query: string): string[] {
|
|
||||||
return query.trim().split(/\s+/).filter(Boolean)
|
|
||||||
}
|
|
||||||
|
|
||||||
function escapeRegExp(value: string): string {
|
function escapeRegExp(value: string): string {
|
||||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||||
|
|
|
||||||
54
src/components/analytics/AnalyticsTimeRangeFilter.shared.ts
Normal file
54
src/components/analytics/AnalyticsTimeRangeFilter.shared.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
import { APP_TIMEZONE, APP_TIMEZONE_OFFSET } from "../../lib/datetime"
|
||||||
|
import { formatPaymentMethod } from "../../lib/payments"
|
||||||
|
import type { DashboardFilters } from "../../types/analytics.types"
|
||||||
|
|
||||||
|
export const MONTH_LABELS = [
|
||||||
|
"January",
|
||||||
|
"February",
|
||||||
|
"March",
|
||||||
|
"April",
|
||||||
|
"May",
|
||||||
|
"June",
|
||||||
|
"July",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"October",
|
||||||
|
"November",
|
||||||
|
"December",
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const MIN_SELECTABLE_YEAR = 2000
|
||||||
|
|
||||||
|
export function getYearOptions(): number[] {
|
||||||
|
const currentYear = new Date().getFullYear()
|
||||||
|
const years: number[] = []
|
||||||
|
for (let year = currentYear; year >= MIN_SELECTABLE_YEAR; year--) {
|
||||||
|
years.push(year)
|
||||||
|
}
|
||||||
|
return years
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDashboardFilterLabel(filters: DashboardFilters): string {
|
||||||
|
let rangeLabel = "All Time"
|
||||||
|
if (filters.mode === "year" && filters.year != null) {
|
||||||
|
rangeLabel = String(filters.year)
|
||||||
|
} else if (filters.mode === "year_month" && filters.year != null && filters.month != null) {
|
||||||
|
rangeLabel = `${MONTH_LABELS[filters.month - 1]} ${filters.year}`
|
||||||
|
} else if (filters.mode === "custom" && filters.from && filters.to) {
|
||||||
|
const opts: Intl.DateTimeFormatOptions = {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
year: "numeric",
|
||||||
|
timeZone: APP_TIMEZONE,
|
||||||
|
}
|
||||||
|
const from = new Date(`${filters.from}T00:00:00${APP_TIMEZONE_OFFSET}`)
|
||||||
|
const to = new Date(`${filters.to}T00:00:00${APP_TIMEZONE_OFFSET}`)
|
||||||
|
rangeLabel = `${from.toLocaleDateString("en-US", opts)} – ${to.toLocaleDateString("en-US", opts)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!filters.payment_method) {
|
||||||
|
return rangeLabel
|
||||||
|
}
|
||||||
|
return `${rangeLabel} · ${formatPaymentMethod(filters.payment_method)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,29 +1,11 @@
|
||||||
import { useEffect, useRef, useState } from "react"
|
|
||||||
import { ChevronDown } from "lucide-react"
|
import { ChevronDown } from "lucide-react"
|
||||||
|
import { useEffect, useRef, useState } from "react"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import { Input } from "../ui/input"
|
|
||||||
import { Button } from "../ui/button"
|
|
||||||
import { Select } from "../ui/select"
|
|
||||||
import { formatPaymentMethod } from "../../lib/payments"
|
|
||||||
import { APP_TIMEZONE, APP_TIMEZONE_OFFSET } from "../../lib/datetime"
|
|
||||||
import type { DashboardFilters } from "../../types/analytics.types"
|
import type { DashboardFilters } from "../../types/analytics.types"
|
||||||
|
import { Button } from "../ui/button"
|
||||||
const MONTH_LABELS = [
|
import { Input } from "../ui/input"
|
||||||
"January",
|
import { Select } from "../ui/select"
|
||||||
"February",
|
import { MONTH_LABELS, getYearOptions } from "./AnalyticsTimeRangeFilter.shared"
|
||||||
"March",
|
|
||||||
"April",
|
|
||||||
"May",
|
|
||||||
"June",
|
|
||||||
"July",
|
|
||||||
"August",
|
|
||||||
"September",
|
|
||||||
"October",
|
|
||||||
"November",
|
|
||||||
"December",
|
|
||||||
] as const
|
|
||||||
|
|
||||||
const MIN_SELECTABLE_YEAR = 2000
|
|
||||||
|
|
||||||
export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
|
export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
|
||||||
{ value: "", label: "All methods" },
|
{ value: "", label: "All methods" },
|
||||||
|
|
@ -33,15 +15,6 @@ export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
|
||||||
{ value: "ADMIN_EXTEND", label: "Admin extend" },
|
{ value: "ADMIN_EXTEND", label: "Admin extend" },
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export function getYearOptions(): number[] {
|
|
||||||
const currentYear = new Date().getFullYear()
|
|
||||||
const years: number[] = []
|
|
||||||
for (let year = currentYear; year >= MIN_SELECTABLE_YEAR; year--) {
|
|
||||||
years.push(year)
|
|
||||||
}
|
|
||||||
return years
|
|
||||||
}
|
|
||||||
|
|
||||||
function withPaymentMethod(base: DashboardFilters, paymentMethod?: string): DashboardFilters {
|
function withPaymentMethod(base: DashboardFilters, paymentMethod?: string): DashboardFilters {
|
||||||
const next = { ...base }
|
const next = { ...base }
|
||||||
if (paymentMethod?.trim()) {
|
if (paymentMethod?.trim()) {
|
||||||
|
|
@ -52,30 +25,6 @@ function withPaymentMethod(base: DashboardFilters, paymentMethod?: string): Dash
|
||||||
return next
|
return next
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDashboardFilterLabel(filters: DashboardFilters): string {
|
|
||||||
let rangeLabel = "All Time"
|
|
||||||
if (filters.mode === "year" && filters.year != null) {
|
|
||||||
rangeLabel = String(filters.year)
|
|
||||||
} else if (filters.mode === "year_month" && filters.year != null && filters.month != null) {
|
|
||||||
rangeLabel = `${MONTH_LABELS[filters.month - 1]} ${filters.year}`
|
|
||||||
} else if (filters.mode === "custom" && filters.from && filters.to) {
|
|
||||||
const opts: Intl.DateTimeFormatOptions = {
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
year: "numeric",
|
|
||||||
timeZone: APP_TIMEZONE,
|
|
||||||
}
|
|
||||||
const from = new Date(`${filters.from}T00:00:00${APP_TIMEZONE_OFFSET}`)
|
|
||||||
const to = new Date(`${filters.to}T00:00:00${APP_TIMEZONE_OFFSET}`)
|
|
||||||
rangeLabel = `${from.toLocaleDateString("en-US", opts)} – ${to.toLocaleDateString("en-US", opts)}`
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!filters.payment_method) {
|
|
||||||
return rangeLabel
|
|
||||||
}
|
|
||||||
return `${rangeLabel} · ${formatPaymentMethod(filters.payment_method)}`
|
|
||||||
}
|
|
||||||
|
|
||||||
type AnalyticsTimeRangeFilterProps = {
|
type AnalyticsTimeRangeFilterProps = {
|
||||||
value: DashboardFilters
|
value: DashboardFilters
|
||||||
onChange: (filters: DashboardFilters) => void
|
onChange: (filters: DashboardFilters) => void
|
||||||
|
|
@ -95,18 +44,21 @@ export function AnalyticsTimeRangeFilter({ value, onChange, className }: Analyti
|
||||||
const years = getYearOptions()
|
const years = getYearOptions()
|
||||||
const paymentMethod = value.payment_method ?? ""
|
const paymentMethod = value.payment_method ?? ""
|
||||||
|
|
||||||
useEffect(() => {
|
const [previousYear, setPreviousYear] = useState(value.year)
|
||||||
if (value.year != null) {
|
if (previousYear !== value.year) {
|
||||||
setContextYear(value.year)
|
setPreviousYear(value.year)
|
||||||
}
|
if (value.year != null) setContextYear(value.year)
|
||||||
}, [value.year])
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
const customRangeKey = JSON.stringify([value.mode, value.from, value.to])
|
||||||
|
const [previousCustomRange, setPreviousCustomRange] = useState(customRangeKey)
|
||||||
|
if (previousCustomRange !== customRangeKey) {
|
||||||
|
setPreviousCustomRange(customRangeKey)
|
||||||
if (value.mode === "custom") {
|
if (value.mode === "custom") {
|
||||||
setCustomFrom(value.from ?? "")
|
setCustomFrom(value.from ?? "")
|
||||||
setCustomTo(value.to ?? "")
|
setCustomTo(value.to ?? "")
|
||||||
}
|
}
|
||||||
}, [value.from, value.mode, value.to])
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return
|
if (!open) return
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
|
||||||
|
export const SUBSCRIPTION_CHART_COLORS = [
|
||||||
|
"#B87891", // Rose
|
||||||
|
"#578E83", // Sage teal
|
||||||
|
"#8F7CA2", // Mauve
|
||||||
|
"#C39A53", // Champagne
|
||||||
|
"#6F859E", // Slate blue
|
||||||
|
"#BE6F7C", // Berry
|
||||||
|
"#82946D", // Olive
|
||||||
|
"#877B72", // Stone
|
||||||
|
]
|
||||||
|
|
||||||
|
export type PieSlice = { name: string; value: number; color: string }
|
||||||
|
|
||||||
|
export function labelCountsToPieSlices(
|
||||||
|
rows: { label: string; count: number }[],
|
||||||
|
colors: string[] = SUBSCRIPTION_CHART_COLORS,
|
||||||
|
): PieSlice[] {
|
||||||
|
return rows
|
||||||
|
.filter((row) => row.count > 0)
|
||||||
|
.map((row, i) => ({
|
||||||
|
name: row.label,
|
||||||
|
value: row.count,
|
||||||
|
color: colors[i % colors.length],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,84 +1,33 @@
|
||||||
import type { ReactNode } from "react"
|
|
||||||
import { Lightbulb } from "lucide-react"
|
import { Lightbulb } from "lucide-react"
|
||||||
|
import type { ReactNode } from "react"
|
||||||
import {
|
import {
|
||||||
Area,
|
Bar,
|
||||||
AreaChart,
|
BarChart,
|
||||||
CartesianGrid,
|
CartesianGrid,
|
||||||
Cell,
|
Cell,
|
||||||
Pie,
|
LabelList,
|
||||||
PieChart,
|
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
} from "recharts"
|
} from "recharts"
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { formatPercentRate } from "../../lib/analytics"
|
import { formatPercentRate } from "../../lib/analytics"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
||||||
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
|
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
|
||||||
|
import type { PieSlice } from "./SubscriptionRevenueVisuals.shared"
|
||||||
export const SUBSCRIPTION_CHART_COLORS = [
|
|
||||||
"#2563EB",
|
|
||||||
"#0F766E",
|
|
||||||
"#C2410C",
|
|
||||||
"#7C3AED",
|
|
||||||
"#BE123C",
|
|
||||||
"#15803D",
|
|
||||||
"#A16207",
|
|
||||||
"#0891B2",
|
|
||||||
"#4F46E5",
|
|
||||||
"#D97706",
|
|
||||||
"#DB2777",
|
|
||||||
"#65A30D",
|
|
||||||
]
|
|
||||||
|
|
||||||
const BRAND = "#2563EB"
|
|
||||||
|
|
||||||
const chartTooltipStyle = {
|
const chartTooltipStyle = {
|
||||||
borderRadius: 10,
|
borderRadius: 10,
|
||||||
border: "1px solid #E8E8E8",
|
border: "1px solid hsl(var(--border))",
|
||||||
|
backgroundColor: "hsl(var(--popover))",
|
||||||
|
color: "hsl(var(--popover-foreground))",
|
||||||
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
|
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const analyticsSoftCardClass =
|
export const analyticsSoftCardClass =
|
||||||
"rounded-xl border border-grayScale-200/70 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]"
|
"min-w-0 rounded-xl border border-grayScale-200/70 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]"
|
||||||
|
|
||||||
type PieSlice = { name: string; value: number; color: string }
|
|
||||||
|
|
||||||
function PiePercentLabel(props: {
|
|
||||||
cx?: number
|
|
||||||
cy?: number
|
|
||||||
midAngle?: number
|
|
||||||
innerRadius?: number
|
|
||||||
outerRadius?: number
|
|
||||||
percent?: number
|
|
||||||
}) {
|
|
||||||
const { cx = 0, cy = 0, midAngle = 0, innerRadius = 0, outerRadius = 0, percent = 0 } = props
|
|
||||||
if (percent < 0.04) return null
|
|
||||||
const RADIAN = Math.PI / 180
|
|
||||||
const radius = innerRadius + (outerRadius - innerRadius) * 0.52
|
|
||||||
const x = cx + radius * Math.cos(-midAngle * RADIAN)
|
|
||||||
const y = cy + radius * Math.sin(-midAngle * RADIAN)
|
|
||||||
const pct = Math.round(percent * 100)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<g>
|
|
||||||
<circle cx={x} cy={y} r={12} fill="#fff" stroke="#F0F0F0" strokeWidth={1} />
|
|
||||||
<text
|
|
||||||
x={x}
|
|
||||||
y={y}
|
|
||||||
fill="#4B5563"
|
|
||||||
textAnchor="middle"
|
|
||||||
dominantBaseline="central"
|
|
||||||
fontSize={9}
|
|
||||||
fontWeight={700}
|
|
||||||
>
|
|
||||||
{pct}%
|
|
||||||
</text>
|
|
||||||
</g>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function MonthlyRevenueTrendPanel({
|
export function MonthlyRevenueTrendPanel({
|
||||||
title = "Monthly Revenue Trend",
|
title = "Monthly Revenue Trend",
|
||||||
|
|
@ -107,7 +56,7 @@ export function MonthlyRevenueTrendPanel({
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-grayScale-400">{subtitle}</p>
|
<p className="text-xs text-grayScale-400">{subtitle}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex min-w-0 flex-wrap items-start gap-3">
|
||||||
{trailing}
|
{trailing}
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<div className="text-xl font-bold tracking-tight text-grayScale-900 sm:text-2xl">
|
<div className="text-xl font-bold tracking-tight text-grayScale-900 sm:text-2xl">
|
||||||
|
|
@ -126,88 +75,41 @@ export function MonthlyRevenueTrendPanel({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MonthlyRevenueAreaChart({
|
export function MonthlyRevenueBarChart({
|
||||||
data,
|
data,
|
||||||
gradientId = "monthlyRevenueFill",
|
|
||||||
dataKey = "revenue",
|
dataKey = "revenue",
|
||||||
xKey = "month",
|
xKey = "month",
|
||||||
height = 240,
|
height = 240,
|
||||||
yTickFormatter,
|
yTickFormatter,
|
||||||
}: {
|
}: {
|
||||||
data: Record<string, string | number>[]
|
data: { revenue: number; month?: string; date?: string; monthIndex?: number }[]
|
||||||
gradientId?: string
|
dataKey?: "revenue" | "month" | "date" | "monthIndex"
|
||||||
dataKey?: string
|
xKey?: "revenue" | "month" | "date" | "monthIndex"
|
||||||
xKey?: string
|
|
||||||
height?: number
|
height?: number
|
||||||
yTickFormatter?: (value: number) => string
|
yTickFormatter?: (value: number) => string
|
||||||
}) {
|
}) {
|
||||||
const peakIndex = data.reduce((best, row, idx) => {
|
const peakRevenue = Math.max(0, ...data.map(row => Number(row[dataKey] ?? 0)))
|
||||||
const v = Number(row[dataKey] ?? 0)
|
|
||||||
const bestV = Number(data[best]?.[dataKey] ?? 0)
|
|
||||||
return v > bestV ? idx : best
|
|
||||||
}, 0)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SensitiveChart>
|
<div className="min-w-0 w-full" style={{ height }}>
|
||||||
<ResponsiveContainer width="100%" height={height}>
|
<SensitiveChart>
|
||||||
<AreaChart data={data} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
|
<ResponsiveContainer width="100%" height="100%" minWidth={0}>
|
||||||
<defs>
|
<BarChart data={data} margin={{ left: 0, right: 8, top: 16, bottom: 4 }} barCategoryGap="25%">
|
||||||
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
|
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||||
<stop offset="0%" stopColor={BRAND} stopOpacity={0.32} />
|
<XAxis dataKey={xKey} tickLine={false} axisLine={false} fontSize={10} minTickGap={16} tick={{ fill: "var(--gs-500)" }} />
|
||||||
<stop offset="100%" stopColor={BRAND} stopOpacity={0.02} />
|
<YAxis tickLine={false} axisLine={false} fontSize={10} width={48} tick={{ fill: "var(--gs-500)" }} tickFormatter={yTickFormatter} />
|
||||||
</linearGradient>
|
<Tooltip cursor={{ fill: "var(--gs-100)" }} formatter={(value) => [`ETB ${Number(value).toLocaleString()}`, "Revenue"]} contentStyle={chartTooltipStyle} />
|
||||||
</defs>
|
<Bar dataKey={dataKey} name="Revenue" radius={[5, 5, 0, 0]} maxBarSize={30} isAnimationActive={false}>
|
||||||
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
|
{data.map((row, index) => <Cell key={String(row[xKey] ?? index)} fill={Number(row[dataKey]) === peakRevenue && peakRevenue > 0 ? "#775166" : "#B87891"} />)}
|
||||||
<XAxis
|
</Bar>
|
||||||
dataKey={xKey}
|
</BarChart>
|
||||||
tickLine={false}
|
</ResponsiveContainer>
|
||||||
axisLine={false}
|
</SensitiveChart>
|
||||||
fontSize={11}
|
</div>
|
||||||
tick={{ fill: "#9E9E9E" }}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={false}
|
|
||||||
fontSize={11}
|
|
||||||
width={44}
|
|
||||||
tick={{ fill: "#9E9E9E" }}
|
|
||||||
tickFormatter={yTickFormatter}
|
|
||||||
/>
|
|
||||||
<Tooltip
|
|
||||||
formatter={(value) => [`ETB ${Number(value).toLocaleString()}`, "Revenue"]}
|
|
||||||
contentStyle={chartTooltipStyle}
|
|
||||||
/>
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey={dataKey}
|
|
||||||
stroke={BRAND}
|
|
||||||
strokeWidth={2.75}
|
|
||||||
fill={`url(#${gradientId})`}
|
|
||||||
dot={(props) => {
|
|
||||||
const { cx, cy, index } = props
|
|
||||||
if (cx == null || cy == null) return null
|
|
||||||
const highlight = index === peakIndex
|
|
||||||
return (
|
|
||||||
<circle
|
|
||||||
key={`dot-${index}`}
|
|
||||||
cx={cx}
|
|
||||||
cy={cy}
|
|
||||||
r={highlight ? 5.5 : 3.5}
|
|
||||||
fill={BRAND}
|
|
||||||
stroke="#fff"
|
|
||||||
strokeWidth={highlight ? 2 : 1}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
activeDot={{ r: 6, strokeWidth: 2, stroke: "#fff" }}
|
|
||||||
/>
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</SensitiveChart>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DonutBreakdownCard({
|
export function BreakdownBarCard({
|
||||||
title,
|
title,
|
||||||
data,
|
data,
|
||||||
countSuffix = "Users",
|
countSuffix = "Users",
|
||||||
|
|
@ -224,60 +126,25 @@ export function DonutBreakdownCard({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className={cn(analyticsSoftCardClass, className)}>
|
<Card className={cn(analyticsSoftCardClass, className)}>
|
||||||
<CardHeader className="pb-2 pt-5">
|
<CardHeader className="pb-4 pt-5">
|
||||||
<CardTitle className="text-base font-bold text-grayScale-900">{title}</CardTitle>
|
<CardTitle className="text-base font-bold text-grayScale-900">{title}</CardTitle>
|
||||||
|
{total > 0 && <p className="text-xs text-grayScale-500">{total.toLocaleString()} {(total === 1 ? countSuffix.replace(/s$/i, "") : countSuffix).toLowerCase()} in total</p>}
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="px-5 pb-5 pt-0">
|
<CardContent className="min-w-0 space-y-5 px-5 pb-6 pt-0">
|
||||||
{data.length > 0 && total > 0 ? (
|
{total > 0 ? (
|
||||||
<div className="grid items-center gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]">
|
<>
|
||||||
<div className="relative mx-auto h-[200px] w-full max-w-[220px]">
|
<VerticalCategoryChart data={data} label={title} />
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<PieChart>
|
|
||||||
<Pie
|
|
||||||
data={data}
|
|
||||||
dataKey="value"
|
|
||||||
nameKey="name"
|
|
||||||
innerRadius={58}
|
|
||||||
outerRadius={82}
|
|
||||||
paddingAngle={3}
|
|
||||||
strokeWidth={0}
|
|
||||||
label={PiePercentLabel}
|
|
||||||
labelLine={false}
|
|
||||||
>
|
|
||||||
{data.map((entry) => (
|
|
||||||
<Cell key={entry.name} fill={entry.color} />
|
|
||||||
))}
|
|
||||||
</Pie>
|
|
||||||
<Tooltip
|
|
||||||
formatter={(value, name) => [
|
|
||||||
`${Number(value).toLocaleString()} ${countSuffix.toLowerCase()}`,
|
|
||||||
String(name),
|
|
||||||
]}
|
|
||||||
contentStyle={chartTooltipStyle}
|
|
||||||
/>
|
|
||||||
</PieChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{data.map((s) => (
|
{data.map((row, index) => (
|
||||||
<div key={s.name} className="flex items-start gap-3">
|
<div key={row.name} className="flex items-start gap-2 text-xs">
|
||||||
<span
|
<span className="mt-1 h-2.5 w-2.5 shrink-0 rounded-sm" style={{ backgroundColor: row.color }} />
|
||||||
className="mt-0.5 h-10 w-1.5 shrink-0 rounded-full"
|
<span className="min-w-0 flex-1 break-words text-grayScale-700 [overflow-wrap:anywhere]">{row.name.length > 14 ? `${index + 1}. ` : ""}{row.name}</span>
|
||||||
style={{ backgroundColor: s.color }}
|
<span className="shrink-0 font-semibold tabular-nums text-grayScale-800">{row.value.toLocaleString()} <span className="font-normal text-grayScale-500">({Math.round(row.value / total * 100)}%)</span></span>
|
||||||
/>
|
|
||||||
<div className="min-w-0">
|
|
||||||
<div className="truncate text-sm font-semibold text-grayScale-800">{s.name}</div>
|
|
||||||
<div className="text-xs text-grayScale-400">
|
|
||||||
{s.value.toLocaleString()} {countSuffix}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</>
|
||||||
) : (
|
) : <div className="py-10 text-center text-xs text-grayScale-500">{emptyMessage}</div>}
|
||||||
<div className="py-12 text-center text-xs text-grayScale-400">{emptyMessage}</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
|
|
@ -293,7 +160,7 @@ export function ActivePlansBreakdownCard({
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DonutBreakdownCard
|
<BreakdownBarCard
|
||||||
title={title}
|
title={title}
|
||||||
data={data}
|
data={data}
|
||||||
countSuffix="Users"
|
countSuffix="Users"
|
||||||
|
|
@ -307,25 +174,16 @@ export function RenewalRateCard({
|
||||||
renewalRate,
|
renewalRate,
|
||||||
autoRenewCount,
|
autoRenewCount,
|
||||||
cancelledCount,
|
cancelledCount,
|
||||||
activeNow,
|
tip = "Review upcoming expiry dates and follow up with learners before their access ends.",
|
||||||
tip = "Enable automated email reminders for manual renewal users to improve retention by estimated 3–5%.",
|
|
||||||
className,
|
className,
|
||||||
}: {
|
}: {
|
||||||
renewalRate: number
|
renewalRate: number
|
||||||
autoRenewCount: number
|
autoRenewCount: number
|
||||||
cancelledCount: number
|
cancelledCount: number
|
||||||
activeNow: number
|
|
||||||
tip?: string
|
tip?: string
|
||||||
className?: string
|
className?: string
|
||||||
}) {
|
}) {
|
||||||
const ratePct = Math.max(0, Math.min(100, renewalRate * 100))
|
const ratePct = Math.max(0, Math.min(100, renewalRate * 100))
|
||||||
const circumference = 2 * Math.PI * 48
|
|
||||||
const dash = (ratePct / 100) * circumference
|
|
||||||
const autoRenewPct =
|
|
||||||
activeNow > 0 ? Math.min(100, (autoRenewCount / activeNow) * 100) : 0
|
|
||||||
const cancelledDenom = activeNow + cancelledCount
|
|
||||||
const cancelledPct =
|
|
||||||
cancelledDenom > 0 ? Math.min(100, (cancelledCount / cancelledDenom) * 100) : 0
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className={cn(analyticsSoftCardClass, className)}>
|
<Card className={cn(analyticsSoftCardClass, className)}>
|
||||||
|
|
@ -333,58 +191,25 @@ export function RenewalRateCard({
|
||||||
<CardTitle className="text-base font-bold text-grayScale-900">Renewal Rate</CardTitle>
|
<CardTitle className="text-base font-bold text-grayScale-900">Renewal Rate</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="px-5 pb-5 pt-0">
|
<CardContent className="px-5 pb-5 pt-0">
|
||||||
<div className="flex flex-col gap-5 sm:flex-row sm:items-center">
|
<div className="rounded-xl border border-grayScale-100 bg-grayScale-100/30 p-4">
|
||||||
<div className="relative mx-auto flex h-40 w-40 shrink-0 items-center justify-center">
|
<p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-grayScale-500">Learner retention</p>
|
||||||
<svg viewBox="0 0 120 120" className="h-full w-full -rotate-90">
|
<div className="mb-4 mt-3 flex items-baseline gap-2">
|
||||||
<circle cx="60" cy="60" r="48" fill="none" stroke="#F0F0F0" strokeWidth="10" />
|
<span className="text-4xl font-semibold tracking-tight text-grayScale-900">{formatPercentRate(renewalRate, 0)}</span>
|
||||||
<circle
|
<span className="text-xs text-grayScale-500">renewal rate</span>
|
||||||
cx="60"
|
|
||||||
cy="60"
|
|
||||||
r="48"
|
|
||||||
fill="none"
|
|
||||||
stroke={BRAND}
|
|
||||||
strokeWidth="10"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeDasharray={`${dash.toFixed(1)} ${circumference.toFixed(1)}`}
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
<div className="absolute inset-0 flex flex-col items-center justify-center text-center">
|
|
||||||
<span className="text-2xl font-bold tracking-tight text-grayScale-900">
|
|
||||||
{formatPercentRate(renewalRate, 0)}
|
|
||||||
</span>
|
|
||||||
<span className="text-[11px] font-medium text-grayScale-400">Retention</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div role="meter" aria-label="Renewal rate" aria-valuemin={0} aria-valuemax={100} aria-valuenow={ratePct} className="h-2.5 overflow-hidden rounded-full bg-grayScale-200">
|
||||||
<div className="min-w-0 flex-1 space-y-4">
|
<div className="h-full rounded-full bg-[#578E83]" style={{ width: `${ratePct}%` }} />
|
||||||
<div>
|
</div>
|
||||||
<div className="mb-1.5 flex items-center justify-between gap-2 text-xs">
|
<div className="mt-1.5 flex justify-between text-[10px] text-grayScale-500"><span>0%</span><span>100%</span></div>
|
||||||
<span className="font-semibold text-grayScale-800">Auto-Renew</span>
|
</div>
|
||||||
<span className="text-grayScale-400">
|
<div className="mt-5 grid grid-cols-2 gap-3">
|
||||||
{autoRenewCount.toLocaleString()} Users
|
<div className="min-w-0 border-l-2 border-[#578E83] pl-3">
|
||||||
</span>
|
<p className="text-xl font-semibold tabular-nums text-grayScale-900">{autoRenewCount.toLocaleString()}</p>
|
||||||
</div>
|
<p className="mt-1 text-[11px] leading-relaxed text-grayScale-500">Auto-renew enabled</p>
|
||||||
<div className="h-2.5 overflow-hidden rounded-full bg-grayScale-100">
|
</div>
|
||||||
<div
|
<div className="min-w-0 border-l-2 border-[#BE6F7C] pl-3">
|
||||||
className="h-full rounded-full transition-all"
|
<p className="text-xl font-semibold tabular-nums text-grayScale-900">{cancelledCount.toLocaleString()}</p>
|
||||||
style={{ width: `${autoRenewPct}%`, backgroundColor: BRAND }}
|
<p className="mt-1 text-[11px] leading-relaxed text-grayScale-500">Canceled</p>
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="mb-1.5 flex items-center justify-between gap-2 text-xs">
|
|
||||||
<span className="font-semibold text-grayScale-800">Canceled</span>
|
|
||||||
<span className="text-grayScale-400">
|
|
||||||
{cancelledCount.toLocaleString()} Users
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-2.5 overflow-hidden rounded-full bg-grayScale-100">
|
|
||||||
<div
|
|
||||||
className="h-full rounded-full bg-sky-300 transition-all"
|
|
||||||
style={{ width: `${Math.max(cancelledPct, cancelledCount > 0 ? 8 : 0)}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -400,17 +225,26 @@ export function RenewalRateCard({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function labelCountsToPieSlices(
|
function VerticalCategoryChart({ data, label }: { data: PieSlice[]; label: string }) {
|
||||||
rows: { label: string; count: number }[],
|
const chartData = data.map((row, index) => ({ ...row, axisLabel: row.name.length > 14 ? `#${index + 1}` : row.name.toLowerCase().replace(/(^|\s)\S/g, letter => letter.toUpperCase()) }))
|
||||||
colors: string[] = SUBSCRIPTION_CHART_COLORS,
|
return (
|
||||||
): PieSlice[] {
|
<div className={cn("min-w-0", data.length > 4 ? "overflow-x-auto overscroll-x-contain" : "overflow-hidden")} role="img" aria-label={label}>
|
||||||
return rows
|
<div className="h-[210px] w-full" style={{ minWidth: data.length > 4 ? data.length * 64 : undefined }}>
|
||||||
.filter((row) => row.count > 0)
|
<ResponsiveContainer width="100%" height="100%" minWidth={0}>
|
||||||
.map((row, i) => ({
|
<BarChart data={chartData} margin={{ top: 24, right: 8, bottom: 4, left: 0 }} barCategoryGap="28%">
|
||||||
name: row.label,
|
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||||
value: row.count,
|
<XAxis dataKey="axisLabel" interval={0} height={32} tickLine={false} axisLine={false} fontSize={10} tick={{ fill: "var(--gs-500)" }} />
|
||||||
color: colors[i % colors.length],
|
<YAxis domain={[0, Math.max(1, ...data.map(row => row.value))]} allowDecimals={false} width={34} tickLine={false} axisLine={false} fontSize={10} tick={{ fill: "var(--gs-500)" }} tickFormatter={value => Number(value).toLocaleString(undefined, { notation: "compact" })} />
|
||||||
}))
|
<Tooltip cursor={{ fill: "var(--gs-100)" }} labelFormatter={(_, entries) => entries[0]?.payload?.name ?? ""} formatter={value => [Number(value).toLocaleString(), "Count"]} contentStyle={chartTooltipStyle} />
|
||||||
|
<Bar dataKey="value" maxBarSize={36} radius={[6, 6, 0, 0]} isAnimationActive={false}>
|
||||||
|
{data.map(row => <Cell key={row.name} fill={row.color} />)}
|
||||||
|
<LabelList dataKey="value" position="top" fill="var(--gs-600)" fontSize={10} formatter={value => Number(value) > 0 ? Number(value).toLocaleString(undefined, { notation: "compact" }) : ""} />
|
||||||
|
</Bar>
|
||||||
|
</BarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SensitiveYtdValue({ amount }: { amount: number }) {
|
export function SensitiveYtdValue({ amount }: { amount: number }) {
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,5 @@
|
||||||
import { useMemo } from "react"
|
|
||||||
import { Plus, Trash2 } from "lucide-react"
|
import { Plus, Trash2 } from "lucide-react"
|
||||||
import { Button } from "../ui/button"
|
import { useMemo } from "react"
|
||||||
import { Input } from "../ui/input"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
import { UnassignedLabel } from "../../lib/displayValue"
|
||||||
import {
|
import {
|
||||||
createEmptyTable,
|
createEmptyTable,
|
||||||
|
|
@ -10,6 +7,9 @@ import {
|
||||||
serializeTableSlotValue,
|
serializeTableSlotValue,
|
||||||
type DynamicTableValue,
|
type DynamicTableValue,
|
||||||
} from "../../lib/dynamicTableValue"
|
} from "../../lib/dynamicTableValue"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import { Button } from "../ui/button"
|
||||||
|
import { Input } from "../ui/input"
|
||||||
|
|
||||||
export type DynamicTableBuilderProps = {
|
export type DynamicTableBuilderProps = {
|
||||||
value: string
|
value: string
|
||||||
|
|
@ -91,7 +91,7 @@ export function DynamicTableBuilder({
|
||||||
|
|
||||||
const previewColumns = table.columns.map((c, i) => c.trim() || `Column ${i + 1}`)
|
const previewColumns = table.columns.map((c, i) => c.trim() || `Column ${i + 1}`)
|
||||||
const previewRows = table.rows.map((row) =>
|
const previewRows = table.rows.map((row) =>
|
||||||
row.map((cell, ci) => cell.trim() || ""),
|
row.map((cell) => cell.trim() || ""),
|
||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
|
||||||
|
export type PracticeQuestionEditorType = "MCQ" | "TRUE_FALSE" | "SHORT" | "AUDIO" | "DYNAMIC"
|
||||||
|
|
||||||
|
export type PracticeQuestionEditorDifficulty = "EASY" | "MEDIUM" | "HARD"
|
||||||
|
|
||||||
|
export interface PracticeQuestionOptionDraft {
|
||||||
|
text: string
|
||||||
|
isCorrect: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PracticeQuestionDynamicRow {
|
||||||
|
id: string
|
||||||
|
kind: string
|
||||||
|
label?: string
|
||||||
|
required?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PracticeQuestionEditorValue {
|
||||||
|
questionText: string
|
||||||
|
questionType: PracticeQuestionEditorType
|
||||||
|
difficultyLevel: PracticeQuestionEditorDifficulty
|
||||||
|
points: number
|
||||||
|
tips: string
|
||||||
|
explanation: string
|
||||||
|
options: PracticeQuestionOptionDraft[]
|
||||||
|
voicePrompt: string
|
||||||
|
sampleAnswerVoicePrompt: string
|
||||||
|
audioCorrectAnswerText: string
|
||||||
|
shortAnswer: string
|
||||||
|
/** Stored URL or object key; same semantics as Speaking practice editor */
|
||||||
|
imageUrl: string
|
||||||
|
/** When `questionType` is DYNAMIC — definition used to shape `dynamic_payload` */
|
||||||
|
questionTypeDefinitionId: number | null
|
||||||
|
dynamicStimulusRows: PracticeQuestionDynamicRow[]
|
||||||
|
dynamicResponseRows: PracticeQuestionDynamicRow[]
|
||||||
|
/** Keys `stimulus:${elementId}` and `response:${elementId}` (ids from the type definition schema) */
|
||||||
|
dynamicFieldValues: Record<string, string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createEmptyPracticeQuestionDraft(): PracticeQuestionEditorValue {
|
||||||
|
return {
|
||||||
|
questionText: "",
|
||||||
|
questionType: "MCQ",
|
||||||
|
difficultyLevel: "EASY",
|
||||||
|
points: 1,
|
||||||
|
tips: "",
|
||||||
|
explanation: "",
|
||||||
|
options: [
|
||||||
|
{ text: "", isCorrect: true },
|
||||||
|
{ text: "", isCorrect: false },
|
||||||
|
{ text: "", isCorrect: false },
|
||||||
|
{ text: "", isCorrect: false },
|
||||||
|
],
|
||||||
|
voicePrompt: "",
|
||||||
|
sampleAnswerVoicePrompt: "",
|
||||||
|
audioCorrectAnswerText: "",
|
||||||
|
shortAnswer: "",
|
||||||
|
imageUrl: "",
|
||||||
|
questionTypeDefinitionId: null,
|
||||||
|
dynamicStimulusRows: [],
|
||||||
|
dynamicResponseRows: [],
|
||||||
|
dynamicFieldValues: {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { Check, Image as ImageIcon, Mic, Plus, Upload, X } from "lucide-react"
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
|
|
@ -6,34 +6,26 @@ import {
|
||||||
useState,
|
useState,
|
||||||
type ChangeEvent,
|
type ChangeEvent,
|
||||||
} from "react"
|
} from "react"
|
||||||
import { Check, Image as ImageIcon, Mic, Plus, Upload, X } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { resolveMediaPreviewUrl } from "../../lib/practiceMedia"
|
|
||||||
import { uploadAudioFile, uploadImageFile } from "../../api/files.api"
|
import { uploadAudioFile, uploadImageFile } from "../../api/files.api"
|
||||||
import {
|
import {
|
||||||
getQuestionTypeDefinitionById,
|
getQuestionTypeDefinitionById,
|
||||||
getQuestionTypeDefinitions,
|
getQuestionTypeDefinitions,
|
||||||
questionTypeDefinitionListLabel,
|
questionTypeDefinitionListLabel,
|
||||||
} from "../../api/questionTypeDefinitions.api"
|
} from "../../api/questionTypeDefinitions.api"
|
||||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
import { Input } from "../ui/input"
|
import { resolveMediaPreviewUrl } from "../../lib/practiceMedia"
|
||||||
import { Textarea } from "../ui/textarea"
|
|
||||||
import { Select } from "../ui/select"
|
|
||||||
import { Button } from "../ui/button"
|
|
||||||
import { SpinnerIcon } from "../ui/spinner-icon"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { isNoInputComponentKind } from "../../lib/questionComponentKinds"
|
import { isNoInputComponentKind } from "../../lib/questionComponentKinds"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||||
import { ResolvedAudio } from "../media/ResolvedAudio"
|
import { ResolvedAudio } from "../media/ResolvedAudio"
|
||||||
import { ResolvedImage } from "../media/ResolvedImage"
|
import { ResolvedImage } from "../media/ResolvedImage"
|
||||||
|
import { Button } from "../ui/button"
|
||||||
|
import { Input } from "../ui/input"
|
||||||
|
import { Select } from "../ui/select"
|
||||||
|
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||||
import { DynamicSchemaSlotField } from "./DynamicSchemaSlotField"
|
import { DynamicSchemaSlotField } from "./DynamicSchemaSlotField"
|
||||||
|
import type { PracticeQuestionDynamicRow, PracticeQuestionEditorDifficulty, PracticeQuestionEditorType, PracticeQuestionEditorValue, PracticeQuestionOptionDraft } from "./PracticeQuestionEditorFields.shared"
|
||||||
export type PracticeQuestionEditorType = "MCQ" | "TRUE_FALSE" | "SHORT" | "AUDIO" | "DYNAMIC"
|
|
||||||
export type PracticeQuestionEditorDifficulty = "EASY" | "MEDIUM" | "HARD"
|
|
||||||
|
|
||||||
export interface PracticeQuestionOptionDraft {
|
|
||||||
text: string
|
|
||||||
isCorrect: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
type RecordingField = "voice_prompt" | "sample_answer_voice_prompt"
|
type RecordingField = "voice_prompt" | "sample_answer_voice_prompt"
|
||||||
|
|
||||||
|
|
@ -42,61 +34,6 @@ const ALLOWED_AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "m4a", "aac", "we
|
||||||
const MAX_IMAGE_SIZE_BYTES = 10 * 1024 * 1024
|
const MAX_IMAGE_SIZE_BYTES = 10 * 1024 * 1024
|
||||||
const ALLOWED_IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "webp", "gif"])
|
const ALLOWED_IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "webp", "gif"])
|
||||||
|
|
||||||
export interface PracticeQuestionDynamicRow {
|
|
||||||
id: string
|
|
||||||
kind: string
|
|
||||||
label?: string
|
|
||||||
required?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PracticeQuestionEditorValue {
|
|
||||||
questionText: string
|
|
||||||
questionType: PracticeQuestionEditorType
|
|
||||||
difficultyLevel: PracticeQuestionEditorDifficulty
|
|
||||||
points: number
|
|
||||||
tips: string
|
|
||||||
explanation: string
|
|
||||||
options: PracticeQuestionOptionDraft[]
|
|
||||||
voicePrompt: string
|
|
||||||
sampleAnswerVoicePrompt: string
|
|
||||||
audioCorrectAnswerText: string
|
|
||||||
shortAnswer: string
|
|
||||||
/** Stored URL or object key; same semantics as Speaking practice editor */
|
|
||||||
imageUrl: string
|
|
||||||
/** When `questionType` is DYNAMIC — definition used to shape `dynamic_payload` */
|
|
||||||
questionTypeDefinitionId: number | null
|
|
||||||
dynamicStimulusRows: PracticeQuestionDynamicRow[]
|
|
||||||
dynamicResponseRows: PracticeQuestionDynamicRow[]
|
|
||||||
/** Keys `stimulus:${elementId}` and `response:${elementId}` (ids from the type definition schema) */
|
|
||||||
dynamicFieldValues: Record<string, string>
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createEmptyPracticeQuestionDraft(): PracticeQuestionEditorValue {
|
|
||||||
return {
|
|
||||||
questionText: "",
|
|
||||||
questionType: "MCQ",
|
|
||||||
difficultyLevel: "EASY",
|
|
||||||
points: 1,
|
|
||||||
tips: "",
|
|
||||||
explanation: "",
|
|
||||||
options: [
|
|
||||||
{ text: "", isCorrect: true },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
],
|
|
||||||
voicePrompt: "",
|
|
||||||
sampleAnswerVoicePrompt: "",
|
|
||||||
audioCorrectAnswerText: "",
|
|
||||||
shortAnswer: "",
|
|
||||||
imageUrl: "",
|
|
||||||
questionTypeDefinitionId: null,
|
|
||||||
dynamicStimulusRows: [],
|
|
||||||
dynamicResponseRows: [],
|
|
||||||
dynamicFieldValues: {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function useDebouncedString(value: string, delayMs: number) {
|
function useDebouncedString(value: string, delayMs: number) {
|
||||||
const [debounced, setDebounced] = useState(value)
|
const [debounced, setDebounced] = useState(value)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
||||||
53
src/components/dashboard/DashboardProfileRail.tsx
Normal file
53
src/components/dashboard/DashboardProfileRail.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
import { ArrowUpRight, BookOpen, CalendarDays, ChevronRight, Pencil, ShieldCheck, Users } from "lucide-react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import type { DashboardData } from "../../types/analytics.types"
|
||||||
|
|
||||||
|
export function DashboardProfileRail({ firstName, dashboard }: { firstName: string; dashboard: DashboardData | null }) {
|
||||||
|
const name = [firstName || localStorage.getItem("user_first_name"), localStorage.getItem("user_last_name")].filter(Boolean).join(" ") || "Your account"
|
||||||
|
const role = (localStorage.getItem("role") || "Team member").replaceAll("_", " ").toLowerCase()
|
||||||
|
const today = new Date()
|
||||||
|
const weekStart = new Date(today)
|
||||||
|
weekStart.setDate(today.getDate() - today.getDay())
|
||||||
|
const days = Array.from({ length: 7 }, (_, index) => {
|
||||||
|
const day = new Date(weekStart)
|
||||||
|
day.setDate(weekStart.getDate() + index)
|
||||||
|
return day
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<aside className="dashboard-profile min-w-0" aria-label="Your workspace summary">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h2 className="text-sm font-semibold">Profile</h2>
|
||||||
|
<Link to="/profile" aria-label="Edit profile" className="rail-icon"><Pencil className="h-4 w-4" /></Link>
|
||||||
|
</div>
|
||||||
|
<div className="py-7 text-center">
|
||||||
|
<div className="profile-orbit mx-auto mb-4 grid h-24 w-24 place-items-center rounded-full">
|
||||||
|
<span className="grid h-[74px] w-[74px] place-items-center rounded-full bg-brand-100 text-2xl font-semibold text-brand-600">{name.split(" ").slice(0, 2).map(part => part.charAt(0)).join("")}</span>
|
||||||
|
</div>
|
||||||
|
<p className="flex items-center justify-center gap-1.5 text-sm font-semibold">{name}<ShieldCheck className="h-4 w-4 text-brand-500" /></p>
|
||||||
|
<p className="mt-1 text-xs capitalize text-grayScale-500">{role}</p>
|
||||||
|
</div>
|
||||||
|
<section className="rounded-xl bg-grayScale-100/70 px-3 py-4" aria-label="Current week">
|
||||||
|
<p className="mb-4 flex items-center justify-center gap-2 text-xs font-semibold"><CalendarDays className="h-3.5 w-3.5 text-brand-600" />{today.toLocaleDateString(undefined, { month: "long", year: "numeric" })}</p>
|
||||||
|
<div className="grid grid-cols-7 gap-1 text-center">
|
||||||
|
{days.map(day => <div key={day.toISOString()} className={day.toDateString() === today.toDateString() ? "rounded-full bg-brand-500 py-2 text-white" : "py-2"} aria-current={day.toDateString() === today.toDateString() ? "date" : undefined}>
|
||||||
|
<p className="mb-2 text-[9px] opacity-60">{day.toLocaleDateString(undefined, { weekday: "narrow" })}</p>
|
||||||
|
<p className={day.toDateString() === today.toDateString() ? "mx-auto grid h-6 w-6 place-items-center rounded-full bg-brand-400 text-[10px] font-medium" : "grid h-6 place-items-center text-[10px] font-medium"}>{day.getDate()}</p>
|
||||||
|
</div>)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="mt-6 border-t pt-6">
|
||||||
|
<h2 className="mb-4 text-sm font-semibold">Workspace at a glance</h2>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Link to="/users/list" className="rail-summary"><span className="rail-icon bg-brand-100"><Users className="h-4 w-4" /></span><span className="flex-1"><span className="block text-xs font-medium">Learners</span><span className="mt-1 block text-[11px] text-grayScale-500">{dashboard ? dashboard.users.total_users.toLocaleString() + " registered users" : "Manage your community"}</span></span><ChevronRight className="h-3.5 w-3.5 text-grayScale-400" /></Link>
|
||||||
|
<Link to="/new-content/courses" className="rail-summary"><span className="rail-icon bg-brand-100"><BookOpen className="h-4 w-4" /></span><span className="flex-1"><span className="block text-xs font-medium">Makeup artistry courses</span><span className="mt-1 block text-[11px] text-grayScale-500">Organize courses and lessons</span></span><ChevronRight className="h-3.5 w-3.5 text-grayScale-400" /></Link>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div className="rail-callout mt-7 rounded-xl bg-brand-50 p-4">
|
||||||
|
<span className="mb-3 inline-flex rounded-lg bg-white/70 p-2 text-brand-600"><BookOpen className="h-5 w-5" /></span>
|
||||||
|
<h3 className="text-sm font-semibold">Where artistry begins.</h3>
|
||||||
|
<p className="mt-2 text-xs leading-relaxed text-grayScale-500">Shape the next generation of makeup artists, one lesson at a time.</p>
|
||||||
|
<Link to="/new-content/courses" className="mt-4 flex items-center justify-between rounded-lg bg-brand-500 px-3 py-2.5 text-xs font-medium text-white transition hover:bg-brand-600">Explore content<ArrowUpRight className="h-4 w-4" /></Link>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -1,15 +1,16 @@
|
||||||
import { useEffect, useMemo, useState } from "react"
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import { getDashboard } from "../../api/analytics.api"
|
import { getDashboard } from "../../api/analytics.api"
|
||||||
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter"
|
import { getYearOptions } from "../analytics/AnalyticsTimeRangeFilter.shared"
|
||||||
|
|
||||||
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
|
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
|
||||||
|
import type { DateRevenue } from "../../types/analytics.types"
|
||||||
import {
|
import {
|
||||||
MonthlyRevenueAreaChart,
|
MonthlyRevenueBarChart,
|
||||||
MonthlyRevenueTrendPanel,
|
MonthlyRevenueTrendPanel,
|
||||||
SensitiveYtdValue,
|
SensitiveYtdValue,
|
||||||
} from "../analytics/SubscriptionRevenueVisuals"
|
} from "../analytics/SubscriptionRevenueVisuals"
|
||||||
import { Select } from "../ui/select"
|
import { Select } from "../ui/select"
|
||||||
import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analytics"
|
|
||||||
import type { DateRevenue } from "../../types/analytics.types"
|
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
|
||||||
|
|
||||||
export function RevenueTrendCard({ paymentMethod }: { paymentMethod?: string }) {
|
export function RevenueTrendCard({ paymentMethod }: { paymentMethod?: string }) {
|
||||||
const currentYear = new Date().getFullYear()
|
const currentYear = new Date().getFullYear()
|
||||||
|
|
@ -80,9 +81,9 @@ export function RevenueTrendCard({ paymentMethod }: { paymentMethod?: string })
|
||||||
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<MonthlyRevenueAreaChart
|
<MonthlyRevenueBarChart
|
||||||
data={chartData}
|
data={chartData}
|
||||||
gradientId="dashboardMonthlyRevenueFill"
|
|
||||||
yTickFormatter={formatRevenueAxisTick}
|
yTickFormatter={formatRevenueAxisTick}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -27,20 +27,20 @@ export function StatCard({
|
||||||
<Card
|
<Card
|
||||||
className={cn(
|
className={cn(
|
||||||
analyticsSoftCardClass,
|
analyticsSoftCardClass,
|
||||||
"ui-3d-card-interactive",
|
"dashboard-stat ui-3d-card-interactive",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<CardContent className="p-5">
|
<CardContent className="p-5">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-xs font-semibold uppercase tracking-wide text-grayScale-400">
|
<div className="text-xs font-medium text-grayScale-600">
|
||||||
{label}
|
{label}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1.5 text-[1.75rem] font-semibold leading-none tracking-tight text-grayScale-900">
|
<div className="mt-1.5 text-[1.75rem] font-semibold leading-none tracking-tight text-grayScale-900">
|
||||||
{value}
|
{value}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-brand-100/60 text-brand-600 ring-1 ring-brand-100/80">
|
<div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl stat-icon bg-white/60 text-brand-600">
|
||||||
<Icon className="h-5 w-5" />
|
<Icon className="h-5 w-5" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState, type ReactNode } from "react"
|
import { useState, type ReactNode } from "react"
|
||||||
import { ChevronDown, SlidersHorizontal, X } from "lucide-react"
|
import { ChevronDown, SlidersHorizontal, X } from "lucide-react"
|
||||||
import { Badge } from "../ui/badge"
|
import { Badge } from "../ui/badge"
|
||||||
import { Button } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
|
|
@ -33,11 +33,12 @@ export function AdminFiltersPanel({
|
||||||
const [open, setOpen] = useState(defaultOpen || activeFilterCount > 0)
|
const [open, setOpen] = useState(defaultOpen || activeFilterCount > 0)
|
||||||
const inlineActions = Boolean(actions)
|
const inlineActions = Boolean(actions)
|
||||||
|
|
||||||
useEffect(() => {
|
const filterState = `${activeFilterCount}:${inlineActions}`
|
||||||
if (!inlineActions && activeFilterCount > 0) {
|
const [previousFilterState, setPreviousFilterState] = useState(filterState)
|
||||||
setOpen(true)
|
if (previousFilterState !== filterState) {
|
||||||
}
|
setPreviousFilterState(filterState)
|
||||||
}, [activeFilterCount, inlineActions])
|
if (!inlineActions && activeFilterCount > 0) setOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,24 @@
|
||||||
import { useState } from "react";
|
|
||||||
import { Bell } from "lucide-react";
|
import { Bell } from "lucide-react";
|
||||||
import { Badge } from "../ui/badge";
|
import { useState } from "react";
|
||||||
import { Button } from "../ui/button";
|
import { UnassignedLabel } from "../../lib/displayValue";
|
||||||
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
|
|
||||||
import { SpinnerIcon } from "../ui/spinner-icon";
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||||
|
NOTIFICATION_TYPE_CONFIG,
|
||||||
formatNotificationDateTime,
|
formatNotificationDateTime,
|
||||||
formatNotificationTimestamp,
|
formatNotificationTimestamp,
|
||||||
formatNotificationTypeLabel,
|
formatNotificationTypeLabel,
|
||||||
isMeaningfulExpiry,
|
isMeaningfulExpiry,
|
||||||
NOTIFICATION_TYPE_CONFIG,
|
|
||||||
} from "../../lib/notificationDisplay";
|
} from "../../lib/notificationDisplay";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
import {
|
import {
|
||||||
getNotificationMessage,
|
getNotificationMessage,
|
||||||
getNotificationTitle,
|
getNotificationTitle,
|
||||||
type Notification,
|
type Notification,
|
||||||
} from "../../types/notification.types";
|
} from "../../types/notification.types";
|
||||||
import { cn } from "../../lib/utils";
|
import { Badge } from "../ui/badge";
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
import { Button } from "../ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
|
||||||
|
import { SpinnerIcon } from "../ui/spinner-icon";
|
||||||
|
|
||||||
type NotificationDetailDialogProps = {
|
type NotificationDetailDialogProps = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
|
|
@ -150,8 +150,6 @@ export function NotificationDetailDialog({
|
||||||
) : (
|
) : (
|
||||||
<PreviewTab
|
<PreviewTab
|
||||||
notification={notification}
|
notification={notification}
|
||||||
config={config}
|
|
||||||
Icon={Icon}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -249,12 +247,8 @@ function DetailsTab({
|
||||||
|
|
||||||
function PreviewTab({
|
function PreviewTab({
|
||||||
notification,
|
notification,
|
||||||
config,
|
|
||||||
Icon,
|
|
||||||
}: {
|
}: {
|
||||||
notification: Notification;
|
notification: Notification;
|
||||||
config: { bg: string; color: string };
|
|
||||||
Icon: React.ComponentType<{ className?: string }>;
|
|
||||||
}) {
|
}) {
|
||||||
const title = getNotificationTitle(notification) || "Notification";
|
const title = getNotificationTitle(notification) || "Notification";
|
||||||
const message = getNotificationMessage(notification) || "";
|
const message = getNotificationMessage(notification) || "";
|
||||||
|
|
|
||||||
|
|
@ -154,9 +154,9 @@ const SUBSCRIPTION_STATUS_OPTIONS = [
|
||||||
]
|
]
|
||||||
|
|
||||||
const PLAN_CATEGORY_OPTIONS = [
|
const PLAN_CATEGORY_OPTIONS = [
|
||||||
{ code: "LEARN_ENGLISH", label: "Learn English" },
|
{ code: "LEARN_ENGLISH", label: "Legacy: Learn English" },
|
||||||
{ code: "IELTS", label: "IELTS" },
|
{ code: "IELTS", label: "Legacy: IELTS" },
|
||||||
{ code: "DUOLINGO", label: "Duolingo" },
|
{ code: "DUOLINGO", label: "Legacy: Duolingo" },
|
||||||
]
|
]
|
||||||
|
|
||||||
const BOOL_OPTIONS = [
|
const BOOL_OPTIONS = [
|
||||||
|
|
@ -307,7 +307,7 @@ export function PlatformAudienceFilterPanel({
|
||||||
/>
|
/>
|
||||||
<FilterDropdown
|
<FilterDropdown
|
||||||
id="audience-language-goal"
|
id="audience-language-goal"
|
||||||
label="Language goal"
|
label="Artistry focus"
|
||||||
value={filters.languageGoal}
|
value={filters.languageGoal}
|
||||||
allLabel="Any language goal"
|
allLabel="Any language goal"
|
||||||
options={PROFILE_FILTER_LANGUAGE_GOALS}
|
options={PROFILE_FILTER_LANGUAGE_GOALS}
|
||||||
|
|
|
||||||
|
|
@ -239,7 +239,7 @@ export function Sidebar({
|
||||||
Admin workspace
|
Admin workspace
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-0.5 truncate text-xs font-semibold text-grayScale-600">
|
<p className="mt-0.5 truncate text-xs font-semibold text-grayScale-600">
|
||||||
Learning operations
|
Makeup artistry academy
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-grayScale-100 text-[10px] font-bold tracking-wide text-grayScale-500 dark:bg-white/5 dark:text-grayScale-300">
|
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-grayScale-100 text-[10px] font-bold tracking-wide text-grayScale-500 dark:bg-white/5 dark:text-grayScale-300">
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
|
import { useTheme } from "../../contexts/ThemeContext.shared"
|
||||||
import { BrandLogo } from "../brand/BrandLogo"
|
import { BrandLogo } from "../brand/BrandLogo"
|
||||||
import { useTheme } from "../../contexts/ThemeContext"
|
|
||||||
|
|
||||||
type SidebarLogoProps = {
|
type SidebarLogoProps = {
|
||||||
collapsed: boolean
|
collapsed: boolean
|
||||||
|
|
|
||||||
|
|
@ -1,33 +1,33 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
|
||||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Badge } from "../ui/badge"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { SpinnerIcon } from "../ui/spinner-icon"
|
|
||||||
import { ToggleSwitch } from "../ui/toggle-switch"
|
|
||||||
import { resolveNotificationDetail } from "../../api/notifications.api"
|
import { resolveNotificationDetail } from "../../api/notifications.api"
|
||||||
import { useNotifications } from "../../hooks/useNotifications"
|
import { useNotifications } from "../../hooks/useNotifications"
|
||||||
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
import { showNotificationRealtimePopup } from "../notifications/showNotificationRealtimePopup"
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||||
formatNotificationTimestamp,
|
|
||||||
NOTIFICATION_TYPE_CONFIG,
|
NOTIFICATION_TYPE_CONFIG,
|
||||||
|
formatNotificationTimestamp,
|
||||||
} from "../../lib/notificationDisplay"
|
} from "../../lib/notificationDisplay"
|
||||||
import {
|
import {
|
||||||
getNotificationPopupEnabled,
|
|
||||||
NOTIFICATION_POPUP_PREFERENCE_EVENT,
|
NOTIFICATION_POPUP_PREFERENCE_EVENT,
|
||||||
|
getNotificationPopupEnabled,
|
||||||
setNotificationPopupEnabled,
|
setNotificationPopupEnabled,
|
||||||
} from "../../lib/notificationPopupPreference"
|
} from "../../lib/notificationPopupPreference"
|
||||||
import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket"
|
import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
import {
|
import {
|
||||||
getNotificationMessage,
|
getNotificationMessage,
|
||||||
getNotificationTitle,
|
getNotificationTitle,
|
||||||
hasNotificationContent,
|
hasNotificationContent,
|
||||||
type Notification,
|
type Notification,
|
||||||
} from "../../types/notification.types"
|
} from "../../types/notification.types"
|
||||||
|
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
||||||
|
import { showNotificationRealtimePopup } from "../notifications/showNotificationRealtimePopup"
|
||||||
|
import { Badge } from "../ui/badge"
|
||||||
|
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||||
|
import { ToggleSwitch } from "../ui/toggle-switch"
|
||||||
|
|
||||||
const SLIDE_OUT_MS = 360
|
const SLIDE_OUT_MS = 360
|
||||||
const DELETE_UNDO_MS = 5000
|
const DELETE_UNDO_MS = 5000
|
||||||
|
|
@ -58,18 +58,17 @@ function NotificationItem({
|
||||||
const [slideOut, setSlideOut] = useState(false)
|
const [slideOut, setSlideOut] = useState(false)
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!isDismissing) {
|
if (!isDismissing) return
|
||||||
setSlideOut(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const el = slideRef.current
|
const el = slideRef.current
|
||||||
if (!el) return
|
if (!el) return
|
||||||
|
|
||||||
setSlideOut(false)
|
|
||||||
void el.offsetHeight
|
void el.offsetHeight
|
||||||
const frame = requestAnimationFrame(() => setSlideOut(true))
|
const frame = requestAnimationFrame(() => setSlideOut(true))
|
||||||
return () => cancelAnimationFrame(frame)
|
return () => {
|
||||||
|
cancelAnimationFrame(frame)
|
||||||
|
setSlideOut(false)
|
||||||
|
}
|
||||||
}, [isDismissing])
|
}, [isDismissing])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -78,7 +77,7 @@ function NotificationItem({
|
||||||
ref={slideRef}
|
ref={slideRef}
|
||||||
className={cn(
|
className={cn(
|
||||||
"w-full will-change-transform transition-[transform,opacity] duration-300 ease-in-out",
|
"w-full will-change-transform transition-[transform,opacity] duration-300 ease-in-out",
|
||||||
slideOut ? "-translate-x-full opacity-0" : "translate-x-0 opacity-100",
|
isDismissing && slideOut ? "-translate-x-full opacity-0" : "translate-x-0 opacity-100",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
|
|
@ -212,7 +211,7 @@ export function NotificationDropdown() {
|
||||||
setSelectedNotification(null)
|
setSelectedNotification(null)
|
||||||
setSelectedNotificationId(null)
|
setSelectedNotificationId(null)
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (err) {
|
||||||
setHiddenIds((prev) => {
|
setHiddenIds((prev) => {
|
||||||
const next = new Set(prev)
|
const next = new Set(prev)
|
||||||
next.delete(pending.notification.id)
|
next.delete(pending.notification.id)
|
||||||
|
|
@ -285,7 +284,7 @@ export function NotificationDropdown() {
|
||||||
if (markReadIfNeeded && !resolved.is_read) {
|
if (markReadIfNeeded && !resolved.is_read) {
|
||||||
void markOneRead(resolved.id)
|
void markOneRead(resolved.id)
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (err) {
|
||||||
if (hasNotificationContent(notification)) {
|
if (hasNotificationContent(notification)) {
|
||||||
setSelectedNotification(notification)
|
setSelectedNotification(notification)
|
||||||
if (markReadIfNeeded && !notification.is_read) {
|
if (markReadIfNeeded && !notification.is_read) {
|
||||||
|
|
@ -349,16 +348,24 @@ export function NotificationDropdown() {
|
||||||
setOpen(false)
|
setOpen(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") setOpen(false)
|
||||||
|
}
|
||||||
if (open) {
|
if (open) {
|
||||||
document.addEventListener("mousedown", handleMouseDown)
|
document.addEventListener("mousedown", handleMouseDown)
|
||||||
|
document.addEventListener("keydown", handleKeyDown)
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousedown", handleMouseDown)
|
||||||
|
document.removeEventListener("keydown", handleKeyDown)
|
||||||
}
|
}
|
||||||
return () => document.removeEventListener("mousedown", handleMouseDown)
|
|
||||||
}, [open])
|
}, [open])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const slideTimers = slideTimersRef.current
|
||||||
return () => {
|
return () => {
|
||||||
slideTimersRef.current.forEach((timer) => clearTimeout(timer))
|
slideTimers.forEach((timer) => clearTimeout(timer))
|
||||||
slideTimersRef.current.clear()
|
slideTimers.clear()
|
||||||
const current = pendingDeleteRef.current
|
const current = pendingDeleteRef.current
|
||||||
if (current) clearTimeout(current.timeoutId)
|
if (current) clearTimeout(current.timeoutId)
|
||||||
pendingDeleteRef.current = null
|
pendingDeleteRef.current = null
|
||||||
|
|
@ -374,6 +381,7 @@ export function NotificationDropdown() {
|
||||||
type="button"
|
type="button"
|
||||||
className="relative grid h-10 w-10 place-items-center rounded-full border bg-white text-grayScale-500 transition-colors hover:text-brand-600"
|
className="relative grid h-10 w-10 place-items-center rounded-full border bg-white text-grayScale-500 transition-colors hover:text-brand-600"
|
||||||
aria-label="Notifications"
|
aria-label="Notifications"
|
||||||
|
aria-expanded={open}
|
||||||
onClick={() => setOpen((prev) => !prev)}
|
onClick={() => setOpen((prev) => !prev)}
|
||||||
>
|
>
|
||||||
<Bell className="h-5 w-5" />
|
<Bell className="h-5 w-5" />
|
||||||
|
|
|
||||||
|
|
@ -1,122 +1,143 @@
|
||||||
"use client"
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react"
|
|
||||||
import { useNavigate } from "react-router-dom"
|
|
||||||
import { LogOut, Menu, Settings, UserCircle2 } from "lucide-react"
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar"
|
|
||||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
||||||
import { cn } from "../../lib/utils"
|
import { ArrowUpRight, CalendarDays, ChevronDown, ChevronRight, LogOut, Menu, Paintbrush, Search, Settings, UserCircle2 } from "lucide-react"
|
||||||
import { NotificationDropdown } from "./NotificationDropdown"
|
import { useEffect, useState } from "react"
|
||||||
|
import { useLocation, useNavigate } from "react-router-dom"
|
||||||
|
import { isPathAllowedForTeamRole } from "../../lib/adminAccess"
|
||||||
|
import { TEAM_SESSION_UPDATED_EVENT } from "../../lib/teamAuthStorage"
|
||||||
|
import { getNormalizedSessionTeamRole } from "../../lib/teamRole"
|
||||||
import { FullPanelOnly } from "../access/AdminAccessGates"
|
import { FullPanelOnly } from "../access/AdminAccessGates"
|
||||||
|
import { Avatar, AvatarFallback } from "../ui/avatar"
|
||||||
|
import { NotificationDropdown } from "./NotificationDropdown"
|
||||||
|
|
||||||
type TopbarProps = {
|
const destinations = [
|
||||||
onSidebarToggle: () => void
|
{ label: "Dashboard", path: "/dashboard" },
|
||||||
|
{ label: "Analytics", path: "/analytics" },
|
||||||
|
{ label: "Learners", path: "/users/list" },
|
||||||
|
{ label: "Courses", path: "/new-content/courses" },
|
||||||
|
{ label: "Question types", path: "/new-content/question-types" },
|
||||||
|
{ label: "Question bank", path: "/content/questions" },
|
||||||
|
{ label: "Team members", path: "/team" },
|
||||||
|
{ label: "Personas", path: "/personas" },
|
||||||
|
{ label: "Payments", path: "/payments" },
|
||||||
|
{ label: "Activity log", path: "/user-log" },
|
||||||
|
{ label: "App reviews", path: "/app-reviews" },
|
||||||
|
{ label: "Notifications", path: "/notifications" },
|
||||||
|
{ label: "Settings", path: "/settings" },
|
||||||
|
{ label: "Profile", path: "/profile" },
|
||||||
|
]
|
||||||
|
|
||||||
|
function readAccount() {
|
||||||
|
const first = localStorage.getItem("user_first_name")?.trim() ?? ""
|
||||||
|
const last = localStorage.getItem("user_last_name")?.trim() ?? ""
|
||||||
|
return {
|
||||||
|
name: [first, last].filter(Boolean).join(" ") || "Your account",
|
||||||
|
initials: (first.charAt(0) + last.charAt(0)).toUpperCase() || "RA",
|
||||||
|
role: (getNormalizedSessionTeamRole() || "Team member").replaceAll("_", " ").toLowerCase(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Topbar({ onSidebarToggle }: TopbarProps) {
|
export function Topbar({ onSidebarToggle }: { onSidebarToggle: () => void }) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [shortName, setShortName] = useState("AA")
|
const { pathname } = useLocation()
|
||||||
|
const [account, setAccount] = useState(readAccount)
|
||||||
|
const [search, setSearch] = useState("")
|
||||||
|
const [searchOpen, setSearchOpen] = useState(false)
|
||||||
|
const pageTitle = destinations
|
||||||
|
.filter(item => pathname === item.path || pathname.startsWith(item.path + "/"))
|
||||||
|
.sort((a, b) => b.path.length - a.path.length)[0]?.label
|
||||||
|
?? (pathname.startsWith("/users") ? "Learners" : pathname.startsWith("/new-content") || pathname.startsWith("/content") ? "Learning content" : "Academy workspace")
|
||||||
|
const matches = destinations.filter(item =>
|
||||||
|
isPathAllowedForTeamRole(item.path, getNormalizedSessionTeamRole()) &&
|
||||||
|
item.label.toLowerCase().includes(search.trim().toLowerCase()),
|
||||||
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const updateShortName = () => {
|
const update = () => setAccount(readAccount())
|
||||||
const first = localStorage.getItem("user_first_name") ?? "A"
|
window.addEventListener("user-profile-updated", update)
|
||||||
const last = localStorage.getItem("user_last_name") ?? "A"
|
window.addEventListener(TEAM_SESSION_UPDATED_EVENT, update)
|
||||||
setShortName(first.charAt(0).toUpperCase() + last.charAt(0).toUpperCase())
|
window.addEventListener("storage", update)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("user-profile-updated", update)
|
||||||
|
window.removeEventListener(TEAM_SESSION_UPDATED_EVENT, update)
|
||||||
|
window.removeEventListener("storage", update)
|
||||||
}
|
}
|
||||||
|
|
||||||
updateShortName()
|
|
||||||
|
|
||||||
window.addEventListener("user-profile-updated", updateShortName)
|
|
||||||
return () => window.removeEventListener("user-profile-updated", updateShortName)
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const handleOptionClick = (option: string) => {
|
const openPage = (path: string) => {
|
||||||
switch (option) {
|
setSearch("")
|
||||||
case "profile":
|
setSearchOpen(false)
|
||||||
navigate("/profile")
|
navigate(path)
|
||||||
break
|
|
||||||
case "settings":
|
|
||||||
navigate("/settings")
|
|
||||||
break
|
|
||||||
case "logout":
|
|
||||||
localStorage.clear()
|
|
||||||
window.location.href = "/login"
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="z-40 flex h-16 shrink-0 items-center justify-between gap-3 border-b bg-grayScale-50/85 px-4 backdrop-blur lg:justify-end lg:px-6">
|
<header className="studio-topbar relative z-40 shrink-0 border-b">
|
||||||
{/* Sidebar toggle */}
|
<div className="flex min-h-[76px] items-center justify-between gap-3 px-4 sm:px-6 lg:px-8">
|
||||||
<button
|
<div className="flex min-w-0 items-center gap-3">
|
||||||
type="button"
|
<button type="button" onClick={onSidebarToggle} aria-label="Open menu" className="studio-header-control lg:hidden">
|
||||||
className="grid h-10 w-10 place-items-center rounded-full border bg-white text-grayScale-500 transition-colors hover:text-brand-600 lg:hidden"
|
<Menu className="h-5 w-5" />
|
||||||
onClick={onSidebarToggle}
|
</button>
|
||||||
aria-label="Open menu"
|
<span className="studio-header-emblem hidden h-11 w-11 shrink-0 items-center justify-center rounded-2xl sm:flex" aria-hidden="true">
|
||||||
>
|
<Paintbrush className="h-5 w-5" strokeWidth={1.5} />
|
||||||
<Menu className="h-5 w-5" />
|
</span>
|
||||||
</button>
|
<div className="min-w-0">
|
||||||
|
<p className="mb-0.5 truncate text-[9px] font-semibold uppercase tracking-[0.2em] text-grayScale-500">The beauty academy</p>
|
||||||
|
<p className="truncate font-display text-[27px] font-semibold leading-none text-foreground sm:text-[30px]">{pageTitle}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex shrink-0 items-center gap-2 sm:gap-4">
|
||||||
<NotificationDropdown />
|
<div className="studio-header-notifications"><NotificationDropdown /></div>
|
||||||
|
<span className="hidden h-7 w-px bg-border sm:block" aria-hidden="true" />
|
||||||
|
<DropdownMenu.Root>
|
||||||
|
<DropdownMenu.Trigger asChild>
|
||||||
|
<button type="button" aria-label="Account menu" className="studio-account flex max-w-[240px] items-center gap-3 rounded-md p-1.5 text-left sm:pr-3">
|
||||||
|
<Avatar className="h-9 w-9 shrink-0 border border-white/20">
|
||||||
|
<AvatarFallback className="bg-brand-100 text-xs font-semibold text-brand-600">{account.initials}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<span className="hidden min-w-0 sm:block">
|
||||||
|
<span className="block truncate text-xs font-semibold">{account.name}</span>
|
||||||
|
<span className="mt-0.5 block truncate text-[10px] capitalize opacity-70">{account.role}</span>
|
||||||
|
</span>
|
||||||
|
<ChevronDown className="hidden h-3.5 w-3.5 shrink-0 opacity-70 sm:block" />
|
||||||
|
</button>
|
||||||
|
</DropdownMenu.Trigger>
|
||||||
|
<DropdownMenu.Portal>
|
||||||
|
<DropdownMenu.Content side="bottom" align="end" sideOffset={10} collisionPadding={12} className="studio-account-menu z-50 w-60 rounded-2xl border bg-popover p-2 text-popover-foreground shadow-xl">
|
||||||
|
<DropdownMenu.Label className="mb-1 border-b px-3 pb-3 pt-2">
|
||||||
|
<span className="block truncate text-sm font-semibold">{account.name}</span>
|
||||||
|
<span className="mt-1 block text-[11px] font-normal capitalize text-grayScale-500">{account.role}</span>
|
||||||
|
</DropdownMenu.Label>
|
||||||
|
<DropdownMenu.Item className="studio-account-item" onSelect={() => openPage("/profile")}><UserCircle2 className="h-4 w-4" />My profile<ArrowUpRight className="ml-auto h-3.5 w-3.5 opacity-50" /></DropdownMenu.Item>
|
||||||
|
<FullPanelOnly>
|
||||||
|
<DropdownMenu.Item className="studio-account-item" onSelect={() => openPage("/settings")}><Settings className="h-4 w-4" />Settings</DropdownMenu.Item>
|
||||||
|
</FullPanelOnly>
|
||||||
|
<DropdownMenu.Separator className="my-1 h-px bg-border" />
|
||||||
|
<DropdownMenu.Item className="studio-account-item text-destructive" onSelect={() => { localStorage.clear(); window.location.href = "/login" }}><LogOut className="h-4 w-4" />Sign out</DropdownMenu.Item>
|
||||||
|
</DropdownMenu.Content>
|
||||||
|
</DropdownMenu.Portal>
|
||||||
|
</DropdownMenu.Root>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="h-6 w-px bg-grayScale-200" />
|
<div className="studio-header-toolbar flex min-h-[54px] items-center justify-between gap-4 px-4 pb-3 sm:px-6 lg:px-8">
|
||||||
|
<div className="hidden min-w-0 items-center gap-2 text-[11px] text-grayScale-500 md:flex" aria-label="Current section">
|
||||||
{/* Avatar + Radix Dropdown */}
|
<span>Academy workspace</span><ChevronRight className="h-3 w-3 shrink-0 text-brand-400" /><span className="truncate font-medium text-brand-600">{pageTitle}</span>
|
||||||
<DropdownMenu.Root>
|
</div>
|
||||||
<DropdownMenu.Trigger asChild>
|
<div className="studio-header-search relative w-full md:ml-auto md:max-w-[340px]" onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget)) setSearchOpen(false) }}>
|
||||||
<button className="focus:outline-none">
|
<form role="search" onSubmit={event => { event.preventDefault(); if (search.trim() && matches[0]) openPage(matches[0].path) }}>
|
||||||
<Avatar className="h-10 w-10 ring-2 ring-brand-100">
|
<label className="studio-search-field flex h-9 items-center gap-2.5 rounded-md border px-3.5">
|
||||||
<AvatarImage src="" alt="Admin" />
|
<Search className="h-3.5 w-3.5 shrink-0 text-brand-500" />
|
||||||
<AvatarFallback className="bg-brand-500 text-sm font-medium text-white">
|
<input type="search" aria-label="Search admin pages" placeholder="Find a page in your academy..." value={search} onFocus={() => setSearchOpen(true)} onChange={event => { setSearch(event.target.value); setSearchOpen(true) }} onKeyDown={event => { if (event.key === "Escape") { setSearch(""); setSearchOpen(false) } }} className="w-full min-w-0 bg-transparent text-xs outline-none placeholder:text-grayScale-400" />
|
||||||
{shortName}
|
</label>
|
||||||
</AvatarFallback>
|
</form>
|
||||||
</Avatar>
|
{searchOpen && search.trim() && (
|
||||||
</button>
|
<div className="absolute left-0 right-0 top-11 z-50 max-h-[min(360px,50dvh)] overflow-y-auto rounded-2xl border bg-popover p-1.5 shadow-xl" aria-label="Matching pages">
|
||||||
</DropdownMenu.Trigger>
|
<p className="px-3 py-2 text-[9px] font-semibold uppercase tracking-[0.12em] text-grayScale-400">Go to a page</p>
|
||||||
|
{matches.length ? matches.map(item => <button type="button" key={item.path} onClick={() => openPage(item.path)} className="flex w-full items-center justify-between rounded-xl px-3 py-2.5 text-left text-xs outline-none hover:bg-brand-50 focus-visible:bg-brand-50">{item.label}<ArrowUpRight className="h-3 w-3 text-brand-400" /></button>) : <p className="px-3 py-3 text-xs text-grayScale-500">No matching pages</p>}
|
||||||
<DropdownMenu.Content
|
</div>
|
||||||
side="bottom"
|
)}
|
||||||
align="end"
|
</div>
|
||||||
className="z-50 w-48 rounded-lg bg-white p-2 shadow-lg ring-1 ring-black ring-opacity-5"
|
<span className="hidden shrink-0 items-center gap-2 text-[11px] text-grayScale-500 xl:flex"><CalendarDays className="h-3.5 w-3.5 text-brand-500" />{new Date().toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })}</span>
|
||||||
>
|
|
||||||
<DropdownMenu.Item
|
|
||||||
className={cn(
|
|
||||||
"group flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-grayScale-600 hover:bg-grayScale-100 hover:text-brand-600"
|
|
||||||
)}
|
|
||||||
onClick={() => handleOptionClick("profile")}
|
|
||||||
>
|
|
||||||
<span className="grid h-8 w-8 place-items-center rounded-lg bg-grayScale-100 text-grayScale-500 group-hover:bg-brand-100 group-hover:text-brand-600">
|
|
||||||
<UserCircle2 className="h-4 w-4" />
|
|
||||||
</span>
|
|
||||||
Profile
|
|
||||||
</DropdownMenu.Item>
|
|
||||||
<FullPanelOnly>
|
|
||||||
<DropdownMenu.Item
|
|
||||||
className={cn(
|
|
||||||
"group flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-grayScale-600 hover:bg-grayScale-100 hover:text-brand-600"
|
|
||||||
)}
|
|
||||||
onClick={() => handleOptionClick("settings")}
|
|
||||||
>
|
|
||||||
<span className="grid h-8 w-8 place-items-center rounded-lg bg-grayScale-100 text-grayScale-500 group-hover:bg-brand-100 group-hover:text-brand-600">
|
|
||||||
<Settings className="h-4 w-4" />
|
|
||||||
</span>
|
|
||||||
Settings
|
|
||||||
</DropdownMenu.Item>
|
|
||||||
</FullPanelOnly>
|
|
||||||
<DropdownMenu.Item
|
|
||||||
className={cn(
|
|
||||||
"group flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-grayScale-600 hover:bg-grayScale-100 hover:text-brand-600"
|
|
||||||
)}
|
|
||||||
onClick={() => handleOptionClick("logout")}
|
|
||||||
>
|
|
||||||
<span className="grid h-8 w-8 place-items-center rounded-lg bg-grayScale-100 text-grayScale-500 group-hover:bg-brand-100 group-hover:text-brand-600">
|
|
||||||
<LogOut className="h-4 w-4" />
|
|
||||||
</span>
|
|
||||||
Logout
|
|
||||||
</DropdownMenu.Item>
|
|
||||||
</DropdownMenu.Content>
|
|
||||||
</DropdownMenu.Root>
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ const badgeVariants = cva(
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
|
outline: "border-grayScale-200 text-grayScale-600",
|
||||||
default: "border-transparent bg-primary text-primary-foreground",
|
default: "border-transparent bg-primary text-primary-foreground",
|
||||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||||
warning: "border-transparent bg-gold-600 text-white",
|
warning: "border-transparent bg-gold-600 text-white",
|
||||||
|
|
|
||||||
29
src/components/ui/button.shared.ts
Normal file
29
src/components/ui/button.shared.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
|
||||||
|
export const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "ui-3d-button bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
brand: "ui-3d-button bg-brand-500 text-white hover:bg-brand-600 hover:text-white",
|
||||||
|
secondary: "ui-3d-button bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
outline: "ui-3d-button border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||||
|
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||||
|
destructive: "ui-3d-button bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-10 px-4 py-2",
|
||||||
|
sm: "h-9 px-3",
|
||||||
|
lg: "h-11 px-6",
|
||||||
|
icon: "h-10 w-10",
|
||||||
|
"icon-sm": "h-8 w-8",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
@ -1,36 +1,10 @@
|
||||||
import * as React from "react"
|
|
||||||
import { Slot } from "@radix-ui/react-slot"
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { type VariantProps } from "class-variance-authority"
|
||||||
|
import * as React from "react"
|
||||||
|
import { buttonVariants } from "./button.shared"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const buttonVariants = cva(
|
|
||||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
|
|
||||||
{
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "ui-3d-button bg-primary text-primary-foreground hover:bg-primary/90",
|
|
||||||
brand: "ui-3d-button bg-brand-500 text-white hover:bg-brand-600 hover:text-white",
|
|
||||||
secondary: "ui-3d-button bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
|
||||||
outline: "ui-3d-button border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
|
||||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
|
||||||
destructive: "ui-3d-button bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
|
||||||
},
|
|
||||||
size: {
|
|
||||||
default: "h-10 px-4 py-2",
|
|
||||||
sm: "h-9 px-3",
|
|
||||||
lg: "h-11 px-6",
|
|
||||||
icon: "h-10 w-10",
|
|
||||||
"icon-sm": "h-8 w-8",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
size: "default",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
export interface ButtonProps
|
export interface ButtonProps
|
||||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||||
VariantProps<typeof buttonVariants> {
|
VariantProps<typeof buttonVariants> {
|
||||||
|
|
@ -51,6 +25,4 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
)
|
)
|
||||||
Button.displayName = "Button"
|
Button.displayName = "Button"
|
||||||
|
|
||||||
export { buttonVariants }
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import * as React from "react";
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
|
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>
|
||||||
|
|
||||||
export const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
export const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||||
({ className, type, ...props }, ref) => {
|
({ className, type, ...props }, ref) => {
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import * as React from "react";
|
|
||||||
import { ChevronDown } from "lucide-react";
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ChevronDown } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
|
||||||
export interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {}
|
export type SelectProps = React.SelectHTMLAttributes<HTMLSelectElement>
|
||||||
|
|
||||||
export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
|
export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
|
||||||
({ className, children, ...props }, ref) => {
|
({ className, children, ...props }, ref) => {
|
||||||
|
|
|
||||||
27
src/components/ui/sensitive-value.shared.ts
Normal file
27
src/components/ui/sensitive-value.shared.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useState
|
||||||
|
} from "react"
|
||||||
|
|
||||||
|
export type SensitiveRevealContextValue = {
|
||||||
|
revealed: boolean
|
||||||
|
toggle: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SensitiveRevealContext = createContext<SensitiveRevealContextValue | null>(null)
|
||||||
|
|
||||||
|
export function useSensitiveReveal() {
|
||||||
|
const ctx = useContext(SensitiveRevealContext)
|
||||||
|
const [localRevealed, setLocalRevealed] = useState(false)
|
||||||
|
const toggleLocal = useCallback(() => setLocalRevealed((v) => !v), [])
|
||||||
|
|
||||||
|
if (ctx) return ctx
|
||||||
|
|
||||||
|
return {
|
||||||
|
revealed: localRevealed,
|
||||||
|
toggle: toggleLocal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,19 +1,11 @@
|
||||||
import {
|
|
||||||
createContext,
|
|
||||||
useCallback,
|
|
||||||
useContext,
|
|
||||||
useState,
|
|
||||||
type ReactNode,
|
|
||||||
} from "react"
|
|
||||||
import { Eye, EyeOff } from "lucide-react"
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Eye, EyeOff } from "lucide-react"
|
||||||
type SensitiveRevealContextValue = {
|
import {
|
||||||
revealed: boolean
|
useCallback,
|
||||||
toggle: () => void
|
useState,
|
||||||
}
|
type ReactNode
|
||||||
|
} from "react"
|
||||||
const SensitiveRevealContext = createContext<SensitiveRevealContextValue | null>(null)
|
import { SensitiveRevealContext, useSensitiveReveal } from "./sensitive-value.shared"
|
||||||
|
|
||||||
export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
||||||
const [revealed, setRevealed] = useState(false)
|
const [revealed, setRevealed] = useState(false)
|
||||||
|
|
@ -26,19 +18,6 @@ export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSensitiveReveal() {
|
|
||||||
const ctx = useContext(SensitiveRevealContext)
|
|
||||||
const [localRevealed, setLocalRevealed] = useState(false)
|
|
||||||
const toggleLocal = useCallback(() => setLocalRevealed((v) => !v), [])
|
|
||||||
|
|
||||||
if (ctx) return ctx
|
|
||||||
|
|
||||||
return {
|
|
||||||
revealed: localRevealed,
|
|
||||||
toggle: toggleLocal,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SensitiveRevealToggle({
|
export function SensitiveRevealToggle({
|
||||||
className,
|
className,
|
||||||
label = "revenue",
|
label = "revenue",
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ type TableProps = React.HTMLAttributes<HTMLTableElement> & {
|
||||||
export const Table = React.forwardRef<HTMLTableElement, TableProps>(
|
export const Table = React.forwardRef<HTMLTableElement, TableProps>(
|
||||||
({ className, noWrapper = false, ...props }, ref) => {
|
({ className, noWrapper = false, ...props }, ref) => {
|
||||||
const table = (
|
const table = (
|
||||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
<table ref={ref} className={cn("admin-data-table w-full caption-bottom text-sm", className)} {...props} />
|
||||||
)
|
)
|
||||||
if (noWrapper) return table
|
if (noWrapper) return table
|
||||||
return <div className="relative w-full min-w-0 overflow-auto overscroll-x-contain [-webkit-overflow-scrolling:touch]">{table}</div>
|
return <div className="relative w-full min-w-0 overflow-auto overscroll-x-contain [-webkit-overflow-scrolling:touch]">{table}</div>
|
||||||
|
|
@ -53,7 +53,7 @@ export const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttr
|
||||||
({ className, ...props }, ref) => (
|
({ className, ...props }, ref) => (
|
||||||
<th
|
<th
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn("h-11 px-3 text-left align-middle text-xs font-semibold text-grayScale-500 sm:px-4 [&:has([role=checkbox])]:pr-0", className)}
|
className={cn("h-12 px-3 text-left align-middle text-[11px] font-semibold uppercase tracking-[0.07em] text-grayScale-500 sm:px-4 [&:has([role=checkbox])]:pr-0", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import * as React from "react"
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
import * as React from "react"
|
||||||
|
|
||||||
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
|
||||||
|
|
||||||
export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||||
({ className, ...props }, ref) => {
|
({ className, ...props }, ref) => {
|
||||||
|
|
|
||||||
32
src/contexts/ThemeContext.shared.ts
Normal file
32
src/contexts/ThemeContext.shared.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useContext
|
||||||
|
} from "react"
|
||||||
|
import {
|
||||||
|
getSystemTheme,
|
||||||
|
type ResolvedTheme,
|
||||||
|
type ThemeMode
|
||||||
|
} from "../lib/theme"
|
||||||
|
|
||||||
|
export type ThemeContextValue = {
|
||||||
|
theme: ThemeMode
|
||||||
|
resolvedTheme: ResolvedTheme
|
||||||
|
systemTheme: ResolvedTheme
|
||||||
|
setTheme: (mode: ThemeMode) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ThemeContext = createContext<ThemeContextValue | null>(null)
|
||||||
|
|
||||||
|
export function useTheme(): ThemeContextValue {
|
||||||
|
const ctx = useContext(ThemeContext)
|
||||||
|
if (!ctx) {
|
||||||
|
throw new Error("useTheme must be used within ThemeProvider")
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useThemeOptional(): ThemeContextValue | null {
|
||||||
|
return useContext(ThemeContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { getSystemTheme }
|
||||||
|
|
@ -1,11 +1,9 @@
|
||||||
import {
|
import {
|
||||||
createContext,
|
|
||||||
useCallback,
|
useCallback,
|
||||||
useContext,
|
|
||||||
useEffect,
|
useEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
useState,
|
useState,
|
||||||
type ReactNode,
|
type ReactNode
|
||||||
} from "react"
|
} from "react"
|
||||||
import {
|
import {
|
||||||
applyTheme,
|
applyTheme,
|
||||||
|
|
@ -17,15 +15,7 @@ import {
|
||||||
type ResolvedTheme,
|
type ResolvedTheme,
|
||||||
type ThemeMode,
|
type ThemeMode,
|
||||||
} from "../lib/theme"
|
} from "../lib/theme"
|
||||||
|
import { ThemeContext } from "./ThemeContext.shared"
|
||||||
type ThemeContextValue = {
|
|
||||||
theme: ThemeMode
|
|
||||||
resolvedTheme: ResolvedTheme
|
|
||||||
systemTheme: ResolvedTheme
|
|
||||||
setTheme: (mode: ThemeMode) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
const ThemeContext = createContext<ThemeContextValue | null>(null)
|
|
||||||
|
|
||||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
const [theme, setThemeState] = useState<ThemeMode>(() => getStoredTheme())
|
const [theme, setThemeState] = useState<ThemeMode>(() => getStoredTheme())
|
||||||
|
|
@ -60,17 +50,3 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
|
||||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useTheme(): ThemeContextValue {
|
|
||||||
const ctx = useContext(ThemeContext)
|
|
||||||
if (!ctx) {
|
|
||||||
throw new Error("useTheme must be used within ThemeProvider")
|
|
||||||
}
|
|
||||||
return ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useThemeOptional(): ThemeContextValue | null {
|
|
||||||
return useContext(ThemeContext)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { getSystemTheme }
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
import { useCallback, useMemo, useState } from "react"
|
||||||
import type { ParentContextPractice } from "../types/course.types"
|
import type { ParentContextPractice } from "../types/course.types"
|
||||||
|
|
||||||
export function usePracticeListSelection(
|
export function usePracticeListSelection(
|
||||||
|
|
@ -11,14 +11,17 @@ export function usePracticeListSelection(
|
||||||
[visiblePractices],
|
[visiblePractices],
|
||||||
)
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
const visibleKey = [...visibleIds].join(",")
|
||||||
|
const [previousVisibleKey, setPreviousVisibleKey] = useState(visibleKey)
|
||||||
|
if (previousVisibleKey !== visibleKey) {
|
||||||
|
setPreviousVisibleKey(visibleKey)
|
||||||
setSelectedIds((prev) => {
|
setSelectedIds((prev) => {
|
||||||
const next = new Set(
|
const next = new Set(
|
||||||
[...prev].filter((id) => visibleIds.has(id)),
|
[...prev].filter((id) => visibleIds.has(id)),
|
||||||
)
|
)
|
||||||
return next.size === prev.size ? prev : next
|
return next.size === prev.size ? prev : next
|
||||||
})
|
})
|
||||||
}, [visibleIds])
|
}
|
||||||
|
|
||||||
const selectedPractices = useMemo(
|
const selectedPractices = useMemo(
|
||||||
() => visiblePractices.filter((practice) => selectedIds.has(practice.id)),
|
() => visiblePractices.filter((practice) => selectedIds.has(practice.id)),
|
||||||
|
|
|
||||||
|
|
@ -7,45 +7,25 @@ import {
|
||||||
type PracticeParentTitleMap,
|
type PracticeParentTitleMap,
|
||||||
} from "../lib/practiceParentTitles"
|
} from "../lib/practiceParentTitles"
|
||||||
|
|
||||||
export function usePracticeParentTitles(
|
export function usePracticeParentTitles(parents: PracticeParent[], hints?: PracticeParentTitleHints) {
|
||||||
parents: PracticeParent[],
|
const parentsKey = useMemo(() => JSON.stringify(dedupeParents(parents)), [parents])
|
||||||
hints?: PracticeParentTitleHints,
|
const hintsKey = JSON.stringify({
|
||||||
) {
|
courses: hints?.courses ?? {},
|
||||||
const [titles, setTitles] = useState<PracticeParentTitleMap>(() => new Map())
|
modules: hints?.modules ?? {},
|
||||||
const [loading, setLoading] = useState(true)
|
lessons: hints?.lessons ?? {},
|
||||||
|
})
|
||||||
const parentsKey = useMemo(
|
const requestKey = `${parentsKey}:${hintsKey}`
|
||||||
() =>
|
const [result, setResult] = useState<{ key: string; titles: PracticeParentTitleMap }>(() => ({ key: "", titles: new Map() }))
|
||||||
dedupeParents(parents)
|
|
||||||
.map((parent) => `${parent.parent_kind}:${parent.parent_id}`)
|
|
||||||
.sort()
|
|
||||||
.join("|"),
|
|
||||||
[parents],
|
|
||||||
)
|
|
||||||
|
|
||||||
const hintsKey = useMemo(
|
|
||||||
() =>
|
|
||||||
JSON.stringify({
|
|
||||||
courses: hints?.courses ?? {},
|
|
||||||
modules: hints?.modules ?? {},
|
|
||||||
lessons: hints?.lessons ?? {},
|
|
||||||
}),
|
|
||||||
[hints?.courses, hints?.modules, hints?.lessons],
|
|
||||||
)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
setLoading(true)
|
const currentParents: PracticeParent[] = JSON.parse(parentsKey)
|
||||||
void resolvePracticeParentTitles(parents, hints).then((resolved) => {
|
const currentHints: PracticeParentTitleHints = JSON.parse(hintsKey)
|
||||||
if (!cancelled) {
|
void resolvePracticeParentTitles(currentParents, currentHints).then((titles) => {
|
||||||
setTitles(resolved)
|
if (!cancelled) setResult({ key: requestKey, titles })
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
return () => {
|
return () => { cancelled = true }
|
||||||
cancelled = true
|
}, [parentsKey, hintsKey, requestKey])
|
||||||
}
|
|
||||||
}, [parentsKey, hintsKey])
|
|
||||||
|
|
||||||
return { titles, loading }
|
return { titles: result.titles, loading: result.key !== requestKey }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
281
src/index.css
281
src/index.css
|
|
@ -1,4 +1,9 @@
|
||||||
@import "@fontsource/inter/latin.css";
|
@import "@fontsource/dm-sans/latin-400.css";
|
||||||
|
@import "@fontsource/dm-sans/latin-500.css";
|
||||||
|
@import "@fontsource/dm-sans/latin-600.css";
|
||||||
|
@import "@fontsource/dm-sans/latin-700.css";
|
||||||
|
@import "@fontsource/cormorant-garamond/latin-500.css";
|
||||||
|
@import "@fontsource/cormorant-garamond/latin-600.css";
|
||||||
|
|
||||||
@tailwind base;
|
@tailwind base;
|
||||||
@tailwind components;
|
@tailwind components;
|
||||||
|
|
@ -7,94 +12,113 @@
|
||||||
@layer base {
|
@layer base {
|
||||||
html {
|
html {
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
|
--chart-primary: #171717;
|
||||||
|
--brand-50: 250 250 250;
|
||||||
|
--brand-100: 237 237 237;
|
||||||
|
--brand-200: 212 212 212;
|
||||||
--gs-50: #ffffff;
|
--gs-50: #ffffff;
|
||||||
--gs-100: #f5f5f5;
|
--gs-100: #f5f5f5;
|
||||||
--gs-200: #e0e0e0;
|
--gs-200: #e5e5e5;
|
||||||
--gs-300: #bdbdbd;
|
--gs-300: #bdbdbd;
|
||||||
--gs-400: #9e9e9e;
|
--gs-400: #737373;
|
||||||
--gs-500: #757575;
|
--gs-500: #626262;
|
||||||
--gs-600: #616161;
|
--gs-600: #525252;
|
||||||
|
--gs-700: #404040;
|
||||||
|
--gs-800: #262626;
|
||||||
|
--gs-900: #171717;
|
||||||
--shadow-soft: 0 8px 24px rgba(0, 0, 0, 0.06);
|
--shadow-soft: 0 8px 24px rgba(0, 0, 0, 0.06);
|
||||||
--shadow-3d-card: 0 1px 2px rgba(24, 24, 27, 0.04), 0 3px 10px rgba(24, 24, 27, 0.05);
|
--shadow-3d-card: 0 1px 2px rgba(24, 24, 27, 0.04), 0 3px 10px rgba(24, 24, 27, 0.05);
|
||||||
--shadow-3d-button: 0 1px 0 rgba(24, 24, 27, 0.16), 0 2px 5px rgba(24, 24, 27, 0.08);
|
--shadow-3d-button: 0 1px 0 rgba(24, 24, 27, 0.16), 0 2px 5px rgba(24, 24, 27, 0.08);
|
||||||
--surface-highlight: rgba(255, 255, 255, 0.45);
|
--surface-highlight: rgba(255, 255, 255, 0.45);
|
||||||
--control-inset: inset 0 1px 2px rgba(24, 24, 27, 0.04);
|
--control-inset: inset 0 1px 2px rgba(24, 24, 27, 0.04);
|
||||||
|
|
||||||
--background: 0 0% 100%;
|
--background: 0 0% 98%;
|
||||||
--foreground: 240 5.9% 10%;
|
--foreground: 0 0% 9%;
|
||||||
|
|
||||||
--card: 0 0% 100%;
|
--card: 0 0% 100%;
|
||||||
--card-foreground: 240 5.9% 10%;
|
--card-foreground: 0 0% 9%;
|
||||||
|
|
||||||
--popover: 0 0% 100%;
|
--popover: 0 0% 100%;
|
||||||
--popover-foreground: 240 5.9% 10%;
|
--popover-foreground: 0 0% 9%;
|
||||||
|
|
||||||
--primary: 240 3.7% 25%;
|
--primary: 0 0% 4%;
|
||||||
--primary-foreground: 0 0% 100%;
|
--primary-foreground: 0 0% 100%;
|
||||||
|
|
||||||
--secondary: 0 0% 96.1%;
|
--secondary: 0 0% 94%;
|
||||||
--secondary-foreground: 240 5.9% 10%;
|
--secondary-foreground: 0 0% 9%;
|
||||||
|
|
||||||
--muted: 0 0% 96.1%;
|
--muted: 0 0% 95%;
|
||||||
--muted-foreground: 240 3.8% 46.1%;
|
--muted-foreground: 0 0% 40%;
|
||||||
|
|
||||||
--accent: 0 0% 96.1%;
|
--accent: 0 0% 94%;
|
||||||
--accent-foreground: 240 5.9% 10%;
|
--accent-foreground: 0 0% 9%;
|
||||||
|
|
||||||
--destructive: 0 84.2% 60.2%;
|
--destructive: 0 84.2% 60.2%;
|
||||||
--destructive-foreground: 0 0% 100%;
|
--destructive-foreground: 0 0% 100%;
|
||||||
|
|
||||||
--border: 0 0% 89.8%;
|
--border: 0 0% 88%;
|
||||||
--input: 0 0% 89.8%;
|
--input: 0 0% 85%;
|
||||||
--ring: 240 3.7% 25%;
|
--ring: 0 0% 20%;
|
||||||
|
|
||||||
--radius: 14px;
|
--radius: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
html.dark {
|
html.dark {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
--gs-50: #2b2b30;
|
--chart-primary: #e5e5e5;
|
||||||
--gs-100: #18181b;
|
--brand-50: 38 38 38;
|
||||||
--gs-200: #3f3f46;
|
--brand-100: 51 51 51;
|
||||||
--gs-300: #52525b;
|
--brand-200: 82 82 82;
|
||||||
--gs-400: #a1a1aa;
|
--gs-50: #262626;
|
||||||
--gs-500: #d4d4d8;
|
--gs-100: #171717;
|
||||||
--gs-600: #f4f4f5;
|
--gs-200: #404040;
|
||||||
|
--gs-300: #525252;
|
||||||
|
--gs-400: #a3a3a3;
|
||||||
|
--gs-500: #d4d4d4;
|
||||||
|
--gs-600: #f5f5f5;
|
||||||
|
--gs-700: #f5f5f5;
|
||||||
|
--gs-800: #fafafa;
|
||||||
|
--gs-900: #ffffff;
|
||||||
--shadow-soft: 0 8px 24px rgba(0, 0, 0, 0.45);
|
--shadow-soft: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||||
--shadow-3d-card: 0 1px 3px rgba(0, 0, 0, 0.22), 0 4px 12px rgba(0, 0, 0, 0.16);
|
--shadow-3d-card: 0 1px 3px rgba(0, 0, 0, 0.22), 0 4px 12px rgba(0, 0, 0, 0.16);
|
||||||
--shadow-3d-button: 0 1px 0 rgba(0, 0, 0, 0.3), 0 2px 6px rgba(0, 0, 0, 0.18);
|
--shadow-3d-button: 0 1px 0 rgba(0, 0, 0, 0.3), 0 2px 6px rgba(0, 0, 0, 0.18);
|
||||||
--surface-highlight: rgba(255, 255, 255, 0.04);
|
--surface-highlight: rgba(255, 255, 255, 0.04);
|
||||||
--control-inset: inset 0 1px 2px rgba(0, 0, 0, 0.12);
|
--control-inset: inset 0 1px 2px rgba(0, 0, 0, 0.12);
|
||||||
|
|
||||||
--background: 240 5.9% 10%;
|
--background: 0 0% 9%;
|
||||||
--foreground: 0 0% 96%;
|
--foreground: 0 0% 96%;
|
||||||
|
|
||||||
--card: 240 3.7% 15.9%;
|
--card: 0 0% 15%;
|
||||||
--card-foreground: 0 0% 96%;
|
--card-foreground: 0 0% 96%;
|
||||||
|
|
||||||
--popover: 240 3.7% 15.9%;
|
--popover: 0 0% 15%;
|
||||||
--popover-foreground: 0 0% 96%;
|
--popover-foreground: 0 0% 96%;
|
||||||
|
|
||||||
--primary: 0 0% 86%;
|
--primary: 0 0% 86%;
|
||||||
--primary-foreground: 240 5.9% 10%;
|
--primary-foreground: 0 0% 9%;
|
||||||
|
|
||||||
--secondary: 240 3.7% 15.9%;
|
--secondary: 0 0% 15%;
|
||||||
--secondary-foreground: 0 0% 96%;
|
--secondary-foreground: 0 0% 96%;
|
||||||
|
|
||||||
--muted: 240 3.7% 15.9%;
|
--muted: 0 0% 15%;
|
||||||
--muted-foreground: 240 4.9% 83.9%;
|
--muted-foreground: 0 0% 84%;
|
||||||
|
|
||||||
--accent: 240 3.7% 15.9%;
|
--accent: 0 0% 15%;
|
||||||
--accent-foreground: 0 0% 96%;
|
--accent-foreground: 0 0% 96%;
|
||||||
|
|
||||||
--destructive: 0 62% 50%;
|
--destructive: 0 62% 50%;
|
||||||
--destructive-foreground: 0 0% 100%;
|
--destructive-foreground: 0 0% 100%;
|
||||||
|
|
||||||
--border: 240 3.7% 25%;
|
--border: 0 0% 25%;
|
||||||
--input: 240 3.7% 25%;
|
--input: 0 0% 25%;
|
||||||
--ring: 0 0% 86%;
|
--ring: 0 0% 86%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
h1, h2 {
|
||||||
|
font-family: "Cormorant Garamond", Georgia, serif;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
@apply border-border;
|
@apply border-border;
|
||||||
}
|
}
|
||||||
|
|
@ -711,3 +735,186 @@
|
||||||
height: 0;
|
height: 0;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Makeup academy workspace: black accents, neutral surfaces, editorial headings. */
|
||||||
|
@layer components {
|
||||||
|
.admin-app { background: hsl(var(--background)); }
|
||||||
|
.admin-main { background: hsl(var(--background)); }
|
||||||
|
.admin-app > .sidebar-shell { background: #f4f4f4; box-shadow: none; border-color: #e5e5e5; }
|
||||||
|
.admin-app .sidebar-brand-header { background: transparent; border: 0; box-shadow: none; padding: 4px 0 0; }
|
||||||
|
.admin-app .sidebar-workspace-label { background: transparent; border: 0; box-shadow: none; padding-left: 12px; }
|
||||||
|
.admin-app .sidebar-nav-icon { background: transparent; box-shadow: none; }
|
||||||
|
.admin-app .sidebar-nav-item { border-radius: 6px; font-size: 12px; }
|
||||||
|
.admin-app .sidebar-nav-item-active { background: #111111; background-image: none; border-color: transparent; box-shadow: 0 3px 8px #00000012; color: white; }
|
||||||
|
.admin-app .sidebar-nav-item-active:hover { background: #292929; color: white; }
|
||||||
|
.admin-app .sidebar-nav-item-active > span { color: white; }
|
||||||
|
.admin-app .sidebar-nav-icon-active { color: white; background: transparent; outline: none; box-shadow: none; }
|
||||||
|
.admin-app .sidebar-active-indicator { display: none; }
|
||||||
|
.admin-app .sidebar-subnav-item-active { background: #e5e5e5; color: #262626; box-shadow: inset 2px 0 #737373; }
|
||||||
|
.admin-app .ui-3d-card { box-shadow: none; filter: none; border-color: #e5e5e5; }
|
||||||
|
.admin-app .ui-3d-card-interactive:hover { box-shadow: 0 6px 20px #00000008; filter: none; }
|
||||||
|
.dashboard-layout { display: grid; gap: 32px; }
|
||||||
|
.dashboard-greeting > .pointer-events-none { display: none; }
|
||||||
|
.dashboard-profile { border: 1px solid #e5e5e5; border-radius: 8px; padding: 22px; align-self: start; }
|
||||||
|
.profile-orbit { border: 2px solid #d4d4d4; border-right-color: #171717; outline: 5px solid #f5f5f5; outline-offset: 4px; }
|
||||||
|
.rail-icon { display: inline-grid; place-items: center; width: 34px; height: 34px; flex-shrink: 0; border: 1px solid #e5e5e5; border-radius: 6px; }
|
||||||
|
.rail-summary { display: flex; align-items: center; gap: 10px; border-radius: 8px; }
|
||||||
|
.rail-summary:hover { color: #171717; }
|
||||||
|
.admin-app .dashboard-stat { position: relative; overflow: hidden; background: #f0f0f0; border: 0; }
|
||||||
|
.dashboard-stat:nth-child(3n + 2) { background: #f7f7f7; }
|
||||||
|
.dashboard-stat:nth-child(3n) { background: #e9e9e9; }
|
||||||
|
.dashboard-stat::after { content: ""; position: absolute; width: 160px; height: 160px; border: 1px solid #ffffff70; border-radius: 40px; transform: rotate(40deg); top: -95px; right: -40px; pointer-events: none; }
|
||||||
|
.dashboard-stat .border-t { border-color: #ffffff80; }
|
||||||
|
.admin-app .dashboard-stat .stat-icon { border-radius: 50%; color: #262626; }
|
||||||
|
.dashboard-stat:nth-child(3n + 2) .stat-icon { color: #525252; }
|
||||||
|
.dashboard-stat:nth-child(3n) .stat-icon { color: #404040; }
|
||||||
|
.dashboard-stat .text-mint-500 { color: #24745e; }
|
||||||
|
@media (min-width: 1440px) {
|
||||||
|
.dashboard-layout { grid-template-columns: minmax(0, 1fr) 260px; gap: 28px; }
|
||||||
|
.dashboard-profile { border: 0; border-left: 1px solid #e5e5e5; border-radius: 0; padding: 0 0 20px 24px; position: sticky; top: 0; }
|
||||||
|
}
|
||||||
|
@media (min-width: 768px) and (max-width: 1439px) {
|
||||||
|
.dashboard-profile { display: grid; grid-template-columns: 1fr 1fr; gap: 20px 32px; }
|
||||||
|
.dashboard-profile > section, .dashboard-profile > .rail-callout { margin-top: 0; }
|
||||||
|
}
|
||||||
|
html.dark .admin-app, html.dark .admin-main { background: hsl(var(--background)); }
|
||||||
|
html.dark .admin-app > .sidebar-shell { background: #1c1c1c; border-color: #404040; }
|
||||||
|
html.dark .admin-app .sidebar-nav-item-active { background: #333333; }
|
||||||
|
html.dark .dashboard-stat { background: #292929; }
|
||||||
|
html.dark .dashboard-stat:nth-child(3n + 2) { background: #303030; }
|
||||||
|
html.dark .dashboard-stat:nth-child(3n) { background: #242424; }
|
||||||
|
html.dark .dashboard-profile, html.dark .admin-app .ui-3d-card { border-color: #404040; }
|
||||||
|
html.dark .profile-orbit { outline-color: #303030; }
|
||||||
|
html.dark .rail-callout { background: #252525; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.admin-data-table {
|
||||||
|
--table-header: #111111;
|
||||||
|
--table-header-text: #ffffff;
|
||||||
|
--table-row: #ffffff;
|
||||||
|
--table-hover: #f5f5f5;
|
||||||
|
--table-selected: #e8e8e8;
|
||||||
|
--table-divider: #e5e5e5;
|
||||||
|
--table-edge: #737373;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > thead > tr {
|
||||||
|
background: var(--table-header);
|
||||||
|
border-bottom: 3px solid var(--table-edge);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > thead > tr > th {
|
||||||
|
height: 54px;
|
||||||
|
padding-top: 17px;
|
||||||
|
padding-bottom: 17px;
|
||||||
|
background: var(--table-header);
|
||||||
|
color: var(--table-header-text);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0;
|
||||||
|
text-transform: none;
|
||||||
|
border-right: 1px solid #ffffff14;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > thead > tr > th:last-child { border-right: 0; }
|
||||||
|
.admin-data-table > thead :is(button, svg) { color: inherit; }
|
||||||
|
|
||||||
|
.admin-data-table > tbody > tr {
|
||||||
|
--table-current-row: var(--table-row);
|
||||||
|
--table-current-edge: transparent;
|
||||||
|
background: var(--table-current-row);
|
||||||
|
border-bottom: 1px solid var(--table-divider);
|
||||||
|
transition: background-color 140ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > tbody > tr:hover:not(:has(td[colspan])),
|
||||||
|
.admin-data-table > tbody > tr:focus-within {
|
||||||
|
--table-current-row: var(--table-hover);
|
||||||
|
--table-current-edge: var(--table-edge);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > tbody > tr[data-state="selected"],
|
||||||
|
.admin-data-table > tbody > tr:has(input[type="checkbox"]:checked),
|
||||||
|
.admin-data-table > tbody > tr:has([role="checkbox"][data-state="checked"]) {
|
||||||
|
--table-current-row: var(--table-selected);
|
||||||
|
--table-current-edge: var(--table-edge);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-data-table > tbody > tr:last-child { border-bottom: 0; }
|
||||||
|
.admin-data-table > tbody > tr > td:not([colspan]) { padding-top: 20px; padding-bottom: 20px; }
|
||||||
|
.admin-data-table > tbody > tr > td:first-child:not([colspan]) { box-shadow: inset 3px 0 var(--table-current-edge); }
|
||||||
|
.admin-data-table > tbody > tr > td.sticky { background: var(--table-current-row); }
|
||||||
|
.admin-data-table input[type="checkbox"] { accent-color: var(--table-edge); }
|
||||||
|
.admin-data-table > tfoot { background: var(--table-hover); border-top: 2px solid var(--table-divider); }
|
||||||
|
|
||||||
|
html.dark .admin-data-table {
|
||||||
|
--table-header: #111111;
|
||||||
|
--table-header-text: #fafafa;
|
||||||
|
--table-row: #262626;
|
||||||
|
--table-hover: #333333;
|
||||||
|
--table-selected: #404040;
|
||||||
|
--table-divider: #404040;
|
||||||
|
--table-edge: #bdbdbd;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.admin-data-table > tbody > tr { transition: none; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.admin-app h1 { font-size: clamp(2rem, 2.5vw, 2.75rem); line-height: 1.12; letter-spacing: -0.025em; }
|
||||||
|
.dashboard-workspace h2 { font-size: 1.6rem; line-height: 1.2; }
|
||||||
|
.dashboard-profile h2 { font-size: 1.25rem; }
|
||||||
|
.admin-app .sidebar-nav-item { font-size: 13px; }
|
||||||
|
.admin-app .sidebar-brand-header { border-bottom: 1px solid hsl(var(--border)); border-radius: 0; padding-bottom: 18px; }
|
||||||
|
.admin-app .ui-3d-button { box-shadow: none; }
|
||||||
|
.admin-app .sidebar-nav-item-active { box-shadow: 0 4px 12px #0000001a; }
|
||||||
|
.admin-app .sidebar-subnav-item-active { color: #262626; background: #e5e5e5; }
|
||||||
|
.admin-app .ui-3d-card { border-radius: 8px; }
|
||||||
|
.dashboard-stat .stat-icon { background: #ffffffa6; }
|
||||||
|
.rail-callout h3 { font-family: "Cormorant Garamond", Georgia, serif; font-size: 1.55rem; line-height: 1.15; }
|
||||||
|
html.dark .text-brand-500, html.dark .text-brand-600 { color: #e5e5e5; }
|
||||||
|
html.dark .bg-brand-500, html.dark .bg-brand-600 { color: white; }
|
||||||
|
html.dark .admin-app .sidebar-subnav-item-active { color: #f5f5f5; background: #333333; }
|
||||||
|
html.dark .dashboard-stat .text-mint-500 { color: #80d3b4; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
.studio-topbar { background: #ffffff; border-color: #e5e5e5; box-shadow: 0 4px 24px #00000004; }
|
||||||
|
.studio-header-emblem { color: #171717; background: #ededed; border: 1px solid #d4d4d4; }
|
||||||
|
.studio-header-control { display: grid; place-items: center; width: 38px; height: 38px; flex-shrink: 0; border: 1px solid hsl(var(--border)); border-radius: 6px; color: hsl(var(--foreground)); }
|
||||||
|
.studio-account { background: #111111; color: #ffffff; box-shadow: 0 3px 10px #00000014; transition: background-color 150ms ease; }
|
||||||
|
.studio-account:hover { background: #292929; }
|
||||||
|
.studio-account:focus-visible, .studio-header-control:focus-visible { outline: 2px solid #737373; outline-offset: 3px; }
|
||||||
|
.studio-header-notifications > div > button { border-radius: 6px; background: transparent; border-color: hsl(var(--border)); }
|
||||||
|
.studio-header-toolbar { border-top: 1px solid #f4f4f4; padding-top: 10px; }
|
||||||
|
.studio-search-field { background: #f3f3f3; border-color: transparent; transition: border-color 150ms ease, background-color 150ms ease; }
|
||||||
|
.studio-search-field:focus-within { background: hsl(var(--card)); border-color: #737373; box-shadow: 0 0 0 3px #00000012; }
|
||||||
|
.studio-account-item { display: flex; align-items: center; gap: 10px; cursor: pointer; border-radius: 6px; padding: 11px 12px; font-size: 12px; outline: none; }
|
||||||
|
.studio-account-item[data-highlighted] { background: hsl(var(--accent)); }
|
||||||
|
html.dark .studio-topbar { background: #1b1b1b; border-color: #404040; box-shadow: none; }
|
||||||
|
html.dark .studio-header-toolbar { border-color: #333333; }
|
||||||
|
html.dark .studio-header-emblem { background: #333333; border-color: #525252; color: #e5e5e5; }
|
||||||
|
html.dark .studio-account { background: #111111; }
|
||||||
|
html.dark .studio-account:hover { background: #333333; }
|
||||||
|
html.dark .studio-search-field { background: #262626; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer components {
|
||||||
|
@media (max-width: 639px) {
|
||||||
|
.studio-header-notifications > div { position: static; }
|
||||||
|
.studio-header-notifications > div > div {
|
||||||
|
top: 68px;
|
||||||
|
right: 12px;
|
||||||
|
width: calc(100vw - 24px);
|
||||||
|
max-width: 380px;
|
||||||
|
max-height: calc(100dvh - 90px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -90,7 +90,7 @@ export function AppLayout() {
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh overflow-hidden bg-grayScale-100">
|
<div className="admin-app flex h-dvh overflow-hidden bg-grayScale-100">
|
||||||
<Sidebar
|
<Sidebar
|
||||||
isOpen={sidebarOpen}
|
isOpen={sidebarOpen}
|
||||||
isCollapsed={sidebarCollapsed}
|
isCollapsed={sidebarCollapsed}
|
||||||
|
|
@ -105,7 +105,7 @@ export function AppLayout() {
|
||||||
<Topbar onSidebarToggle={handleSidebarToggle} />
|
<Topbar onSidebarToggle={handleSidebarToggle} />
|
||||||
<main
|
<main
|
||||||
ref={mainRef}
|
ref={mainRef}
|
||||||
className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 pb-8 pt-4 sm:px-4 lg:px-6"
|
className="admin-main min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-y-contain px-3 pb-8 pt-6 sm:px-5 lg:px-8"
|
||||||
>
|
>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
|
|
|
||||||
|
|
@ -225,11 +225,11 @@ export const RESOURCE_TYPE_OPTIONS: { value: string; label: string }[] = [
|
||||||
{ value: "CATEGORY", label: "Category" },
|
{ value: "CATEGORY", label: "Category" },
|
||||||
{ value: "SUB_COURSE", label: "Sub-course" },
|
{ value: "SUB_COURSE", label: "Sub-course" },
|
||||||
{ value: "QUESTION_SET", label: "Question set" },
|
{ value: "QUESTION_SET", label: "Question set" },
|
||||||
{ value: "EXAM_PREP_CATALOG_COURSE", label: "Duolingo/IELTS course" },
|
{ value: "EXAM_PREP_CATALOG_COURSE", label: "Makeup artistry course" },
|
||||||
{ value: "EXAM_PREP_UNIT", label: "Duolingo/IELTS unit" },
|
{ value: "EXAM_PREP_UNIT", label: "Makeup artistry unit" },
|
||||||
{ value: "EXAM_PREP_MODULE", label: "Duolingo/IELTS module" },
|
{ value: "EXAM_PREP_MODULE", label: "Makeup artistry module" },
|
||||||
{ value: "EXAM_PREP_LESSON", label: "Duolingo/IELTS lesson" },
|
{ value: "EXAM_PREP_LESSON", label: "Makeup artistry lesson" },
|
||||||
{ value: "EXAM_PREP_PRACTICE", label: "Duolingo/IELTS practice" },
|
{ value: "EXAM_PREP_PRACTICE", label: "Makeup artistry practice" },
|
||||||
{ value: "APP_VERSION", label: "App version" },
|
{ value: "APP_VERSION", label: "App version" },
|
||||||
{ value: "FIELD_OPTION", label: "Field option" },
|
{ value: "FIELD_OPTION", label: "Field option" },
|
||||||
{ value: "DEVICE", label: "Device" },
|
{ value: "DEVICE", label: "Device" },
|
||||||
|
|
|
||||||
|
|
@ -15,10 +15,10 @@ export const SUBSCRIPTION_STATUS_BREAKDOWN = [
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
const SUBSCRIPTION_STATUS_COLORS: Record<string, string> = {
|
const SUBSCRIPTION_STATUS_COLORS: Record<string, string> = {
|
||||||
ACTIVE: "#27272A",
|
ACTIVE: "#578E83",
|
||||||
PENDING: "#A1A1AA",
|
PENDING: "#C39A53",
|
||||||
EXPIRED: "#3F3F46",
|
EXPIRED: "#8F7CA2",
|
||||||
CANCELLED: "#3F3F46",
|
CANCELLED: "#BE6F7C",
|
||||||
}
|
}
|
||||||
|
|
||||||
const INACTIVE_SUBSCRIPTION_STATUSES = new Set([
|
const INACTIVE_SUBSCRIPTION_STATUSES = new Set([
|
||||||
|
|
@ -185,7 +185,7 @@ export function getPrimaryQuestionTypeSummary(questionsByType: LabelCount[]): st
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getVideoLessonsSummary(lmsLessonsWithVideo = 0, examPrepLessonsWithVideo = 0): string {
|
export function getVideoLessonsSummary(lmsLessonsWithVideo = 0, examPrepLessonsWithVideo = 0): string {
|
||||||
return `${lmsLessonsWithVideo.toLocaleString()} LMS · ${examPrepLessonsWithVideo.toLocaleString()} Duolingo/IELTS lessons`
|
return `${lmsLessonsWithVideo.toLocaleString()} academy videos · ${examPrepLessonsWithVideo.toLocaleString()} catalog video lessons`
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MonthlyRevenuePoint {
|
export interface MonthlyRevenuePoint {
|
||||||
|
|
|
||||||
15
src/lib/apiResponse.ts
Normal file
15
src/lib/apiResponse.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
function record(value: unknown): Record<string, unknown> | undefined {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||||
|
? value as Record<string, unknown>
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read IDs from current and legacy create-response envelopes. */
|
||||||
|
export function readCreatedEntityId(body: unknown, entity: "course" | "category"): number | null {
|
||||||
|
const root = record(body)
|
||||||
|
const data = record(root?.data)
|
||||||
|
const value = data?.id ?? record(data?.[entity])?.id ?? record(data?.data)?.id ?? record(root?.[entity])?.id ?? root?.id
|
||||||
|
if (value == null) return null
|
||||||
|
const id = Number(value)
|
||||||
|
return Number.isSafeInteger(id) && id > 0 ? id : null
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
|
import { paymentsFilterParams } from "../api/payments.api"
|
||||||
import type { GetUsersParams } from "../api/users.api"
|
import type { GetUsersParams } from "../api/users.api"
|
||||||
import { buildUsersListQuery } from "../api/users.api"
|
import { buildUsersListQuery } from "../api/users.api"
|
||||||
import { paymentsFilterParams } from "../api/payments.api"
|
|
||||||
import { nextCalendarDay } from "./payments"
|
|
||||||
import type { ActivityLogFilters } from "../types/activity-log.types"
|
import type { ActivityLogFilters } from "../types/activity-log.types"
|
||||||
|
import type { SubscriptionPlanCategory } from "../types/subscription.types"
|
||||||
import type { QueryParams } from "./csv-export"
|
import type { QueryParams } from "./csv-export"
|
||||||
|
import { nextCalendarDay } from "./payments"
|
||||||
|
|
||||||
export function paymentListFiltersToExportQuery(filters: {
|
export function paymentListFiltersToExportQuery(filters: {
|
||||||
status?: string
|
status?: string
|
||||||
provider?: string
|
provider?: string
|
||||||
planCategory?: string
|
planCategory?: SubscriptionPlanCategory
|
||||||
currency?: string
|
currency?: string
|
||||||
reference?: string
|
reference?: string
|
||||||
/** Inclusive YYYY-MM-DD; mapped to created_from. */
|
/** Inclusive YYYY-MM-DD; mapped to created_from. */
|
||||||
|
|
@ -34,8 +35,10 @@ export function usersExportQuery(params: Omit<GetUsersParams, "page" | "page_siz
|
||||||
}
|
}
|
||||||
|
|
||||||
export function activityLogExportQuery(filters: ActivityLogFilters): QueryParams {
|
export function activityLogExportQuery(filters: ActivityLogFilters): QueryParams {
|
||||||
const { limit: _limit, offset: _offset, ...rest } = filters
|
const query: QueryParams = { ...filters }
|
||||||
return rest
|
delete query.limit
|
||||||
|
delete query.offset
|
||||||
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
export function teamMemberExportQuery(filters: {
|
export function teamMemberExportQuery(filters: {
|
||||||
|
|
|
||||||
18
src/lib/displayValue.shared.ts
Normal file
18
src/lib/displayValue.shared.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
|
||||||
|
export const UNASSIGNED_LABEL = "unassigned"
|
||||||
|
|
||||||
|
export const LEGACY_EMPTY_LABELS = new Set(["—", "-", "Not assigned", "not assigned"])
|
||||||
|
|
||||||
|
export function isUnassignedLabel(value: string | null | undefined): boolean {
|
||||||
|
const trimmed = value?.trim()
|
||||||
|
return !trimmed || trimmed === UNASSIGNED_LABEL || LEGACY_EMPTY_LABELS.has(trimmed)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function displayValue(value: string | null | undefined): string {
|
||||||
|
const trimmed = value?.trim()
|
||||||
|
if (!trimmed || LEGACY_EMPTY_LABELS.has(trimmed) || trimmed === UNASSIGNED_LABEL) {
|
||||||
|
return UNASSIGNED_LABEL
|
||||||
|
}
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,27 +1,11 @@
|
||||||
import type { ReactNode } from "react"
|
import type { ReactNode } from "react"
|
||||||
import { SearchHighlight } from "../components/SearchHighlight"
|
import { SearchHighlight } from "../components/SearchHighlight"
|
||||||
|
import { UNASSIGNED_LABEL, isUnassignedLabel } from "./displayValue.shared"
|
||||||
import { cn } from "./utils"
|
import { cn } from "./utils"
|
||||||
|
|
||||||
export const UNASSIGNED_LABEL = "unassigned"
|
|
||||||
|
|
||||||
/** @deprecated Prefer UNASSIGNED_LABEL */
|
/** @deprecated Prefer UNASSIGNED_LABEL */
|
||||||
export const NOT_ASSIGNED_LABEL = UNASSIGNED_LABEL
|
export const NOT_ASSIGNED_LABEL = UNASSIGNED_LABEL
|
||||||
|
|
||||||
const LEGACY_EMPTY_LABELS = new Set(["—", "-", "Not assigned", "not assigned"])
|
|
||||||
|
|
||||||
export function isUnassignedLabel(value: string | null | undefined): boolean {
|
|
||||||
const trimmed = value?.trim()
|
|
||||||
return !trimmed || trimmed === UNASSIGNED_LABEL || LEGACY_EMPTY_LABELS.has(trimmed)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function displayValue(value: string | null | undefined): string {
|
|
||||||
const trimmed = value?.trim()
|
|
||||||
if (!trimmed || LEGACY_EMPTY_LABELS.has(trimmed) || trimmed === UNASSIGNED_LABEL) {
|
|
||||||
return UNASSIGNED_LABEL
|
|
||||||
}
|
|
||||||
return trimmed
|
|
||||||
}
|
|
||||||
|
|
||||||
export function UnassignedLabel({ className }: { className?: string }) {
|
export function UnassignedLabel({ className }: { className?: string }) {
|
||||||
return (
|
return (
|
||||||
<span className={cn("italic text-grayScale-400", className)}>{UNASSIGNED_LABEL}</span>
|
<span className={cn("italic text-grayScale-400", className)}>{UNASSIGNED_LABEL}</span>
|
||||||
|
|
|
||||||
|
|
@ -8,9 +8,6 @@ import {
|
||||||
getExamPrepUnitModules,
|
getExamPrepUnitModules,
|
||||||
getExamPrepUnitPractices,
|
getExamPrepUnitPractices,
|
||||||
} from "../api/courses.api"
|
} from "../api/courses.api"
|
||||||
import { examPrepParentsFromPractice } from "./questionTypeDefinitionPractices"
|
|
||||||
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
|
||||||
import { dedupeParents, parentsFromPractice } from "./practiceParents"
|
|
||||||
import type {
|
import type {
|
||||||
ExamPrepCatalogCourseItem,
|
ExamPrepCatalogCourseItem,
|
||||||
ExamPrepCatalogUnitItem,
|
ExamPrepCatalogUnitItem,
|
||||||
|
|
@ -19,34 +16,16 @@ import type {
|
||||||
PracticeParent,
|
PracticeParent,
|
||||||
} from "../types/course.types"
|
} from "../types/course.types"
|
||||||
import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types"
|
import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types"
|
||||||
|
import { fetchAllOffsetPages, offsetPageFromListEnvelope } from "./fetchAllOffsetPages"
|
||||||
|
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
||||||
|
import { dedupeParents, parentsFromPractice } from "./practiceParents"
|
||||||
|
import { examPrepParentsFromPractice } from "./questionTypeDefinitionPractices"
|
||||||
|
|
||||||
const PAGE_SIZE = 100
|
const PAGE_SIZE = 100
|
||||||
const DEFAULT_PROGRAM_TYPE = "proficiency"
|
const DEFAULT_PROGRAM_TYPE = "proficiency"
|
||||||
|
|
||||||
type ExamPrepParentTab = "catalog_course" | "unit" | "lesson"
|
type ExamPrepParentTab = "catalog_course" | "unit" | "lesson"
|
||||||
|
|
||||||
function listFromEnvelope<T>(
|
|
||||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
|
||||||
key: string,
|
|
||||||
): T[] {
|
|
||||||
const body = res.data?.data ?? res.data?.Data
|
|
||||||
if (!body || typeof body !== "object") return []
|
|
||||||
const record = body as Record<string, unknown>
|
|
||||||
const pascalKey = key.charAt(0).toUpperCase() + key.slice(1)
|
|
||||||
const raw = record[key] ?? record[pascalKey]
|
|
||||||
return Array.isArray(raw) ? (raw as T[]) : []
|
|
||||||
}
|
|
||||||
|
|
||||||
function totalFromEnvelope(
|
|
||||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
|
||||||
): number | undefined {
|
|
||||||
const body = res.data?.data ?? res.data?.Data
|
|
||||||
if (!body || typeof body !== "object") return undefined
|
|
||||||
const record = body as Record<string, unknown>
|
|
||||||
const total = Number(record.total_count ?? record.TotalCount ?? record.totalCount)
|
|
||||||
return Number.isFinite(total) && total >= 0 ? total : undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
function parentTabFromKind(kind?: string): ExamPrepParentTab | null {
|
function parentTabFromKind(kind?: string): ExamPrepParentTab | null {
|
||||||
const k = (kind || "").toUpperCase()
|
const k = (kind || "").toUpperCase()
|
||||||
if (k === "CATALOG_COURSE") return "catalog_course"
|
if (k === "CATALOG_COURSE") return "catalog_course"
|
||||||
|
|
@ -80,66 +59,34 @@ function buildLessonEditPath(
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllCatalogCourses(): Promise<ExamPrepCatalogCourseItem[]> {
|
async function fetchAllCatalogCourses(): Promise<ExamPrepCatalogCourseItem[]> {
|
||||||
const all: ExamPrepCatalogCourseItem[] = []
|
const all = await fetchAllOffsetPages<ExamPrepCatalogCourseItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getExamPrepCatalogCourses({ limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<ExamPrepCatalogCourseItem>(res, "catalog_courses")
|
||||||
const res = await getExamPrepCatalogCourses({ limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<ExamPrepCatalogCourseItem>(res, "catalog_courses")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return all
|
return all
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllCatalogUnits(catalogCourseId: number): Promise<ExamPrepCatalogUnitItem[]> {
|
async function fetchAllCatalogUnits(catalogCourseId: number): Promise<ExamPrepCatalogUnitItem[]> {
|
||||||
const all: ExamPrepCatalogUnitItem[] = []
|
const all = await fetchAllOffsetPages<ExamPrepCatalogUnitItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getExamPrepCatalogUnits(catalogCourseId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<ExamPrepCatalogUnitItem>(res, "units")
|
||||||
const res = await getExamPrepCatalogUnits(catalogCourseId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<ExamPrepCatalogUnitItem>(res, "units")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return all
|
return all
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllUnitModules(unitId: number): Promise<ExamPrepUnitModuleItem[]> {
|
async function fetchAllUnitModules(unitId: number): Promise<ExamPrepUnitModuleItem[]> {
|
||||||
const all: ExamPrepUnitModuleItem[] = []
|
const all = await fetchAllOffsetPages<ExamPrepUnitModuleItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getExamPrepUnitModules(unitId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<ExamPrepUnitModuleItem>(res, "modules")
|
||||||
const res = await getExamPrepUnitModules(unitId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<ExamPrepUnitModuleItem>(res, "modules")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return all
|
return all
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllModuleLessons(moduleId: number): Promise<ExamPrepModuleLessonItem[]> {
|
async function fetchAllModuleLessons(moduleId: number): Promise<ExamPrepModuleLessonItem[]> {
|
||||||
const all: ExamPrepModuleLessonItem[] = []
|
const all = await fetchAllOffsetPages<ExamPrepModuleLessonItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getExamPrepModuleLessons(moduleId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<ExamPrepModuleLessonItem>(res, "lessons")
|
||||||
const res = await getExamPrepModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<ExamPrepModuleLessonItem>(res, "lessons")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return all
|
return all
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -157,9 +104,9 @@ async function parentListContainsPractice(
|
||||||
: tab === "unit"
|
: tab === "unit"
|
||||||
? await getExamPrepUnitPractices(parentId, params)
|
? await getExamPrepUnitPractices(parentId, params)
|
||||||
: await getExamPrepLessonPractices(parentId, params)
|
: await getExamPrepLessonPractices(parentId, params)
|
||||||
const page = listFromEnvelope<{ id?: number; ID?: number }>(res, "practices")
|
const { items: page, total_count: total } =
|
||||||
|
offsetPageFromListEnvelope<{ id?: number; ID?: number }>(res, "practices")
|
||||||
if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true
|
if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
if (page.length === 0) break
|
||||||
if (total != null && offset + page.length >= total) break
|
if (total != null && offset + page.length >= total) break
|
||||||
if (page.length < PAGE_SIZE) break
|
if (page.length < PAGE_SIZE) break
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,10 @@ export async function fetchAllOffsetPages<T>(
|
||||||
fetchPage: (offset: number, limit: number) => Promise<OffsetPageResult<T>>,
|
fetchPage: (offset: number, limit: number) => Promise<OffsetPageResult<T>>,
|
||||||
batchSize = DEFAULT_BATCH_SIZE,
|
batchSize = DEFAULT_BATCH_SIZE,
|
||||||
): Promise<T[]> {
|
): Promise<T[]> {
|
||||||
|
if (!Number.isSafeInteger(batchSize) || batchSize <= 0) {
|
||||||
|
throw new RangeError("batchSize must be a positive safe integer")
|
||||||
|
}
|
||||||
|
|
||||||
const all: T[] = []
|
const all: T[] = []
|
||||||
let offset = 0
|
let offset = 0
|
||||||
let totalCount = Number.POSITIVE_INFINITY
|
let totalCount = Number.POSITIVE_INFINITY
|
||||||
|
|
@ -38,7 +42,7 @@ export async function fetchAllOffsetPages<T>(
|
||||||
const { items, total_count } = await fetchPage(offset, batchSize)
|
const { items, total_count } = await fetchPage(offset, batchSize)
|
||||||
all.push(...items)
|
all.push(...items)
|
||||||
|
|
||||||
if (typeof total_count === "number" && Number.isFinite(total_count)) {
|
if (typeof total_count === "number" && Number.isFinite(total_count) && total_count >= 0) {
|
||||||
totalCount = total_count
|
totalCount = total_count
|
||||||
} else if (items.length === 0) {
|
} else if (items.length === 0) {
|
||||||
break
|
break
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { getExamPrepPractices, getPractices } from "../api/courses.api"
|
import { getExamPrepPractices, getPractices } from "../api/courses.api"
|
||||||
import type { ParentContextPractice } from "../types/course.types"
|
import type { ParentContextPractice } from "../types/course.types"
|
||||||
|
import { fetchAllOffsetPages, offsetPageFromListEnvelope } from "./fetchAllOffsetPages"
|
||||||
|
|
||||||
const FETCH_PAGE_SIZE = 100
|
const FETCH_PAGE_SIZE = 100
|
||||||
|
|
||||||
|
|
@ -12,29 +13,8 @@ export async function fetchAllPractices(
|
||||||
options?: FetchAllPracticesOptions,
|
options?: FetchAllPracticesOptions,
|
||||||
): Promise<ParentContextPractice[]> {
|
): Promise<ParentContextPractice[]> {
|
||||||
const listPractices = options?.isExamPrep ? getExamPrepPractices : getPractices
|
const listPractices = options?.isExamPrep ? getExamPrepPractices : getPractices
|
||||||
const all: ParentContextPractice[] = []
|
return fetchAllOffsetPages<ParentContextPractice>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await listPractices({ limit, offset, unlinked_only: unlinkedOnly })
|
||||||
let totalCount = Number.POSITIVE_INFINITY
|
return offsetPageFromListEnvelope<ParentContextPractice>(res, "practices")
|
||||||
|
}, FETCH_PAGE_SIZE)
|
||||||
while (offset < totalCount) {
|
|
||||||
const res = await listPractices({
|
|
||||||
limit: FETCH_PAGE_SIZE,
|
|
||||||
offset,
|
|
||||||
unlinked_only: unlinkedOnly,
|
|
||||||
})
|
|
||||||
const envelope = res.data?.data
|
|
||||||
const batch = Array.isArray(envelope?.practices) ? envelope.practices : []
|
|
||||||
if (typeof envelope?.total_count === "number") {
|
|
||||||
totalCount = envelope.total_count
|
|
||||||
} else if (batch.length === 0) {
|
|
||||||
break
|
|
||||||
} else {
|
|
||||||
totalCount = offset + batch.length
|
|
||||||
}
|
|
||||||
all.push(...batch)
|
|
||||||
if (batch.length === 0) break
|
|
||||||
offset += FETCH_PAGE_SIZE
|
|
||||||
}
|
|
||||||
|
|
||||||
return all
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,6 @@ import {
|
||||||
getProgramCourses,
|
getProgramCourses,
|
||||||
getTopLevelCourseModules,
|
getTopLevelCourseModules,
|
||||||
} from "../api/courses.api"
|
} from "../api/courses.api"
|
||||||
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
|
||||||
import { parentsFromPractice } from "./practiceParents"
|
|
||||||
import type {
|
import type {
|
||||||
LearningProgramListItem,
|
LearningProgramListItem,
|
||||||
ProgramCourseListItem,
|
ProgramCourseListItem,
|
||||||
|
|
@ -17,6 +15,9 @@ import type {
|
||||||
TopLevelModuleLessonItem,
|
TopLevelModuleLessonItem,
|
||||||
} from "../types/course.types"
|
} from "../types/course.types"
|
||||||
import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types"
|
import type { QuestionTypeDefinitionPractice } from "../types/questionTypeDefinition.types"
|
||||||
|
import { fetchAllOffsetPages, offsetPageFromListEnvelope } from "./fetchAllOffsetPages"
|
||||||
|
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
||||||
|
import { parentsFromPractice } from "./practiceParents"
|
||||||
|
|
||||||
const PAGE_SIZE = 100
|
const PAGE_SIZE = 100
|
||||||
|
|
||||||
|
|
@ -41,89 +42,35 @@ function pickNum(...values: unknown[]): number | undefined {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
function listFromEnvelope<T>(
|
|
||||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
|
||||||
key: string,
|
|
||||||
): T[] {
|
|
||||||
const body = res.data?.data ?? res.data?.Data
|
|
||||||
if (!body || typeof body !== "object") return []
|
|
||||||
const record = body as Record<string, unknown>
|
|
||||||
const pascalKey = key.charAt(0).toUpperCase() + key.slice(1)
|
|
||||||
const raw = record[key] ?? record[pascalKey]
|
|
||||||
return Array.isArray(raw) ? (raw as T[]) : []
|
|
||||||
}
|
|
||||||
|
|
||||||
function totalFromEnvelope(
|
|
||||||
res: { data?: { data?: Record<string, unknown>; Data?: Record<string, unknown> } },
|
|
||||||
): number | undefined {
|
|
||||||
const body = res.data?.data ?? res.data?.Data
|
|
||||||
if (!body || typeof body !== "object") return undefined
|
|
||||||
const record = body as Record<string, unknown>
|
|
||||||
const total = Number(record.total_count ?? record.TotalCount ?? record.totalCount)
|
|
||||||
return Number.isFinite(total) && total >= 0 ? total : undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchAllLearningPrograms(): Promise<LearningProgramListItem[]> {
|
async function fetchAllLearningPrograms(): Promise<LearningProgramListItem[]> {
|
||||||
const all: LearningProgramListItem[] = []
|
const all = await fetchAllOffsetPages<LearningProgramListItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getLearningPrograms({ limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<LearningProgramListItem>(res, "programs")
|
||||||
const res = await getLearningPrograms({ limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<LearningProgramListItem>(res, "programs")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return sortBySortOrder(all)
|
return sortBySortOrder(all)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllProgramCourses(programId: number): Promise<ProgramCourseListItem[]> {
|
async function fetchAllProgramCourses(programId: number): Promise<ProgramCourseListItem[]> {
|
||||||
const all: ProgramCourseListItem[] = []
|
const all = await fetchAllOffsetPages<ProgramCourseListItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getProgramCourses(programId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<ProgramCourseListItem>(res, "courses")
|
||||||
const res = await getProgramCourses(programId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<ProgramCourseListItem>(res, "courses")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return sortBySortOrder(all)
|
return sortBySortOrder(all)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllCourseModules(courseId: number): Promise<TopLevelCourseModuleItem[]> {
|
async function fetchAllCourseModules(courseId: number): Promise<TopLevelCourseModuleItem[]> {
|
||||||
const all: TopLevelCourseModuleItem[] = []
|
const all = await fetchAllOffsetPages<TopLevelCourseModuleItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getTopLevelCourseModules(courseId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<TopLevelCourseModuleItem>(res, "modules")
|
||||||
const res = await getTopLevelCourseModules(courseId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<TopLevelCourseModuleItem>(res, "modules")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return sortBySortOrder(all)
|
return sortBySortOrder(all)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchAllModuleLessons(moduleId: number): Promise<TopLevelModuleLessonItem[]> {
|
async function fetchAllModuleLessons(moduleId: number): Promise<TopLevelModuleLessonItem[]> {
|
||||||
const all: TopLevelModuleLessonItem[] = []
|
const all = await fetchAllOffsetPages<TopLevelModuleLessonItem>(async (offset, limit) => {
|
||||||
let offset = 0
|
const res = await getModuleLessons(moduleId, { limit, offset })
|
||||||
while (true) {
|
return offsetPageFromListEnvelope<TopLevelModuleLessonItem>(res, "lessons")
|
||||||
const res = await getModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
|
}, PAGE_SIZE)
|
||||||
const page = listFromEnvelope<TopLevelModuleLessonItem>(res, "lessons")
|
|
||||||
all.push(...page)
|
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
|
||||||
if (total != null && all.length >= total) break
|
|
||||||
if (page.length < PAGE_SIZE) break
|
|
||||||
offset += page.length
|
|
||||||
}
|
|
||||||
return sortBySortOrder(all)
|
return sortBySortOrder(all)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -141,9 +88,9 @@ async function parentListContainsPractice(
|
||||||
: tab === "module"
|
: tab === "module"
|
||||||
? await getPracticesByParentModule(parentId, params)
|
? await getPracticesByParentModule(parentId, params)
|
||||||
: await getPracticesByParentLesson(parentId, params)
|
: await getPracticesByParentLesson(parentId, params)
|
||||||
const page = listFromEnvelope<{ id?: number; ID?: number }>(res, "practices")
|
const { items: page, total_count: total } =
|
||||||
|
offsetPageFromListEnvelope<{ id?: number; ID?: number }>(res, "practices")
|
||||||
if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true
|
if (page.some((p) => Number(p.id ?? p.ID) === practiceId)) return true
|
||||||
const total = totalFromEnvelope(res)
|
|
||||||
if (page.length === 0) break
|
if (page.length === 0) break
|
||||||
if (total != null && offset + page.length >= total) break
|
if (total != null && offset + page.length >= total) break
|
||||||
if (page.length < PAGE_SIZE) break
|
if (page.length < PAGE_SIZE) break
|
||||||
|
|
@ -327,7 +274,7 @@ async function resolveLearnEnglishPath(
|
||||||
}
|
}
|
||||||
|
|
||||||
const parentList =
|
const parentList =
|
||||||
working.parents?.length > 0
|
working.parents && working.parents.length > 0
|
||||||
? working.parents
|
? working.parents
|
||||||
: parentsFromPractice(working)
|
: parentsFromPractice(working)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import type { DynamicQuestionPayload, DynamicElementInstance } from "../types/questionTypeDefinition.types"
|
import type { DynamicElementInstance, DynamicQuestionPayload } from "../types/questionTypeDefinition.types"
|
||||||
import { parseTableSlotValue } from "./dynamicTableValue"
|
import { parseTableSlotValue } from "./dynamicTableValue"
|
||||||
import {
|
import {
|
||||||
finalizeMatchingAnswerPayload,
|
finalizeMatchingAnswerPayload,
|
||||||
|
|
@ -9,6 +9,13 @@ import {
|
||||||
parseMatchingAnswerSlotValue,
|
parseMatchingAnswerSlotValue,
|
||||||
parseMatchingInputsSlotValue,
|
parseMatchingInputsSlotValue,
|
||||||
} from "./matchingSlotValue"
|
} from "./matchingSlotValue"
|
||||||
|
import {
|
||||||
|
multipleChoiceOptionHasValue,
|
||||||
|
multipleChoiceSlotHasContent,
|
||||||
|
normalizeMultipleChoiceValue,
|
||||||
|
parseMultipleChoiceSlotValue,
|
||||||
|
} from "./multipleChoiceSlotValue"
|
||||||
|
import { isNoInputComponentKind } from "./questionComponentKinds"
|
||||||
import {
|
import {
|
||||||
finalizeSelectMissingWordsResponsePayload,
|
finalizeSelectMissingWordsResponsePayload,
|
||||||
finalizeSelectMissingWordsStimulusPayload,
|
finalizeSelectMissingWordsStimulusPayload,
|
||||||
|
|
@ -23,14 +30,6 @@ import {
|
||||||
parseSequenceOrderSlotValue,
|
parseSequenceOrderSlotValue,
|
||||||
sequenceOrderSlotHasContent,
|
sequenceOrderSlotHasContent,
|
||||||
} from "./sequenceOrderSlotValue"
|
} from "./sequenceOrderSlotValue"
|
||||||
import {
|
|
||||||
multipleChoiceOptionHasValue,
|
|
||||||
multipleChoiceSlotHasContent,
|
|
||||||
normalizeMultipleChoiceValue,
|
|
||||||
parseMultipleChoiceSlotValue,
|
|
||||||
serializeMultipleChoiceSlotValue,
|
|
||||||
} from "./multipleChoiceSlotValue"
|
|
||||||
import { isNoInputComponentKind } from "./questionComponentKinds"
|
|
||||||
|
|
||||||
/** Parse a single slot value: plain string/URL, or JSON object/array when input looks like JSON. */
|
/** Parse a single slot value: plain string/URL, or JSON object/array when input looks like JSON. */
|
||||||
export function parseDynamicSlotValue(raw: string | undefined): unknown {
|
export function parseDynamicSlotValue(raw: string | undefined): unknown {
|
||||||
|
|
@ -306,7 +305,7 @@ export function slotApiValueToFieldString(value: unknown, kind: string): string
|
||||||
if (typeof value === "string") return value
|
if (typeof value === "string") return value
|
||||||
|
|
||||||
if (isMultipleChoiceKind(kind)) {
|
if (isMultipleChoiceKind(kind)) {
|
||||||
return serializeMultipleChoiceSlotValue(value as { options: unknown[] })
|
return JSON.stringify(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === "object") return JSON.stringify(value)
|
if (typeof value === "object") return JSON.stringify(value)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type {
|
import type {
|
||||||
|
AuthoringProfile,
|
||||||
GetPracticeFullResponse,
|
GetPracticeFullResponse,
|
||||||
PracticeFullData,
|
PracticeFullData,
|
||||||
PracticeFullPractice,
|
PracticeFullPractice,
|
||||||
|
|
@ -6,7 +7,6 @@ import type {
|
||||||
PracticeFullQuestionSet,
|
PracticeFullQuestionSet,
|
||||||
PracticeParent,
|
PracticeParent,
|
||||||
PracticePublishStatus,
|
PracticePublishStatus,
|
||||||
AuthoringProfile,
|
|
||||||
QuestionDetail,
|
QuestionDetail,
|
||||||
QuestionOption,
|
QuestionOption,
|
||||||
QuestionShortAnswer,
|
QuestionShortAnswer,
|
||||||
|
|
@ -26,20 +26,19 @@ import {
|
||||||
questionRowHasContent,
|
questionRowHasContent,
|
||||||
type LearnEnglishDefinitionQuestionInput,
|
type LearnEnglishDefinitionQuestionInput,
|
||||||
} from "./learnEnglishDefinitionQuestion"
|
} from "./learnEnglishDefinitionQuestion"
|
||||||
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
|
|
||||||
import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator"
|
import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator"
|
||||||
import {
|
import {
|
||||||
dynamicPayloadToFieldValues,
|
dynamicPayloadToFieldValues,
|
||||||
slotApiValueToFieldString,
|
slotApiValueToFieldString,
|
||||||
} from "./practiceDynamicQuestionPayload"
|
} from "./practiceDynamicQuestionPayload"
|
||||||
|
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
|
||||||
import {
|
import {
|
||||||
isIeltsSharedStimulusMode,
|
isIeltsSharedStimulusMode,
|
||||||
mapApiStimulusBlocksToForm,
|
mapApiStimulusBlocksToForm,
|
||||||
mapFormStimulusBlocksToApi,
|
mapFormStimulusBlocksToApi,
|
||||||
normalizeAuthoringProfile,
|
normalizeAuthoringProfile,
|
||||||
validatePracticeStimulusBlocks,
|
validatePracticeStimulusBlocks,
|
||||||
validateStimulusBlocks,
|
type PracticeFormStimulusBlock
|
||||||
type PracticeFormStimulusBlock,
|
|
||||||
} from "./practiceStimulusBlocks"
|
} from "./practiceStimulusBlocks"
|
||||||
import {
|
import {
|
||||||
resolveAssociatedQuestionId,
|
resolveAssociatedQuestionId,
|
||||||
|
|
@ -186,11 +185,11 @@ function normalizeQuestionOptions(raw: unknown): QuestionOption[] | undefined {
|
||||||
|
|
||||||
function normalizeShortAnswerItems(
|
function normalizeShortAnswerItems(
|
||||||
raw: unknown,
|
raw: unknown,
|
||||||
): QuestionShortAnswer[] | string[] | undefined {
|
): QuestionShortAnswer[] | undefined {
|
||||||
if (!Array.isArray(raw)) return undefined
|
if (!Array.isArray(raw)) return undefined
|
||||||
const items = raw
|
const items = raw
|
||||||
.map((entry) => {
|
.map((entry) => {
|
||||||
if (typeof entry === "string") return entry
|
if (typeof entry === "string") return { acceptable_answer: entry, match_type: "CASE_INSENSITIVE" }
|
||||||
const record = asRecord(entry)
|
const record = asRecord(entry)
|
||||||
if (!record) return null
|
if (!record) return null
|
||||||
const acceptable = pickStr(
|
const acceptable = pickStr(
|
||||||
|
|
@ -205,8 +204,8 @@ function normalizeShortAnswerItems(
|
||||||
return { acceptable_answer: acceptable, match_type: matchType }
|
return { acceptable_answer: acceptable, match_type: matchType }
|
||||||
})
|
})
|
||||||
.filter(
|
.filter(
|
||||||
(entry): entry is QuestionShortAnswer | string =>
|
(entry): entry is { acceptable_answer: string; match_type: string } =>
|
||||||
entry != null && (typeof entry === "string" || Boolean(entry.acceptable_answer)),
|
entry != null && Boolean(entry.acceptable_answer),
|
||||||
)
|
)
|
||||||
return items.length > 0 ? items : undefined
|
return items.length > 0 ? items : undefined
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { getSearchTokens } from "../components/SearchHighlight"
|
import { getSearchTokens } from "../components/SearchHighlight.shared"
|
||||||
|
|
||||||
import { questionTypeDefinitionListLabel } from "../api/questionTypeDefinitions.api"
|
import { questionTypeDefinitionListLabel } from "../api/questionTypeDefinitions.api"
|
||||||
import type { QuestionDetail } from "../types/course.types"
|
import type { QuestionDetail } from "../types/course.types"
|
||||||
import type {
|
import type {
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,10 @@ export const SUBSCRIPTION_PLAN_CATEGORIES: {
|
||||||
value: SubscriptionPlanCategory
|
value: SubscriptionPlanCategory
|
||||||
label: string
|
label: string
|
||||||
}[] = [
|
}[] = [
|
||||||
{ value: "LEARN_ENGLISH", label: "Learn English" },
|
{ value: "EDUCATION", label: "Makeup Artistry" },
|
||||||
{ value: "IELTS", label: "IELTS" },
|
{ value: "LEARN_ENGLISH", label: "Legacy: Learn English" },
|
||||||
{ value: "DUOLINGO", label: "Duolingo" },
|
{ value: "IELTS", label: "Legacy: IELTS" },
|
||||||
|
{ value: "DUOLINGO", label: "Legacy: Duolingo" },
|
||||||
]
|
]
|
||||||
|
|
||||||
export const LIFETIME_DURATION_DEFAULT = {
|
export const LIFETIME_DURATION_DEFAULT = {
|
||||||
|
|
@ -123,7 +124,7 @@ export function formatPlanDuration(
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatPlanPrice(
|
export function formatPlanPrice(
|
||||||
plan: Pick<SubscriptionPlan, "price" | "currency" | "is_free">,
|
plan: Pick<SubscriptionPlan, "price" | "currency"> & Partial<Pick<SubscriptionPlan, "is_free">>,
|
||||||
): string {
|
): string {
|
||||||
if (plan.is_free) return "Free"
|
if (plan.is_free) return "Free"
|
||||||
const amount = Number(plan.price)
|
const amount = Number(plan.price)
|
||||||
|
|
|
||||||
5
src/lib/typeToConfirm.shared.ts
Normal file
5
src/lib/typeToConfirm.shared.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
|
||||||
|
export function matchesConfirmWord(value: string, expectedWord: string): boolean {
|
||||||
|
return value.trim().toUpperCase() === expectedWord.trim().toUpperCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState, type ReactNode } from "react"
|
import { useState, type ReactNode } from "react"
|
||||||
import { Button } from "../components/ui/button"
|
import { Button } from "../components/ui/button"
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
|
|
@ -10,6 +10,7 @@ import {
|
||||||
} from "../components/ui/dialog"
|
} from "../components/ui/dialog"
|
||||||
import { Input } from "../components/ui/input"
|
import { Input } from "../components/ui/input"
|
||||||
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||||
|
import { matchesConfirmWord } from "./typeToConfirm.shared"
|
||||||
import { cn } from "./utils"
|
import { cn } from "./utils"
|
||||||
|
|
||||||
type TypeToConfirmFieldProps = {
|
type TypeToConfirmFieldProps = {
|
||||||
|
|
@ -53,10 +54,6 @@ export function TypeToConfirmField({
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function matchesConfirmWord(value: string, expectedWord: string): boolean {
|
|
||||||
return value.trim().toUpperCase() === expectedWord.trim().toUpperCase()
|
|
||||||
}
|
|
||||||
|
|
||||||
type TypeToConfirmDialogProps = {
|
type TypeToConfirmDialogProps = {
|
||||||
open: boolean
|
open: boolean
|
||||||
onOpenChange: (open: boolean) => void
|
onOpenChange: (open: boolean) => void
|
||||||
|
|
@ -86,10 +83,12 @@ export function TypeToConfirmDialog({
|
||||||
const [confirmText, setConfirmText] = useState("")
|
const [confirmText, setConfirmText] = useState("")
|
||||||
const confirmMatched = matchesConfirmWord(confirmText, confirmWord)
|
const confirmMatched = matchesConfirmWord(confirmText, confirmWord)
|
||||||
|
|
||||||
useEffect(() => {
|
const dialogState = JSON.stringify([open, confirmWord])
|
||||||
if (!open) return
|
const [previousDialogState, setPreviousDialogState] = useState(dialogState)
|
||||||
setConfirmText("")
|
if (previousDialogState !== dialogState) {
|
||||||
}, [open, confirmWord])
|
setPreviousDialogState(dialogState)
|
||||||
|
if (open) setConfirmText("")
|
||||||
|
}
|
||||||
|
|
||||||
const handleConfirm = async () => {
|
const handleConfirm = async () => {
|
||||||
if (!confirmMatched || confirming) return
|
if (!confirmMatched || confirming) return
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/**
|
/**
|
||||||
* Profile field options seeded in backend `field_options` (migration 000069).
|
* Profile field options seeded in backend `field_options` (migration 000069).
|
||||||
* Admin UI shows labels; empty / OTHER / unknown / out-of-list values fall back to defaults.
|
* Missing values remain unassigned; historical and custom values are preserved.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const DEFAULT_USER_AGE_GROUP_CODE = "25_34"
|
export const DEFAULT_USER_AGE_GROUP_CODE = "25_34"
|
||||||
|
|
@ -27,6 +27,11 @@ const AGE_GROUP_OPTIONS: ProfileFieldOption[] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
const OCCUPATION_OPTIONS: ProfileFieldOption[] = [
|
const OCCUPATION_OPTIONS: ProfileFieldOption[] = [
|
||||||
|
{ code: "BEAUTY_STUDENT", label: "Beauty and makeup student" },
|
||||||
|
{ code: "MAKEUP_ARTIST", label: "Makeup artist" },
|
||||||
|
{ code: "BEAUTY_EDUCATOR", label: "Makeup educator" },
|
||||||
|
{ code: "SALON_PROFESSIONAL", label: "Salon or studio professional" },
|
||||||
|
|
||||||
{ code: "STUDENTS", label: "Students (High school & University)" },
|
{ code: "STUDENTS", label: "Students (High school & University)" },
|
||||||
{ code: "JOB_SEEKERS", label: "Job Seekers / Fresh Graduates" },
|
{ code: "JOB_SEEKERS", label: "Job Seekers / Fresh Graduates" },
|
||||||
{ code: "WORKING_PROFESSIONALS", label: "Working Professionals (Corporate/Office)" },
|
{ code: "WORKING_PROFESSIONALS", label: "Working Professionals (Corporate/Office)" },
|
||||||
|
|
@ -65,6 +70,11 @@ const EDUCATION_LEVEL_OPTIONS: ProfileFieldOption[] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
const LEARNING_GOAL_OPTIONS: ProfileFieldOption[] = [
|
const LEARNING_GOAL_OPTIONS: ProfileFieldOption[] = [
|
||||||
|
{ code: "PERSONAL_MAKEUP", label: "Develop personal makeup skills" },
|
||||||
|
{ code: "PRO_MAKEUP_ARTIST", label: "Become a professional makeup artist" },
|
||||||
|
{ code: "BRIDAL_SPECIALIST", label: "Specialize in bridal and occasion makeup" },
|
||||||
|
{ code: "EDITORIAL_PORTFOLIO", label: "Build an editorial makeup portfolio" },
|
||||||
|
|
||||||
{ code: "EVERYDAY_CONVERSATION", label: "Everyday conversation" },
|
{ code: "EVERYDAY_CONVERSATION", label: "Everyday conversation" },
|
||||||
{ code: "WORK_CAREER", label: "Work and career" },
|
{ code: "WORK_CAREER", label: "Work and career" },
|
||||||
{ code: "ACADEMIC_STUDY", label: "Academic study" },
|
{ code: "ACADEMIC_STUDY", label: "Academic study" },
|
||||||
|
|
@ -74,6 +84,11 @@ const LEARNING_GOAL_OPTIONS: ProfileFieldOption[] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
const LANGUAGE_CHALLENGE_OPTIONS: ProfileFieldOption[] = [
|
const LANGUAGE_CHALLENGE_OPTIONS: ProfileFieldOption[] = [
|
||||||
|
{ code: "COLOR_MATCHING", label: "Foundation and color matching" },
|
||||||
|
{ code: "BLENDING", label: "Blending and application" },
|
||||||
|
{ code: "EYE_SYMMETRY", label: "Eye makeup and symmetry" },
|
||||||
|
{ code: "CLIENT_CONFIDENCE", label: "Working confidently with clients" },
|
||||||
|
|
||||||
{ code: "PRONUNCIATION", label: "Pronunciation" },
|
{ code: "PRONUNCIATION", label: "Pronunciation" },
|
||||||
{ code: "WORDS_GRAMMAR", label: "Finding words or grammar quickly" },
|
{ code: "WORDS_GRAMMAR", label: "Finding words or grammar quickly" },
|
||||||
{ code: "CONFIDENCE", label: "Feeling nervous or lacking confidence" },
|
{ code: "CONFIDENCE", label: "Feeling nervous or lacking confidence" },
|
||||||
|
|
@ -81,12 +96,21 @@ const LANGUAGE_CHALLENGE_OPTIONS: ProfileFieldOption[] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
const LANGUAGE_GOAL_OPTIONS: ProfileFieldOption[] = [
|
const LANGUAGE_GOAL_OPTIONS: ProfileFieldOption[] = [
|
||||||
|
{ code: "MAKEUP_FOUNDATIONS", label: "Master makeup foundations" },
|
||||||
|
{ code: "PROFESSIONAL_ARTISTRY", label: "Develop professional artistry" },
|
||||||
|
{ code: "CREATIVE_ARTISTRY", label: "Explore creative artistry" },
|
||||||
|
|
||||||
{ code: "LEARN_TO_SPEAK_ENGLISH", label: "Learn to Speak English" },
|
{ code: "LEARN_TO_SPEAK_ENGLISH", label: "Learn to Speak English" },
|
||||||
{ code: "PRACTICE_TO_SPEAK_ENGLISH", label: "Practice Speaking English" },
|
{ code: "PRACTICE_TO_SPEAK_ENGLISH", label: "Practice Speaking English" },
|
||||||
{ code: "SKILL_BASED_COURSES", label: "Skill-based Courses" },
|
{ code: "SKILL_BASED_COURSES", label: "Skill-based Courses" },
|
||||||
]
|
]
|
||||||
|
|
||||||
const FAVOURITE_TOPIC_OPTIONS: ProfileFieldOption[] = [
|
const FAVOURITE_TOPIC_OPTIONS: ProfileFieldOption[] = [
|
||||||
|
{ code: "COMPLEXION_TECHNIQUES", label: "Complexion and foundation techniques" },
|
||||||
|
{ code: "EYE_MAKEUP", label: "Eye makeup and brow design" },
|
||||||
|
{ code: "BRIDAL_MAKEUP", label: "Bridal and occasion looks" },
|
||||||
|
{ code: "EDITORIAL_MAKEUP", label: "Creative and editorial artistry" },
|
||||||
|
|
||||||
{ code: "FOOD_COOKING", label: "Food & Cooking" },
|
{ code: "FOOD_COOKING", label: "Food & Cooking" },
|
||||||
{ code: "HOBBIES_SPORTS_MUSIC", label: "Hobbies, Sports, Music" },
|
{ code: "HOBBIES_SPORTS_MUSIC", label: "Hobbies, Sports, Music" },
|
||||||
{ code: "TECH_NEWS_BUSINESS", label: "Tech, News, Business" },
|
{ code: "TECH_NEWS_BUSINESS", label: "Tech, News, Business" },
|
||||||
|
|
@ -100,11 +124,11 @@ const KNOWLEDGE_LEVEL_OPTIONS: ProfileFieldOption[] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
export const PROFILE_FILTER_AGE_GROUPS = AGE_GROUP_OPTIONS
|
export const PROFILE_FILTER_AGE_GROUPS = AGE_GROUP_OPTIONS
|
||||||
export const PROFILE_FILTER_OCCUPATIONS = OCCUPATION_OPTIONS
|
export const PROFILE_FILTER_OCCUPATIONS = OCCUPATION_OPTIONS.filter((option) => ["BEAUTY_STUDENT", "MAKEUP_ARTIST", "BEAUTY_EDUCATOR", "SALON_PROFESSIONAL"].includes(option.code))
|
||||||
export const PROFILE_FILTER_EDUCATION_LEVELS = EDUCATION_LEVEL_OPTIONS
|
export const PROFILE_FILTER_EDUCATION_LEVELS = EDUCATION_LEVEL_OPTIONS
|
||||||
export const PROFILE_FILTER_LEARNING_GOALS = LEARNING_GOAL_OPTIONS
|
export const PROFILE_FILTER_LEARNING_GOALS = LEARNING_GOAL_OPTIONS.filter((option) => ["PERSONAL_MAKEUP", "PRO_MAKEUP_ARTIST", "BRIDAL_SPECIALIST", "EDITORIAL_PORTFOLIO"].includes(option.code))
|
||||||
export const PROFILE_FILTER_LANGUAGE_GOALS = LANGUAGE_GOAL_OPTIONS
|
export const PROFILE_FILTER_LANGUAGE_GOALS = LANGUAGE_GOAL_OPTIONS.filter((option) => ["MAKEUP_FOUNDATIONS", "PROFESSIONAL_ARTISTRY", "CREATIVE_ARTISTRY"].includes(option.code))
|
||||||
export const PROFILE_FILTER_FAVOURITE_TOPICS = FAVOURITE_TOPIC_OPTIONS
|
export const PROFILE_FILTER_FAVOURITE_TOPICS = FAVOURITE_TOPIC_OPTIONS.filter((option) => ["COMPLEXION_TECHNIQUES", "EYE_MAKEUP", "BRIDAL_MAKEUP", "EDITORIAL_MAKEUP"].includes(option.code))
|
||||||
export const PROFILE_FILTER_KNOWLEDGE_LEVELS = KNOWLEDGE_LEVEL_OPTIONS
|
export const PROFILE_FILTER_KNOWLEDGE_LEVELS = KNOWLEDGE_LEVEL_OPTIONS
|
||||||
export const PROFILE_FILTER_ETHIOPIA_REGIONS = ETHIOPIA_REGION_OPTIONS
|
export const PROFILE_FILTER_ETHIOPIA_REGIONS = ETHIOPIA_REGION_OPTIONS
|
||||||
|
|
||||||
|
|
@ -290,18 +314,18 @@ function isCatchAllProfileValue(normalized: string): boolean {
|
||||||
}
|
}
|
||||||
|
|
||||||
function labelForCode(options: ProfileFieldOption[], code: string): string {
|
function labelForCode(options: ProfileFieldOption[], code: string): string {
|
||||||
return options.find((o) => o.code === code)?.label ?? code
|
return code === "UNASSIGNED" ? "Not provided" : options.find((o) => o.code === code)?.label ?? code
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveProfileFieldCode(
|
function resolveProfileFieldCode(
|
||||||
raw: string | null | undefined,
|
raw: string | null | undefined,
|
||||||
options: ProfileFieldOption[],
|
options: ProfileFieldOption[],
|
||||||
defaultCode: string,
|
_defaultCode: string,
|
||||||
aliases?: Record<string, string>,
|
aliases?: Record<string, string>,
|
||||||
): string {
|
): string {
|
||||||
const trimmed = raw?.trim() ?? ""
|
const trimmed = raw?.trim() ?? ""
|
||||||
const normalized = normalizeProfileFieldKey(trimmed)
|
const normalized = normalizeProfileFieldKey(trimmed)
|
||||||
if (isCatchAllProfileValue(normalized)) return defaultCode
|
if (isCatchAllProfileValue(normalized)) return "UNASSIGNED"
|
||||||
|
|
||||||
if (aliases?.[normalized]) return aliases[normalized]
|
if (aliases?.[normalized]) return aliases[normalized]
|
||||||
|
|
||||||
|
|
@ -317,7 +341,7 @@ function resolveProfileFieldCode(
|
||||||
if (lower === opt.label.toLowerCase()) return opt.code
|
if (lower === opt.label.toLowerCase()) return opt.code
|
||||||
}
|
}
|
||||||
|
|
||||||
return defaultCode
|
return trimmed
|
||||||
}
|
}
|
||||||
|
|
||||||
function displayProfileFieldLabel(
|
function displayProfileFieldLabel(
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import {
|
import {
|
||||||
// Activity,
|
// Activity,
|
||||||
BadgeCheck,
|
BadgeCheck,
|
||||||
Video,
|
Bell,
|
||||||
|
CreditCard,
|
||||||
// Coins,
|
// Coins,
|
||||||
DollarSign,
|
DollarSign,
|
||||||
HelpCircle,
|
HelpCircle,
|
||||||
|
|
@ -9,70 +10,69 @@ import {
|
||||||
Star,
|
Star,
|
||||||
// TrendingUp,
|
// TrendingUp,
|
||||||
Users,
|
Users,
|
||||||
UserX,
|
|
||||||
Bell,
|
|
||||||
CreditCard,
|
|
||||||
UsersRound,
|
UsersRound,
|
||||||
|
UserX,
|
||||||
|
Video,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import spinnerSrc from "../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
|
||||||
import {
|
import {
|
||||||
Area,
|
Bar,
|
||||||
AreaChart,
|
BarChart,
|
||||||
|
Cell,
|
||||||
CartesianGrid,
|
CartesianGrid,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
} from "recharts"
|
} from "recharts"
|
||||||
|
import spinnerSrc from "../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
|
import { ActivePlansBreakdownCard, analyticsSoftCardClass, BreakdownBarCard, RenewalRateCard } from "../components/analytics/SubscriptionRevenueVisuals"
|
||||||
|
import { labelCountsToPieSlices, SUBSCRIPTION_CHART_COLORS } from "../components/analytics/SubscriptionRevenueVisuals.shared"
|
||||||
import { RevenueTrendCard } from "../components/dashboard/RevenueTrendCard"
|
import { RevenueTrendCard } from "../components/dashboard/RevenueTrendCard"
|
||||||
|
import { DashboardProfileRail } from "../components/dashboard/DashboardProfileRail"
|
||||||
import { StatCard } from "../components/dashboard/StatCard"
|
import { StatCard } from "../components/dashboard/StatCard"
|
||||||
import {
|
|
||||||
ActivePlansBreakdownCard,
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
RenewalRateCard,
|
import { Link } from "react-router-dom"
|
||||||
DonutBreakdownCard,
|
import { getDashboard } from "../api/analytics.api"
|
||||||
analyticsSoftCardClass,
|
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
|
||||||
labelCountsToPieSlices,
|
import { getSubscriptionPlans } from "../api/subscription-plans.api"
|
||||||
SUBSCRIPTION_CHART_COLORS,
|
import { getTeamMemberById } from "../api/team.api"
|
||||||
} from "../components/analytics/SubscriptionRevenueVisuals"
|
|
||||||
import alertSrc from "../assets/Alert.svg"
|
import alertSrc from "../assets/Alert.svg"
|
||||||
|
import { AnalyticsTimeRangeFilter } from "../components/analytics/AnalyticsTimeRangeFilter"
|
||||||
|
import { getDashboardFilterLabel } from "../components/analytics/AnalyticsTimeRangeFilter.shared"
|
||||||
import { Badge } from "../components/ui/badge"
|
import { Badge } from "../components/ui/badge"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||||
import { SensitiveRevealProvider, SensitiveValue } from "../components/ui/sensitive-value"
|
import { SensitiveRevealProvider, SensitiveValue } from "../components/ui/sensitive-value"
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
import { getTeamMemberById } from "../api/team.api"
|
|
||||||
import { getDashboard } from "../api/analytics.api"
|
|
||||||
import { getSubscriptionPlans } from "../api/subscription-plans.api"
|
|
||||||
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
|
|
||||||
import { useEffect, useState, type ReactNode } from "react"
|
|
||||||
import { Link } from "react-router-dom"
|
|
||||||
import { AnalyticsTimeRangeFilter, getDashboardFilterLabel } from "../components/analytics/AnalyticsTimeRangeFilter"
|
|
||||||
import {
|
import {
|
||||||
|
buildSubscriptionStatusPie,
|
||||||
formatAnalyticsSeriesDate,
|
formatAnalyticsSeriesDate,
|
||||||
getPrimaryQuestionTypeSummary,
|
getPrimaryQuestionTypeSummary,
|
||||||
getSeriesPeriodLabel,
|
getSeriesPeriodLabel,
|
||||||
getSubscriptionMetrics,
|
getSubscriptionMetrics,
|
||||||
getVideoLessonsSummary,
|
getVideoLessonsSummary,
|
||||||
buildSubscriptionStatusPie,
|
|
||||||
} from "../lib/analytics"
|
} from "../lib/analytics"
|
||||||
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
|
||||||
import { formatAppDateTime } from "../lib/datetime"
|
import { formatAppDateTime } from "../lib/datetime"
|
||||||
import { formatAverageStars } from "../lib/ratingsDisplay"
|
import { formatAverageStars } from "../lib/ratingsDisplay"
|
||||||
import { formatPlanDuration } from "../lib/subscriptionPlans"
|
import { formatPlanDuration } from "../lib/subscriptionPlans"
|
||||||
import type { SubscriptionPlan } from "../types/subscription.types"
|
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
||||||
import type { Rating, RatingSummary } from "../types/ratings.types"
|
import type { Rating, RatingSummary } from "../types/ratings.types"
|
||||||
|
import type { SubscriptionPlan } from "../types/subscription.types"
|
||||||
|
|
||||||
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
|
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
|
||||||
const CHART_BRAND = SUBSCRIPTION_CHART_COLORS[0]
|
|
||||||
const chartTooltipStyle = {
|
const chartTooltipStyle = {
|
||||||
borderRadius: 10,
|
borderRadius: 10,
|
||||||
border: "1px solid #E8E8E8",
|
border: "1px solid hsl(var(--border))",
|
||||||
|
backgroundColor: "hsl(var(--popover))",
|
||||||
|
color: "hsl(var(--popover-foreground))",
|
||||||
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
|
boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
}
|
}
|
||||||
|
|
||||||
function DashboardSectionTitle({ children }: { children: ReactNode }) {
|
function DashboardSectionTitle({ children }: { children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<h2 className="flex items-center gap-3 text-[11px] font-bold uppercase tracking-[0.16em] text-grayScale-400 after:h-px after:flex-1 after:bg-grayScale-100">{children}</h2>
|
<h2 className="flex items-center gap-3 text-base font-semibold tracking-tight text-grayScale-600">{children}</h2>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -186,23 +186,22 @@ export function DashboardPage() {
|
||||||
: null
|
: null
|
||||||
|
|
||||||
const generatedAt = dashboard ? formatAppDateTime(dashboard.generated_at) : ""
|
const generatedAt = dashboard ? formatAppDateTime(dashboard.generated_at) : ""
|
||||||
|
const peakRegistrations = Math.max(0, ...registrationData.map(row => row.count))
|
||||||
const registrationPeakIndex = registrationData.reduce((best, row, idx) => {
|
|
||||||
return row.count > (registrationData[best]?.count ?? 0) ? idx : best
|
|
||||||
}, 0)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SensitiveRevealProvider>
|
<SensitiveRevealProvider>
|
||||||
<div className="mx-auto w-full min-w-0 max-w-[1600px] px-3 pb-10 sm:px-6 2xl:px-8">
|
<div className="dashboard-layout mx-auto w-full min-w-0 max-w-[1800px] pb-6"
|
||||||
<div className="relative mb-6 flex flex-wrap items-center justify-between gap-5 overflow-hidden rounded-2xl border border-grayScale-200/70 bg-gradient-to-r from-white via-white to-brand-50/60 px-5 py-5 shadow-sm sm:px-7 sm:py-6">
|
>
|
||||||
|
<div className="dashboard-workspace min-w-0">
|
||||||
|
<div className="dashboard-greeting relative mb-7 flex flex-wrap items-center justify-between gap-4">
|
||||||
<div className="pointer-events-none absolute -right-12 -top-24 h-64 w-64 rounded-full bg-brand-100/40 blur-3xl" />
|
<div className="pointer-events-none absolute -right-12 -top-24 h-64 w-64 rounded-full bg-brand-100/40 blur-3xl" />
|
||||||
<div className="relative min-w-0">
|
<div className="relative min-w-0">
|
||||||
<div className="mb-1.5 flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.18em] text-brand-600">
|
<div className="mb-1.5 flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.18em] text-brand-600">
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-brand-500" />
|
<span className="h-1.5 w-1.5 rounded-full bg-brand-500" />
|
||||||
Dashboard
|
Dashboard
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-900 sm:text-3xl">
|
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-600">
|
||||||
Welcome back, {userFirstName || localStorage.getItem("user_first_name") || "there"}
|
Hello {userFirstName || localStorage.getItem("user_first_name") || "there"}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mt-1.5 text-sm text-grayScale-500">
|
<p className="mt-1.5 text-sm text-grayScale-500">
|
||||||
Snapshot for {getDashboardFilterLabel(filters)}
|
Snapshot for {getDashboardFilterLabel(filters)}
|
||||||
|
|
@ -389,56 +388,16 @@ export function DashboardPage() {
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="h-[280px] px-5 pb-5 pt-2">
|
<CardContent className="h-[280px] px-5 pb-5 pt-2">
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%" minWidth={0}>
|
||||||
<AreaChart data={registrationData} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
|
<BarChart data={registrationData} margin={{ left: 0, right: 8, top: 16, bottom: 4 }} barCategoryGap="25%">
|
||||||
<defs>
|
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||||
<linearGradient id="dashboardRegFill" x1="0" y1="0" x2="0" y2="1">
|
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={10} minTickGap={20} tick={{ fill: "var(--gs-500)" }} />
|
||||||
<stop offset="0%" stopColor={CHART_BRAND} stopOpacity={0.32} />
|
<YAxis tickLine={false} axisLine={false} fontSize={10} width={36} allowDecimals={false} tick={{ fill: "var(--gs-500)" }} />
|
||||||
<stop offset="100%" stopColor={CHART_BRAND} stopOpacity={0.02} />
|
<Tooltip cursor={{ fill: "var(--gs-100)" }} contentStyle={chartTooltipStyle} />
|
||||||
</linearGradient>
|
<Bar dataKey="count" name="Registrations" radius={[5, 5, 0, 0]} maxBarSize={24} isAnimationActive={false}>
|
||||||
</defs>
|
{registrationData.map(row => <Cell key={row.date} fill={row.count === peakRegistrations && peakRegistrations > 0 ? "#27685F" : "#79AAA0"} />)}
|
||||||
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
|
</Bar>
|
||||||
<XAxis
|
</BarChart>
|
||||||
dataKey="date"
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={false}
|
|
||||||
fontSize={11}
|
|
||||||
tick={{ fill: "#9E9E9E" }}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={false}
|
|
||||||
fontSize={11}
|
|
||||||
width={36}
|
|
||||||
allowDecimals={false}
|
|
||||||
tick={{ fill: "#9E9E9E" }}
|
|
||||||
/>
|
|
||||||
<Tooltip contentStyle={chartTooltipStyle} />
|
|
||||||
<Area
|
|
||||||
type="monotone"
|
|
||||||
dataKey="count"
|
|
||||||
stroke={CHART_BRAND}
|
|
||||||
strokeWidth={2.75}
|
|
||||||
fill="url(#dashboardRegFill)"
|
|
||||||
dot={(props) => {
|
|
||||||
const { cx, cy, index } = props
|
|
||||||
if (cx == null || cy == null) return null
|
|
||||||
const highlight = index === registrationPeakIndex
|
|
||||||
return (
|
|
||||||
<circle
|
|
||||||
key={`reg-dot-${index}`}
|
|
||||||
cx={cx}
|
|
||||||
cy={cy}
|
|
||||||
r={highlight ? 5.5 : 3.5}
|
|
||||||
fill={CHART_BRAND}
|
|
||||||
stroke="#fff"
|
|
||||||
strokeWidth={highlight ? 2 : 1}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
activeDot={{ r: 6, strokeWidth: 2, stroke: "#fff" }}
|
|
||||||
/>
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
@ -454,7 +413,7 @@ export function DashboardPage() {
|
||||||
|
|
||||||
<section className="space-y-3">
|
<section className="space-y-3">
|
||||||
<DashboardSectionTitle>Subscription health</DashboardSectionTitle>
|
<DashboardSectionTitle>Subscription health</DashboardSectionTitle>
|
||||||
<div className="grid gap-4 xl:grid-cols-3">
|
<div className="grid min-w-0 items-stretch gap-4 md:grid-cols-2 2xl:grid-cols-3">
|
||||||
<ActivePlansBreakdownCard
|
<ActivePlansBreakdownCard
|
||||||
data={labelCountsToPieSlices(
|
data={labelCountsToPieSlices(
|
||||||
(dashboard.subscriptions.active_by_plan?.length
|
(dashboard.subscriptions.active_by_plan?.length
|
||||||
|
|
@ -470,14 +429,9 @@ export function DashboardPage() {
|
||||||
renewalRate={dashboard.subscriptions.renewal?.renewal_rate ?? 0}
|
renewalRate={dashboard.subscriptions.renewal?.renewal_rate ?? 0}
|
||||||
autoRenewCount={dashboard.subscriptions.snapshot?.auto_renew_enabled ?? 0}
|
autoRenewCount={dashboard.subscriptions.snapshot?.auto_renew_enabled ?? 0}
|
||||||
cancelledCount={dashboard.subscriptions.snapshot?.cancelled_now ?? 0}
|
cancelledCount={dashboard.subscriptions.snapshot?.cancelled_now ?? 0}
|
||||||
activeNow={
|
|
||||||
dashboard.subscriptions.snapshot?.active_now ??
|
|
||||||
subscriptionMetrics?.active ??
|
|
||||||
0
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
{subscriptionStatusData.length > 0 ? (
|
{subscriptionStatusData.length > 0 ? (
|
||||||
<DonutBreakdownCard
|
<BreakdownBarCard
|
||||||
title="Subscription Status"
|
title="Subscription Status"
|
||||||
data={subscriptionStatusData}
|
data={subscriptionStatusData}
|
||||||
countSuffix="Subscriptions"
|
countSuffix="Subscriptions"
|
||||||
|
|
@ -652,6 +606,8 @@ export function DashboardPage() {
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
|
<DashboardProfileRail firstName={userFirstName} dashboard={dashboard} />
|
||||||
</div>
|
</div>
|
||||||
</SensitiveRevealProvider>
|
</SensitiveRevealProvider>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Pencil, User } from "lucide-react";
|
import { Pencil, User } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { notifyApiError } from "../lib/apiErrors";
|
|
||||||
import { getTeamMe, updateTeamMe } from "../api/team.api";
|
import { getTeamMe, updateTeamMe } from "../api/team.api";
|
||||||
|
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
|
||||||
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 {
|
import {
|
||||||
|
|
@ -20,12 +20,14 @@ import {
|
||||||
import { Input } from "../components/ui/input";
|
import { Input } from "../components/ui/input";
|
||||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||||
import { Textarea } from "../components/ui/textarea";
|
import { Textarea } from "../components/ui/textarea";
|
||||||
|
import { notifyApiError } from "../lib/apiErrors";
|
||||||
|
import { formatAppDateTime, formatAppLongDate } from "../lib/datetime";
|
||||||
|
import { DisplayValue, UnassignedLabel } from "../lib/displayValue";
|
||||||
|
import { isUnassignedLabel } from "../lib/displayValue.shared";
|
||||||
|
|
||||||
import { cn } from "../lib/utils";
|
import { cn } from "../lib/utils";
|
||||||
import type { TeamMeProfile } from "../types/team.types";
|
import type { TeamMeProfile } from "../types/team.types";
|
||||||
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
|
|
||||||
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField";
|
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField";
|
||||||
import { UnassignedLabel, isUnassignedLabel, DisplayValue } from "../lib/displayValue"
|
|
||||||
import { formatAppDateTime, formatAppLongDate } from "../lib/datetime"
|
|
||||||
|
|
||||||
function formatDate(dateStr: string | null | undefined): string {
|
function formatDate(dateStr: string | null | undefined): string {
|
||||||
return formatAppLongDate(dateStr, "unassigned")
|
return formatAppLongDate(dateStr, "unassigned")
|
||||||
|
|
@ -44,11 +46,6 @@ function formatRoleLabel(role: string): string {
|
||||||
.join(" ");
|
.join(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
function displayValue(value: string | null | undefined): string {
|
|
||||||
const trimmed = value?.trim();
|
|
||||||
return trimmed ? trimmed : "unassigned";
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldGroup({
|
function FieldGroup({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { notifyApiError } from "../lib/apiErrors"
|
|
||||||
import React, { useEffect, useState } from "react";
|
|
||||||
import {
|
import {
|
||||||
|
CreditCard,
|
||||||
Eye,
|
Eye,
|
||||||
EyeOff,
|
EyeOff,
|
||||||
Globe,
|
Globe,
|
||||||
|
|
@ -8,11 +7,16 @@ import {
|
||||||
Moon,
|
Moon,
|
||||||
Palette,
|
Palette,
|
||||||
Shield,
|
Shield,
|
||||||
|
Smartphone,
|
||||||
Sun,
|
Sun,
|
||||||
User,
|
User,
|
||||||
CreditCard,
|
|
||||||
Smartphone,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useSearchParams } from "react-router-dom";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { changeTeamMemberPassword } from "../api/team.api";
|
||||||
|
import { getMyProfile } from "../api/users.api";
|
||||||
|
import { Button } from "../components/ui/button";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
|
|
@ -20,21 +24,18 @@ import {
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "../components/ui/card";
|
} from "../components/ui/card";
|
||||||
import { Input } from "../components/ui/input";
|
import { Input } from "../components/ui/input";
|
||||||
import { Button } from "../components/ui/button";
|
|
||||||
import { cn } from "../lib/utils";
|
|
||||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||||
import { changeTeamMemberPassword } from "../api/team.api";
|
import { useTheme } from "../contexts/ThemeContext.shared";
|
||||||
|
|
||||||
|
import { notifyApiError } from "../lib/apiErrors";
|
||||||
import { logoutToLogin } from "../lib/auth";
|
import { logoutToLogin } from "../lib/auth";
|
||||||
import { getMyProfile } from "../api/users.api";
|
import { cn } from "../lib/utils";
|
||||||
import type { TeamMeProfile } from "../types/team.types";
|
import type { TeamMeProfile } from "../types/team.types";
|
||||||
import { toast } from "sonner";
|
import { RolesListPage } from "./role-management/RolesListPage";
|
||||||
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
||||||
import { ReferralsTab } from "./settings/ReferralsTab";
|
import { ReferralsTab } from "./settings/ReferralsTab";
|
||||||
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
||||||
import { ThemeModePreview } from "./settings/components/ThemeModePreview";
|
import { ThemeModePreview } from "./settings/components/ThemeModePreview";
|
||||||
import { useTheme } from "../contexts/ThemeContext";
|
|
||||||
import { RolesListPage } from "./role-management/RolesListPage";
|
|
||||||
import { useSearchParams } from "react-router-dom";
|
|
||||||
|
|
||||||
type SettingsTab =
|
type SettingsTab =
|
||||||
| "referrals"
|
| "referrals"
|
||||||
|
|
@ -220,57 +221,6 @@ function SecurityTab({ memberId }: { memberId: number }) {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function NotificationsTab() {
|
|
||||||
const [emailNotifs, setEmailNotifs] = useState(true);
|
|
||||||
const [pushNotifs, setPushNotifs] = useState(true);
|
|
||||||
const [loginAlerts, setLoginAlerts] = useState(true);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="border border-grayScale-100 rounded-[6px] overflow-hidden animate-in fade-in slide-in-from-bottom-2 duration-300">
|
|
||||||
<div className="h-1 w-full bg-brand-500" />
|
|
||||||
<CardHeader className="pb-3 border-b border-grayScale-50">
|
|
||||||
<CardTitle className="text-sm font-bold text-grayScale-900">
|
|
||||||
Notification Preferences
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-1 pb-6">
|
|
||||||
<SettingRow
|
|
||||||
icon={Bell}
|
|
||||||
title="Email Notifications"
|
|
||||||
description="Receive important updates via email"
|
|
||||||
>
|
|
||||||
<Toggle
|
|
||||||
enabled={emailNotifs}
|
|
||||||
onToggle={() => setEmailNotifs(!emailNotifs)}
|
|
||||||
/>
|
|
||||||
</SettingRow>
|
|
||||||
<Separator className="bg-grayScale-50" />
|
|
||||||
<SettingRow
|
|
||||||
icon={Bell}
|
|
||||||
title="Push Notifications"
|
|
||||||
description="Get notified in the browser"
|
|
||||||
>
|
|
||||||
<Toggle
|
|
||||||
enabled={pushNotifs}
|
|
||||||
onToggle={() => setPushNotifs(!pushNotifs)}
|
|
||||||
/>
|
|
||||||
</SettingRow>
|
|
||||||
<Separator className="bg-grayScale-50" />
|
|
||||||
<SettingRow
|
|
||||||
icon={Shield}
|
|
||||||
title="Login Alerts"
|
|
||||||
description="Get notified when someone logs into your account"
|
|
||||||
>
|
|
||||||
<Toggle
|
|
||||||
enabled={loginAlerts}
|
|
||||||
onToggle={() => setLoginAlerts(!loginAlerts)}
|
|
||||||
/>
|
|
||||||
</SettingRow>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AppearanceTab() {
|
function AppearanceTab() {
|
||||||
const { theme, setTheme, resolvedTheme, systemTheme } = useTheme();
|
const { theme, setTheme, resolvedTheme, systemTheme } = useTheme();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,24 @@
|
||||||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||||
import { useEffect, useState, type ElementType, type ReactNode } from "react"
|
import {
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
BadgeCheck,
|
||||||
|
Bell,
|
||||||
|
BookOpen,
|
||||||
|
CheckCircle2,
|
||||||
|
ChevronDown,
|
||||||
|
CreditCard,
|
||||||
|
DollarSign,
|
||||||
|
FolderOpen,
|
||||||
|
HelpCircle,
|
||||||
|
PlayCircle,
|
||||||
|
RefreshCw,
|
||||||
|
RotateCcw,
|
||||||
|
TrendingDown,
|
||||||
|
TrendingUp,
|
||||||
|
Users,
|
||||||
|
UsersRound,
|
||||||
|
Video,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useEffect, useState, type ElementType, type ReactNode } from "react";
|
||||||
import {
|
import {
|
||||||
Area,
|
Area,
|
||||||
AreaChart,
|
AreaChart,
|
||||||
|
|
@ -14,70 +32,51 @@ import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
} from "recharts"
|
} from "recharts";
|
||||||
import alertSrc from "../../assets/Alert.svg"
|
import { getDashboard } from "../../api/analytics.api";
|
||||||
import {
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
||||||
Users,
|
import alertSrc from "../../assets/Alert.svg";
|
||||||
BadgeCheck,
|
import { AnalyticsTimeRangeFilter } from "../../components/analytics/AnalyticsTimeRangeFilter";
|
||||||
DollarSign,
|
import { getDashboardFilterLabel } from "../../components/analytics/AnalyticsTimeRangeFilter.shared";
|
||||||
BookOpen,
|
|
||||||
HelpCircle,
|
import { MonthlyRevenueBarChart, MonthlyRevenueTrendPanel, SensitiveYtdValue, analyticsSoftCardClass } from "../../components/analytics/SubscriptionRevenueVisuals";
|
||||||
Bell,
|
import { SUBSCRIPTION_CHART_COLORS } from "../../components/analytics/SubscriptionRevenueVisuals.shared";
|
||||||
UsersRound,
|
|
||||||
TrendingUp,
|
import { Badge } from "../../components/ui/badge";
|
||||||
TrendingDown,
|
import { Button } from "../../components/ui/button";
|
||||||
CreditCard,
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card";
|
||||||
Video,
|
|
||||||
FolderOpen,
|
|
||||||
RefreshCw,
|
|
||||||
ChevronDown,
|
|
||||||
PlayCircle,
|
|
||||||
RotateCcw,
|
|
||||||
CheckCircle2,
|
|
||||||
} from "lucide-react"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
|
||||||
import {
|
import {
|
||||||
SensitiveChart,
|
SensitiveChart,
|
||||||
SensitiveRevealProvider,
|
SensitiveRevealProvider,
|
||||||
SensitiveValue,
|
SensitiveValue,
|
||||||
} from "../../components/ui/sensitive-value"
|
} from "../../components/ui/sensitive-value";
|
||||||
import { Badge } from "../../components/ui/badge"
|
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { getDashboard } from "../../api/analytics.api"
|
|
||||||
import { AnalyticsTimeRangeFilter, getDashboardFilterLabel } from "../../components/analytics/AnalyticsTimeRangeFilter"
|
|
||||||
import {
|
|
||||||
MonthlyRevenueAreaChart,
|
|
||||||
MonthlyRevenueTrendPanel,
|
|
||||||
SensitiveYtdValue,
|
|
||||||
SUBSCRIPTION_CHART_COLORS,
|
|
||||||
analyticsSoftCardClass,
|
|
||||||
} from "../../components/analytics/SubscriptionRevenueVisuals"
|
|
||||||
import {
|
import {
|
||||||
|
aggregateRevenueByMonth,
|
||||||
|
formatAnalyticsLabel,
|
||||||
|
formatAnalyticsSeriesDate,
|
||||||
|
formatPercentRate,
|
||||||
|
formatRevenueAxisTick,
|
||||||
getPrimaryQuestionTypeSummary,
|
getPrimaryQuestionTypeSummary,
|
||||||
getSeriesPeriodLabel,
|
getSeriesPeriodLabel,
|
||||||
formatAnalyticsLabel,
|
|
||||||
getSubscriptionMetrics,
|
getSubscriptionMetrics,
|
||||||
getVideoLessonsSummary,
|
getVideoLessonsSummary,
|
||||||
formatPercentRate,
|
} from "../../lib/analytics";
|
||||||
formatAnalyticsSeriesDate,
|
import { formatAppDateTime } from "../../lib/datetime";
|
||||||
aggregateRevenueByMonth,
|
import { isUnassignedLabel } from "../../lib/displayValue.shared";
|
||||||
formatRevenueAxisTick,
|
|
||||||
} from "../../lib/analytics"
|
|
||||||
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
|
|
||||||
import { formatAppDateTime } from "../../lib/datetime"
|
|
||||||
import { isUnassignedLabel } from "../../lib/displayValue"
|
|
||||||
import {
|
import {
|
||||||
displayUserAgeGroup,
|
displayUserAgeGroup,
|
||||||
|
displayUserCountry,
|
||||||
|
displayUserEducationLevel,
|
||||||
|
displayUserKnowledgeLevel,
|
||||||
|
displayUserLanguageChallenge,
|
||||||
|
displayUserLearningGoal,
|
||||||
displayUserOccupation,
|
displayUserOccupation,
|
||||||
displayUserRegion,
|
displayUserRegion,
|
||||||
displayUserEducationLevel,
|
|
||||||
displayUserLearningGoal,
|
|
||||||
displayUserLanguageChallenge,
|
|
||||||
displayUserCountry,
|
|
||||||
displayUserKnowledgeLevel,
|
|
||||||
mergeAnalyticsRowsByDisplayLabel,
|
mergeAnalyticsRowsByDisplayLabel,
|
||||||
} from "../../lib/userProfileFieldDisplay"
|
} from "../../lib/userProfileFieldDisplay";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types";
|
||||||
|
|
||||||
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
|
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
|
||||||
|
|
||||||
|
|
@ -158,14 +157,15 @@ function BreakdownList({
|
||||||
title,
|
title,
|
||||||
data,
|
data,
|
||||||
total,
|
total,
|
||||||
scrollable: _scrollable,
|
|
||||||
formatRowLabel,
|
formatRowLabel,
|
||||||
|
showPercent = true,
|
||||||
}: {
|
}: {
|
||||||
title: string
|
title: string
|
||||||
data: LabelCount[]
|
data: LabelCount[]
|
||||||
total?: number
|
total?: number
|
||||||
scrollable?: boolean
|
scrollable?: boolean
|
||||||
formatRowLabel?: (label: string) => string
|
formatRowLabel?: (label: string) => string
|
||||||
|
showPercent?: boolean
|
||||||
}) {
|
}) {
|
||||||
const labelFn = formatRowLabel ?? formatAnalyticsLabel
|
const labelFn = formatRowLabel ?? formatAnalyticsLabel
|
||||||
const merged = mergeAnalyticsRowsByDisplayLabel(data, labelFn).filter(
|
const merged = mergeAnalyticsRowsByDisplayLabel(data, labelFn).filter(
|
||||||
|
|
@ -199,7 +199,7 @@ function BreakdownList({
|
||||||
</div>
|
</div>
|
||||||
<span className="font-semibold text-grayScale-700">
|
<span className="font-semibold text-grayScale-700">
|
||||||
{item.count.toLocaleString()}
|
{item.count.toLocaleString()}
|
||||||
<span className="ml-1 font-normal text-grayScale-400">({pct.toFixed(0)}%)</span>
|
<span className="ml-1 font-normal text-grayScale-400">{showPercent ? `(${pct.toFixed(0)}%)` : ""}</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-grayScale-100">
|
<div className="h-1.5 w-full overflow-hidden rounded-full bg-grayScale-100">
|
||||||
|
|
@ -639,7 +639,7 @@ export function AnalyticsPage() {
|
||||||
formatRowLabel={displayUserLearningGoal}
|
formatRowLabel={displayUserLearningGoal}
|
||||||
/>
|
/>
|
||||||
<BreakdownList
|
<BreakdownList
|
||||||
title="Language challenge"
|
title="Artistry challenge"
|
||||||
data={users.by_language_challange ?? []}
|
data={users.by_language_challange ?? []}
|
||||||
total={users.total_users}
|
total={users.total_users}
|
||||||
formatRowLabel={displayUserLanguageChallenge}
|
formatRowLabel={displayUserLanguageChallenge}
|
||||||
|
|
@ -682,7 +682,7 @@ export function AnalyticsPage() {
|
||||||
/>
|
/>
|
||||||
{(users.by_knowledge_level?.length ?? 0) > 0 ? (
|
{(users.by_knowledge_level?.length ?? 0) > 0 ? (
|
||||||
<BreakdownList
|
<BreakdownList
|
||||||
title="Knowledge level"
|
title="Makeup experience"
|
||||||
data={users.by_knowledge_level ?? []}
|
data={users.by_knowledge_level ?? []}
|
||||||
total={users.total_users}
|
total={users.total_users}
|
||||||
formatRowLabel={displayUserKnowledgeLevel}
|
formatRowLabel={displayUserKnowledgeLevel}
|
||||||
|
|
@ -703,7 +703,7 @@ export function AnalyticsPage() {
|
||||||
scrollable
|
scrollable
|
||||||
/>
|
/>
|
||||||
<BreakdownList
|
<BreakdownList
|
||||||
title="Language challenge"
|
title="Artistry challenge"
|
||||||
data={users.by_language_challange ?? []}
|
data={users.by_language_challange ?? []}
|
||||||
total={users.total_users}
|
total={users.total_users}
|
||||||
formatRowLabel={displayUserLanguageChallenge}
|
formatRowLabel={displayUserLanguageChallenge}
|
||||||
|
|
@ -778,10 +778,10 @@ export function AnalyticsPage() {
|
||||||
ytdValue={<SensitiveYtdValue amount={payments.total_revenue} />}
|
ytdValue={<SensitiveYtdValue amount={payments.total_revenue} />}
|
||||||
ytdLabel="Period total"
|
ytdLabel="Period total"
|
||||||
>
|
>
|
||||||
<MonthlyRevenueAreaChart
|
<MonthlyRevenueBarChart
|
||||||
data={monthlyRevenueTrendData}
|
data={monthlyRevenueTrendData}
|
||||||
xKey={useMonthlyRevenueTrend ? "month" : "date"}
|
xKey={useMonthlyRevenueTrend ? "month" : "date"}
|
||||||
gradientId="analyticsSubsRevenueFill"
|
|
||||||
height={260}
|
height={260}
|
||||||
yTickFormatter={formatRevenueAxisTick}
|
yTickFormatter={formatRevenueAxisTick}
|
||||||
/>
|
/>
|
||||||
|
|
@ -936,7 +936,8 @@ export function AnalyticsPage() {
|
||||||
<div className="grid items-start gap-4 lg:grid-cols-2">
|
<div className="grid items-start gap-4 lg:grid-cols-2">
|
||||||
{examPrep && (
|
{examPrep && (
|
||||||
<BreakdownList
|
<BreakdownList
|
||||||
title="Exam prep catalog"
|
title="Makeup course catalog"
|
||||||
|
showPercent={false}
|
||||||
data={[
|
data={[
|
||||||
{ label: "Catalog courses", count: examPrep.catalog_courses },
|
{ label: "Catalog courses", count: examPrep.catalog_courses },
|
||||||
{ label: "Units", count: examPrep.units },
|
{ label: "Units", count: examPrep.units },
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
|
||||||
import { Link, Navigate, useNavigate, useSearchParams } from "react-router-dom";
|
|
||||||
import { Eye, EyeOff } from "lucide-react";
|
import { Eye, EyeOff } from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { Link, Navigate, useNavigate, useSearchParams } from "react-router-dom";
|
||||||
|
import { getApiErrorMessage } from "../../lib/apiErrors";
|
||||||
|
|
||||||
import { BrandLogo } from "../../components/brand/BrandLogo";
|
import { BrandLogo } from "../../components/brand/BrandLogo";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
|
|
@ -9,13 +10,13 @@ import { Label } from "../../components/ui/label";
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
||||||
|
|
||||||
|
|
||||||
import { login, loginWithGoogle } from "../../api/auth.api";
|
|
||||||
import type { LoginRequest } from "../../types/auth.types";
|
|
||||||
import type { LoginResult } from "../../api/auth.api";
|
|
||||||
import { saveTeamSessionFromLoginResult, getAccessToken } from "../../lib/teamAuthStorage";
|
|
||||||
import { getDefaultAppHome } from "../../lib/adminAccess";
|
|
||||||
import { getNormalizedSessionTeamRole } from "../../lib/teamRole";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import type { LoginResult } from "../../api/auth.api";
|
||||||
|
import { login, loginWithGoogle } from "../../api/auth.api";
|
||||||
|
import { getDefaultAppHome } from "../../lib/adminAccess";
|
||||||
|
import { getAccessToken, saveTeamSessionFromLoginResult } from "../../lib/teamAuthStorage";
|
||||||
|
import { getNormalizedSessionTeamRole } from "../../lib/teamRole";
|
||||||
|
import type { LoginRequest } from "../../types/auth.types";
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Window {
|
interface Window {
|
||||||
|
|
@ -126,9 +127,9 @@ export function LoginPage() {
|
||||||
try {
|
try {
|
||||||
const result = await loginWithGoogle(response.credential);
|
const result = await loginWithGoogle(response.credential);
|
||||||
storeTokensAndRedirect(result);
|
storeTokensAndRedirect(result);
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setError(
|
setError(
|
||||||
err.response?.data?.message || "Google sign-in failed. Please try again."
|
getApiErrorMessage(err, "Google sign-in failed. Please try again.")
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setGoogleLoading(false);
|
setGoogleLoading(false);
|
||||||
|
|
@ -209,8 +210,8 @@ export function LoginPage() {
|
||||||
try {
|
try {
|
||||||
const res: LoginResult = await login(payload);
|
const res: LoginResult = await login(payload);
|
||||||
storeTokensAndRedirect(res);
|
storeTokensAndRedirect(res);
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setError(err.response?.data?.message || "Invalid email or password");
|
setError(getApiErrorMessage(err, "Invalid email or password"));
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|
@ -233,36 +234,36 @@ export function LoginPage() {
|
||||||
const googleClientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
const googleClientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative flex min-h-dvh overflow-y-auto bg-[#f4f2ec]">
|
<div className="relative flex min-h-dvh overflow-y-auto bg-background">
|
||||||
{/* Decorative left panel */}
|
{/* Decorative left panel */}
|
||||||
<div className="hidden lg:flex lg:w-1/2 xl:w-[55%] items-center justify-center bg-[#163d35] relative">
|
<div className="hidden lg:flex lg:w-1/2 xl:w-[55%] items-center justify-center bg-[#111111] relative">
|
||||||
{/* Abstract decorative shapes */}
|
{/* Abstract decorative shapes */}
|
||||||
<div className="absolute inset-0 overflow-hidden">
|
<div className="absolute inset-0 overflow-hidden">
|
||||||
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full border border-white/10" />
|
<div className="absolute -left-20 -top-20 h-96 w-96 rounded-full border border-white/10" />
|
||||||
<div className="absolute -bottom-32 -right-16 h-[500px] w-[500px] rounded-full border border-white/10" />
|
<div className="absolute -bottom-32 -right-16 h-[500px] w-[500px] rounded-full border border-white/10" />
|
||||||
<div className="absolute left-1/3 top-1/4 h-64 w-64 rounded-full bg-[#d3a76a]/10 blur-3xl" />
|
<div className="absolute left-1/3 top-1/4 h-64 w-64 rounded-full bg-[#D4D4D4]/10 blur-3xl" />
|
||||||
<div className="absolute bottom-1/4 left-1/4 h-48 w-48 rotate-45 rounded-3xl bg-white/[0.03]" />
|
<div className="absolute bottom-1/4 left-1/4 h-48 w-48 rotate-45 rounded-3xl bg-white/[0.03]" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="relative z-10 max-w-lg px-12 text-left">
|
<div className="relative z-10 max-w-lg px-12 text-left">
|
||||||
{/* Brand logo */}
|
{/* Brand logo */}
|
||||||
<BrandLogo variant="light" className="mb-20 h-14" />
|
<BrandLogo variant="light" className="mb-20 h-14" />
|
||||||
<p className="mb-5 text-xs font-semibold uppercase tracking-[0.28em] text-[#e4c28f]">The academy, in sync</p>
|
<p className="mb-5 text-xs font-semibold uppercase tracking-[0.28em] text-[#D4D4D4]">MAKEUP ARTISTRY / ACADEMY WORKSPACE</p>
|
||||||
<h2 className="max-w-md text-5xl font-semibold leading-[1.08] tracking-tight text-white xl:text-6xl">Make room for better learning.</h2>
|
<h2 className="max-w-md text-5xl font-semibold leading-[1.08] tracking-tight text-white xl:text-6xl">The art of beauty. The craft of teaching.</h2>
|
||||||
<p className="mt-6 max-w-sm text-base leading-relaxed text-white/65">
|
<p className="mt-6 max-w-sm text-base leading-relaxed text-white/65">
|
||||||
Manage your academy, track student progress, and streamline
|
Nurture creative talent, curate makeup artistry lessons, and
|
||||||
operations — all from one powerful dashboard.
|
guide every student from first brushstroke to professional confidence.
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-14 flex items-center gap-3 text-sm text-white/70">
|
<div className="mt-14 flex items-center gap-3 text-sm text-white/70">
|
||||||
<span className="h-2 w-2 rounded-full bg-[#d3a76a]" />
|
<span className="h-2 w-2 rounded-full bg-[#D4D4D4]" />
|
||||||
<span>Rezina Academy · Admin workspace</span>
|
<span>Rezina Academy · Admin workspace</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right panel – login form */}
|
{/* Right panel – login form */}
|
||||||
<div className="flex w-full flex-col items-center justify-center bg-[#f4f2ec] px-6 py-12 lg:w-1/2 xl:w-[45%]">
|
<div className="flex w-full flex-col items-center justify-center bg-background px-6 py-12 lg:w-1/2 xl:w-[45%]">
|
||||||
<div className="w-full max-w-[420px] rounded-[28px] border border-[#e8e5dc] bg-white px-7 py-9 shadow-[0_24px_70px_rgba(36,48,40,0.08)] sm:px-10 sm:py-11">
|
<div className="w-full max-w-[420px] rounded-[10px] border border-border bg-card px-7 py-9 shadow-[0_24px_70px_rgba(0,0,0,0.08)] sm:px-10 sm:py-11">
|
||||||
{/* Mobile-only logo */}
|
{/* Mobile-only logo */}
|
||||||
<div className="mb-10 flex justify-center lg:hidden">
|
<div className="mb-10 flex justify-center lg:hidden">
|
||||||
<BrandLogo />
|
<BrandLogo />
|
||||||
|
|
@ -270,13 +271,13 @@ export function LoginPage() {
|
||||||
|
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="mb-10">
|
<div className="mb-10">
|
||||||
<p className="mb-2 text-xs font-semibold uppercase tracking-[0.2em] text-[#8b704d]">
|
<p className="mb-2 text-xs font-semibold uppercase tracking-[0.2em] text-brand-600">
|
||||||
Admin Portal
|
Admin Portal
|
||||||
</p>
|
</p>
|
||||||
<h1 className="mb-2 text-3xl font-semibold tracking-tight text-[#24352f]">
|
<h1 className="mb-2 text-4xl font-semibold tracking-tight text-foreground">
|
||||||
Welcome back
|
Welcome back
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm leading-relaxed text-[#78817b]">
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||||
Sign in to your account to continue
|
Sign in to your account to continue
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -313,7 +314,7 @@ export function LoginPage() {
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleGoogleClick}
|
onClick={handleGoogleClick}
|
||||||
disabled={googleLoading || !googleReady}
|
disabled={googleLoading || !googleReady}
|
||||||
className="group mb-6 flex w-full items-center justify-center gap-3 rounded-xl border border-[#e5e7e2] bg-white px-4 py-3 text-sm font-medium text-[#34443d] transition-all duration-200 hover:border-[#a9b9ac] hover:bg-[#f8faf7] hover:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#31644f]/30 disabled:cursor-not-allowed disabled:opacity-60"
|
className="group mb-6 flex w-full items-center justify-center gap-3 rounded-xl border border-border bg-white px-4 py-3 text-sm font-medium text-foreground transition-all duration-200 hover:border-brand-300 hover:bg-brand-50 hover:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500/30 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
>
|
>
|
||||||
{googleLoading ? (
|
{googleLoading ? (
|
||||||
<SpinnerIcon className="h-5 w-5" />
|
<SpinnerIcon className="h-5 w-5" />
|
||||||
|
|
@ -342,7 +343,7 @@ export function LoginPage() {
|
||||||
<div>
|
<div>
|
||||||
<Label
|
<Label
|
||||||
htmlFor="email"
|
htmlFor="email"
|
||||||
className="mb-1.5 block text-sm font-medium text-[#34443d]"
|
className="mb-1.5 block text-sm font-medium text-foreground"
|
||||||
>
|
>
|
||||||
Email address
|
Email address
|
||||||
</Label>
|
</Label>
|
||||||
|
|
@ -369,13 +370,13 @@ export function LoginPage() {
|
||||||
<div className="mb-1.5 flex items-center justify-between">
|
<div className="mb-1.5 flex items-center justify-between">
|
||||||
<Label
|
<Label
|
||||||
htmlFor="password"
|
htmlFor="password"
|
||||||
className="block text-sm font-medium text-[#34443d]"
|
className="block text-sm font-medium text-foreground"
|
||||||
>
|
>
|
||||||
Password
|
Password
|
||||||
</Label>
|
</Label>
|
||||||
<Link
|
<Link
|
||||||
to="/forgot-password"
|
to="/forgot-password"
|
||||||
className="text-xs font-semibold text-[#31644f] transition-colors hover:text-[#214b39]"
|
className="text-xs font-semibold text-brand-600 transition-colors hover:text-brand-500"
|
||||||
>
|
>
|
||||||
Forgot password?
|
Forgot password?
|
||||||
</Link>
|
</Link>
|
||||||
|
|
@ -410,7 +411,7 @@ export function LoginPage() {
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="mt-2 h-12 w-full rounded-xl bg-[#244f3e] text-sm font-semibold tracking-wide text-white shadow-[0_8px_18px_rgba(36,79,62,0.18)] transition hover:bg-[#1c4434]"
|
className="mt-2 h-12 w-full rounded-xl bg-brand-500 text-sm font-semibold tracking-wide text-white shadow-[0_8px_18px_rgba(0,0,0,0.18)] transition hover:bg-brand-600"
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
>
|
>
|
||||||
{loading ? "Signing in…" : "Sign in"}
|
{loading ? "Signing in…" : "Sign in"}
|
||||||
|
|
@ -418,7 +419,7 @@ export function LoginPage() {
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<div className="mt-9 border-t border-[#eeeee9] pt-6 text-center text-xs text-grayScale-400">
|
<div className="mt-9 border-t border-border pt-6 text-center text-xs text-grayScale-400">
|
||||||
<p>© {new Date().getFullYear()} Rezina Academy · All rights reserved</p>
|
<p>© {new Date().getFullYear()} Rezina Academy · All rights reserved</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,736 +0,0 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useMemo, useState, type ChangeEvent } from "react"
|
|
||||||
import { ArrowLeft, ArrowRight, Check, GripVertical, Plus, Rocket, Trash2, Upload } from "lucide-react"
|
|
||||||
import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { addQuestionToSet, createLesson, createQuestion } from "../../api/courses.api"
|
|
||||||
import { uploadVideoFile } from "../../api/files.api"
|
|
||||||
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
|
|
||||||
import { useVideoUpload } from "../../hooks/useVideoUpload"
|
|
||||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
|
|
||||||
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields"
|
|
||||||
import type { PracticeQuestionDynamicRow } from "../../components/content-management/PracticeQuestionEditorFields"
|
|
||||||
import { buildDynamicQuestionPayload } from "../../lib/practiceDynamicQuestionPayload"
|
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { Card } from "../../components/ui/card"
|
|
||||||
import { Input } from "../../components/ui/input"
|
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
|
||||||
import type { QuestionOption } from "../../types/course.types"
|
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
|
||||||
|
|
||||||
type Step = 1 | 2 | 3 | 4
|
|
||||||
type QuestionType = "MCQ" | "TRUE_FALSE" | "SHORT" | "AUDIO" | "DYNAMIC"
|
|
||||||
type DifficultyLevel = "EASY" | "MEDIUM" | "HARD"
|
|
||||||
type ResultStatus = "success" | "error"
|
|
||||||
|
|
||||||
interface MCQOption {
|
|
||||||
text: string
|
|
||||||
isCorrect: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Question {
|
|
||||||
id: string
|
|
||||||
questionText: string
|
|
||||||
questionType: QuestionType
|
|
||||||
difficultyLevel: DifficultyLevel
|
|
||||||
points: number
|
|
||||||
tips: string
|
|
||||||
explanation: string
|
|
||||||
options: MCQOption[]
|
|
||||||
voicePrompt: string
|
|
||||||
sampleAnswerVoicePrompt: string
|
|
||||||
audioCorrectAnswerText: string
|
|
||||||
shortAnswers: string[]
|
|
||||||
imageUrl: string
|
|
||||||
questionTypeDefinitionId: number | null
|
|
||||||
dynamicStimulusRows: PracticeQuestionDynamicRow[]
|
|
||||||
dynamicResponseRows: PracticeQuestionDynamicRow[]
|
|
||||||
dynamicFieldValues: Record<string, string>
|
|
||||||
}
|
|
||||||
|
|
||||||
const STEPS = [
|
|
||||||
{ number: 1, label: "Context" },
|
|
||||||
{ number: 2, label: "Questions" },
|
|
||||||
{ number: 3, label: "Review" },
|
|
||||||
]
|
|
||||||
|
|
||||||
function createEmptyQuestion(id: string): Question {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
questionText: "",
|
|
||||||
questionType: "MCQ",
|
|
||||||
difficultyLevel: "EASY",
|
|
||||||
points: 1,
|
|
||||||
tips: "",
|
|
||||||
explanation: "",
|
|
||||||
options: [
|
|
||||||
{ text: "", isCorrect: true },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
{ text: "", isCorrect: false },
|
|
||||||
],
|
|
||||||
voicePrompt: "",
|
|
||||||
sampleAnswerVoicePrompt: "",
|
|
||||||
audioCorrectAnswerText: "",
|
|
||||||
shortAnswers: [],
|
|
||||||
imageUrl: "",
|
|
||||||
questionTypeDefinitionId: null,
|
|
||||||
dynamicStimulusRows: [],
|
|
||||||
dynamicResponseRows: [],
|
|
||||||
dynamicFieldValues: {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function introVideoUrlFromUploadResponse(data: { url?: string; embed_url?: string } | undefined): string | null {
|
|
||||||
if (!data) return null
|
|
||||||
const pageUrl = data.url?.trim()
|
|
||||||
const embedUrl = data.embed_url?.trim()
|
|
||||||
if (embedUrl) {
|
|
||||||
const hashFromUrl = pageUrl ? pageUrl.split("/").filter(Boolean).at(-1) : undefined
|
|
||||||
return hashFromUrl ? `${embedUrl}?h=${hashFromUrl}` : embedUrl
|
|
||||||
}
|
|
||||||
return pageUrl || null
|
|
||||||
}
|
|
||||||
|
|
||||||
function toVimeoEmbedUrl(rawUrl: string): string | null {
|
|
||||||
try {
|
|
||||||
const parsed = new URL(rawUrl.trim())
|
|
||||||
const host = parsed.hostname.toLowerCase()
|
|
||||||
if (!host.includes("vimeo.com")) return null
|
|
||||||
if (host.includes("player.vimeo.com") && parsed.pathname.includes("/video/")) return parsed.toString()
|
|
||||||
const segments = parsed.pathname.split("/").filter(Boolean)
|
|
||||||
const videoId = segments.find((segment) => /^\d+$/.test(segment))
|
|
||||||
if (!videoId) return null
|
|
||||||
const hash = parsed.searchParams.get("h")
|
|
||||||
return hash
|
|
||||||
? `https://player.vimeo.com/video/${videoId}?h=${encodeURIComponent(hash)}`
|
|
||||||
: `https://player.vimeo.com/video/${videoId}`
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isDirectVideoFile(url: string): boolean {
|
|
||||||
const clean = url.split("?")[0].toLowerCase()
|
|
||||||
return /\.(mp4|webm|ogg|mov|m4v)$/.test(clean)
|
|
||||||
}
|
|
||||||
|
|
||||||
function questionTypeLabel(type: QuestionType): string {
|
|
||||||
if (type === "TRUE_FALSE") return "True/False"
|
|
||||||
if (type === "SHORT") return "Short Answer"
|
|
||||||
if (type === "AUDIO") return "Audio"
|
|
||||||
if (type === "DYNAMIC") return "Dynamic"
|
|
||||||
return "Multiple Choice"
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AddNewLessonPage() {
|
|
||||||
const { categoryId, courseId, subModuleId } = useParams()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const location = useLocation()
|
|
||||||
|
|
||||||
const backTo = useMemo(() => {
|
|
||||||
if (location.pathname.includes("/content/human-language/") && location.pathname.includes("/sub-module/")) {
|
|
||||||
return `/content/human-language/${categoryId}/${courseId}/sub-module/${subModuleId}`
|
|
||||||
}
|
|
||||||
return `/content/category/${categoryId}/courses/${courseId}/sub-modules/${subModuleId}`
|
|
||||||
}, [categoryId, courseId, subModuleId, location.pathname])
|
|
||||||
|
|
||||||
const [currentStep, setCurrentStep] = useState<Step>(1)
|
|
||||||
const [saving, setSaving] = useState(false)
|
|
||||||
const [resultStatus, setResultStatus] = useState<ResultStatus | null>(null)
|
|
||||||
const [resultMessage, setResultMessage] = useState("")
|
|
||||||
const [lastSavedStatus, setLastSavedStatus] = useState<"DRAFT" | "PUBLISHED" | null>(null)
|
|
||||||
|
|
||||||
const [lessonTitle, setLessonTitle] = useState("")
|
|
||||||
const [lessonDescription, setLessonDescription] = useState("")
|
|
||||||
const [introVideoUrl, setIntroVideoUrl] = useState("")
|
|
||||||
const {
|
|
||||||
upload: uploadIntroVideo,
|
|
||||||
cancel: cancelIntroVideo,
|
|
||||||
progress: introVideoProgress,
|
|
||||||
isBusy: uploadingIntroVideo,
|
|
||||||
} = useVideoUpload()
|
|
||||||
const [importingIntroVideoUrl, setImportingIntroVideoUrl] = useState(false)
|
|
||||||
const [questions, setQuestions] = useState<Question[]>([createEmptyQuestion("1")])
|
|
||||||
|
|
||||||
const handleNext = () => setCurrentStep((s) => (s < 3 ? ((s + 1) as Step) : s))
|
|
||||||
const handleBack = () => setCurrentStep((s) => (s > 1 ? ((s - 1) as Step) : s))
|
|
||||||
|
|
||||||
const handleIntroVideoFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files?.[0]
|
|
||||||
event.target.value = ""
|
|
||||||
if (!file) return
|
|
||||||
try {
|
|
||||||
const res = await uploadIntroVideo(file, {
|
|
||||||
title: lessonTitle.trim() || file.name.replace(/\.[^.]+$/, "") || "Lesson intro",
|
|
||||||
description: lessonDescription.trim() || undefined,
|
|
||||||
})
|
|
||||||
if (res) {
|
|
||||||
setIntroVideoUrl(vimeoResultToStoredUrl(res))
|
|
||||||
toast.success("Intro video uploaded")
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof DOMException && error.name === "AbortError") return
|
|
||||||
console.error("Failed to upload lesson intro video:", error)
|
|
||||||
notifyApiError(error, "Failed to upload intro video")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleIntroVideoUrlBlur = async () => {
|
|
||||||
const source = introVideoUrl.trim()
|
|
||||||
if (!source || !/^https?:\/\//i.test(source)) return
|
|
||||||
const vimeoEmbed = toVimeoEmbedUrl(source)
|
|
||||||
if (vimeoEmbed) {
|
|
||||||
setIntroVideoUrl(vimeoEmbed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (isDirectVideoFile(source)) {
|
|
||||||
setIntroVideoUrl(source)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// For non-direct URLs, automatically try server-side import via /files/upload.
|
|
||||||
setImportingIntroVideoUrl(true)
|
|
||||||
try {
|
|
||||||
const uploadRes = await uploadVideoFile(source, {
|
|
||||||
title: lessonTitle.trim() || "Lesson intro",
|
|
||||||
description: lessonDescription.trim() || undefined,
|
|
||||||
})
|
|
||||||
const finalUrl = introVideoUrlFromUploadResponse(uploadRes.data?.data)
|
|
||||||
if (!finalUrl) throw new Error("Missing uploaded video url")
|
|
||||||
setIntroVideoUrl(finalUrl)
|
|
||||||
toast.success("Intro video URL imported")
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to import intro video URL:", error)
|
|
||||||
notifyApiError(error, "Failed to import intro video URL")
|
|
||||||
} finally {
|
|
||||||
setImportingIntroVideoUrl(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const introVideoPreview = useMemo(() => {
|
|
||||||
const raw = introVideoUrl.trim()
|
|
||||||
if (!raw) return null
|
|
||||||
const vimeoEmbedUrl = toVimeoEmbedUrl(raw)
|
|
||||||
if (vimeoEmbedUrl) return { kind: "vimeo" as const, url: vimeoEmbedUrl }
|
|
||||||
if (isDirectVideoFile(raw)) return { kind: "video" as const, url: raw }
|
|
||||||
return null
|
|
||||||
}, [introVideoUrl])
|
|
||||||
|
|
||||||
const reviewQuestions = useMemo(() => questions, [questions])
|
|
||||||
|
|
||||||
const addQuestion = () => setQuestions((prev) => [...prev, createEmptyQuestion(String(Date.now()))])
|
|
||||||
const removeQuestion = (id: string) => setQuestions((prev) => (prev.length > 1 ? prev.filter((q) => q.id !== id) : prev))
|
|
||||||
const updateQuestion = (id: string, updates: Partial<Question>) =>
|
|
||||||
setQuestions((prev) => prev.map((q) => (q.id === id ? { ...q, ...updates } : q)))
|
|
||||||
|
|
||||||
const saveLesson = async (status: "DRAFT" | "PUBLISHED") => {
|
|
||||||
if (!subModuleId) {
|
|
||||||
toast.error("Missing sub-module id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setSaving(true)
|
|
||||||
try {
|
|
||||||
const lessonRes = await createLesson({
|
|
||||||
sub_module_id: Number(subModuleId),
|
|
||||||
title: lessonTitle.trim() || "Untitled Lesson",
|
|
||||||
description: lessonDescription.trim() || undefined,
|
|
||||||
intro_video_url: introVideoUrl.trim() || undefined,
|
|
||||||
status,
|
|
||||||
})
|
|
||||||
|
|
||||||
const questionSetId = lessonRes.data?.data?.id
|
|
||||||
if (questionSetId) {
|
|
||||||
for (let i = 0; i < questions.length; i++) {
|
|
||||||
const q = questions[i]
|
|
||||||
if (!q.questionText.trim()) continue
|
|
||||||
|
|
||||||
if (q.questionType === "DYNAMIC") {
|
|
||||||
if (q.questionTypeDefinitionId == null || q.questionTypeDefinitionId <= 0) {
|
|
||||||
toast.error(`Question ${i + 1}: select a question type definition for dynamic questions.`)
|
|
||||||
setSaving(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const missingStimulus = q.dynamicStimulusRows.find(
|
|
||||||
(row) =>
|
|
||||||
row.required &&
|
|
||||||
!(q.dynamicFieldValues[`stimulus:${row.id}`]?.trim()),
|
|
||||||
)
|
|
||||||
if (missingStimulus) {
|
|
||||||
toast.error(
|
|
||||||
`Question ${i + 1}: fill required stimulus "${missingStimulus.label || missingStimulus.id}".`,
|
|
||||||
)
|
|
||||||
setSaving(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const missingResponse = q.dynamicResponseRows.find(
|
|
||||||
(row) =>
|
|
||||||
row.required &&
|
|
||||||
!(q.dynamicFieldValues[`response:${row.id}`]?.trim()),
|
|
||||||
)
|
|
||||||
if (missingResponse) {
|
|
||||||
toast.error(
|
|
||||||
`Question ${i + 1}: fill required response "${missingResponse.label || missingResponse.id}".`,
|
|
||||||
)
|
|
||||||
setSaving(false)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const options: QuestionOption[] =
|
|
||||||
q.questionType === "MCQ"
|
|
||||||
? q.options.map((opt, idx) => ({
|
|
||||||
option_order: idx + 1,
|
|
||||||
option_text: opt.text,
|
|
||||||
is_correct: opt.isCorrect,
|
|
||||||
}))
|
|
||||||
: []
|
|
||||||
|
|
||||||
const dynamicPayload =
|
|
||||||
q.questionType === "DYNAMIC" && q.questionTypeDefinitionId != null
|
|
||||||
? buildDynamicQuestionPayload({
|
|
||||||
stimulusRows: q.dynamicStimulusRows,
|
|
||||||
responseRows: q.dynamicResponseRows,
|
|
||||||
fieldValues: q.dynamicFieldValues,
|
|
||||||
})
|
|
||||||
: undefined
|
|
||||||
|
|
||||||
const qRes = await createQuestion({
|
|
||||||
question_text: q.questionText,
|
|
||||||
question_type: q.questionType,
|
|
||||||
difficulty_level: q.difficultyLevel,
|
|
||||||
points: q.points,
|
|
||||||
tips: q.tips || undefined,
|
|
||||||
explanation: q.explanation || undefined,
|
|
||||||
status,
|
|
||||||
options: options.length > 0 ? options : undefined,
|
|
||||||
voice_prompt: q.questionType === "DYNAMIC" ? undefined : q.voicePrompt || undefined,
|
|
||||||
sample_answer_voice_prompt:
|
|
||||||
q.questionType === "DYNAMIC" ? undefined : q.sampleAnswerVoicePrompt || undefined,
|
|
||||||
audio_correct_answer_text:
|
|
||||||
q.questionType === "DYNAMIC" ? undefined : q.audioCorrectAnswerText || undefined,
|
|
||||||
image_url: q.questionType === "DYNAMIC" ? undefined : q.imageUrl.trim() || undefined,
|
|
||||||
short_answers:
|
|
||||||
q.questionType !== "DYNAMIC" && q.shortAnswers.length > 0 ? q.shortAnswers : undefined,
|
|
||||||
...(q.questionType === "DYNAMIC" && q.questionTypeDefinitionId != null && dynamicPayload
|
|
||||||
? {
|
|
||||||
question_type_definition_id: q.questionTypeDefinitionId,
|
|
||||||
dynamic_payload: dynamicPayload,
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
})
|
|
||||||
const questionId = qRes.data?.data?.id
|
|
||||||
if (questionId) {
|
|
||||||
await addQuestionToSet(questionSetId, { question_id: questionId, display_order: i + 1 })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setResultStatus("success")
|
|
||||||
setResultMessage(status === "PUBLISHED" ? "Lesson published successfully." : "Lesson saved as draft.")
|
|
||||||
setLastSavedStatus(status)
|
|
||||||
setCurrentStep(4)
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to save lesson:", error)
|
|
||||||
setResultStatus("error")
|
|
||||||
setResultMessage(error instanceof Error ? error.message : "Failed to save lesson")
|
|
||||||
setLastSavedStatus(null)
|
|
||||||
setCurrentStep(4)
|
|
||||||
} finally {
|
|
||||||
setSaving(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mx-auto w-full max-w-7xl px-4 pb-12 sm:px-6 lg:px-8">
|
|
||||||
<div className="space-y-5 sm:space-y-6">
|
|
||||||
{currentStep !== 4 ? (
|
|
||||||
<>
|
|
||||||
<Link
|
|
||||||
to={backTo}
|
|
||||||
className="group inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-sm font-medium text-grayScale-600 transition-colors hover:bg-brand-50 hover:text-brand-600"
|
|
||||||
>
|
|
||||||
<ArrowLeft className="h-4 w-4 transition-transform group-hover:-translate-x-0.5" />
|
|
||||||
Back to Sub-course
|
|
||||||
</Link>
|
|
||||||
<div className="border-b border-grayScale-100 pb-6 sm:pb-8">
|
|
||||||
<h1 className="text-2xl font-bold tracking-tight text-grayScale-900 sm:text-3xl">Add New Lesson</h1>
|
|
||||||
<p className="mt-2 max-w-3xl text-sm leading-relaxed text-grayScale-500 sm:text-[15px]">
|
|
||||||
Create a lesson backed by `question_sets` and attach it through `sub_module_lessons`.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-center rounded-2xl border border-grayScale-100 bg-grayScale-50/40 px-3 py-4 sm:px-6 sm:py-5">
|
|
||||||
{STEPS.map((step, index) => (
|
|
||||||
<div key={step.number} className="flex items-center">
|
|
||||||
<div className="flex flex-col items-center">
|
|
||||||
<div
|
|
||||||
className={`flex h-9 w-9 items-center justify-center rounded-full text-xs font-semibold shadow-sm transition-all duration-300 sm:h-10 sm:w-10 sm:text-sm ${
|
|
||||||
currentStep === step.number
|
|
||||||
? "bg-brand-500 text-white ring-4 ring-brand-100"
|
|
||||||
: currentStep > step.number
|
|
||||||
? "bg-brand-500 text-white"
|
|
||||||
: "border-2 border-grayScale-300 bg-white text-grayScale-400"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{currentStep > step.number ? <Check className="h-4 w-4" /> : step.number}
|
|
||||||
</div>
|
|
||||||
<span className="mt-2 text-xs font-semibold text-grayScale-500">{step.label}</span>
|
|
||||||
</div>
|
|
||||||
{index < STEPS.length - 1 ? (
|
|
||||||
<div className={`mx-4 h-0.5 w-20 ${currentStep > step.number ? "bg-brand-500" : "bg-grayScale-200"}`} />
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentStep === 1 ? (
|
|
||||||
<Card className="overflow-hidden border-grayScale-200/80 shadow-sm">
|
|
||||||
<div className="border-b border-grayScale-100 bg-gradient-to-r from-grayScale-50/80 to-white px-5 py-5 sm:px-8 sm:py-6">
|
|
||||||
<h2 className="text-lg font-semibold tracking-tight text-grayScale-900 sm:text-xl">Step 1: Context</h2>
|
|
||||||
<p className="mt-1.5 max-w-3xl text-sm leading-relaxed text-grayScale-500">
|
|
||||||
Define lesson metadata that will be stored in the linked question set.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-5 sm:p-8 lg:p-10">
|
|
||||||
<div className="mt-5 grid gap-8 lg:grid-cols-12">
|
|
||||||
<div className="space-y-4 lg:col-span-7">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="text-sm font-medium text-grayScale-700">Lesson title</label>
|
|
||||||
<Input
|
|
||||||
value={lessonTitle}
|
|
||||||
onChange={(e) => setLessonTitle(e.target.value)}
|
|
||||||
placeholder="Enter lesson title"
|
|
||||||
className="h-11"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="text-sm font-medium text-grayScale-700">Description</label>
|
|
||||||
<textarea
|
|
||||||
value={lessonDescription}
|
|
||||||
onChange={(e) => setLessonDescription(e.target.value)}
|
|
||||||
className="min-h-[96px] w-full rounded-lg border border-grayScale-200 px-3 py-2.5 text-sm transition-colors focus:border-grayScale-400 focus:outline-none focus:ring-2 focus:ring-grayScale-100"
|
|
||||||
placeholder="Enter lesson description"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="text-sm font-medium text-grayScale-700">Intro video URL (optional)</label>
|
|
||||||
<Input
|
|
||||||
value={introVideoUrl}
|
|
||||||
onChange={(e) => setIntroVideoUrl(e.target.value)}
|
|
||||||
onBlur={() => void handleIntroVideoUrlBlur()}
|
|
||||||
placeholder="https://..."
|
|
||||||
type="url"
|
|
||||||
inputMode="url"
|
|
||||||
autoComplete="off"
|
|
||||||
className="font-mono text-[13px]"
|
|
||||||
disabled={uploadingIntroVideo || importingIntroVideoUrl}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<label className="inline-flex cursor-pointer items-center gap-2 rounded-md border border-grayScale-200 px-3 py-2 text-xs text-grayScale-700 hover:bg-grayScale-50">
|
|
||||||
{uploadingIntroVideo ? <SpinnerIcon className="h-4 w-4" alt="" /> : <Upload className="h-4 w-4" />}
|
|
||||||
{uploadingIntroVideo ? introVideoProgress.message || "Uploading..." : "Upload video from computer"}
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept="video/*"
|
|
||||||
className="hidden"
|
|
||||||
onChange={handleIntroVideoFileChange}
|
|
||||||
disabled={uploadingIntroVideo || importingIntroVideoUrl}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
{introVideoUrl.trim() ? (
|
|
||||||
<Button type="button" variant="ghost" size="sm" onClick={() => setIntroVideoUrl("")}>
|
|
||||||
Clear URL
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
{introVideoProgress.phase !== "idle" ? (
|
|
||||||
<VideoUploadProgressBar
|
|
||||||
progress={introVideoProgress}
|
|
||||||
onCancel={cancelIntroVideo}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{introVideoPreview ? (
|
|
||||||
<div className="rounded-xl border border-grayScale-200 bg-grayScale-50/40 p-3">
|
|
||||||
<p className="mb-2 text-xs font-medium text-grayScale-500">Preview</p>
|
|
||||||
{introVideoPreview.kind === "vimeo" ? (
|
|
||||||
<div className="overflow-hidden rounded-lg border border-grayScale-200 bg-black">
|
|
||||||
<iframe
|
|
||||||
src={introVideoPreview.url}
|
|
||||||
title="Intro video preview"
|
|
||||||
className="aspect-video w-full"
|
|
||||||
allow="autoplay; fullscreen; picture-in-picture"
|
|
||||||
allowFullScreen
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<video
|
|
||||||
controls
|
|
||||||
src={introVideoPreview.url}
|
|
||||||
className="aspect-video w-full rounded-lg border border-grayScale-200 bg-black"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<aside className="space-y-4 lg:col-span-5">
|
|
||||||
<div className="rounded-xl border border-grayScale-200 bg-grayScale-50/40 p-5 shadow-sm">
|
|
||||||
<h3 className="text-xs font-semibold uppercase tracking-wider text-grayScale-500">Lesson schema mapping</h3>
|
|
||||||
<div className="mt-3 space-y-2 text-sm text-grayScale-700">
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">question_sets.title</span> ← Lesson title
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">question_sets.description</span> ← Description
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">question_sets.set_type</span> = QUIZ
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">sub_module_lessons.intro_video_url</span> ← Intro URL
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col-reverse items-stretch justify-between gap-3 border-t border-grayScale-100 bg-grayScale-50/30 px-5 py-4 sm:flex-row sm:items-center sm:px-8 sm:py-5">
|
|
||||||
<Button variant="ghost" onClick={() => navigate(backTo)} className="sm:w-auto">
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleNext}>
|
|
||||||
Next: Questions
|
|
||||||
<ArrowRight className="ml-2 h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentStep === 2 ? (
|
|
||||||
<div className="space-y-5">
|
|
||||||
{questions.map((question, index) => (
|
|
||||||
<Card key={question.id} className="border border-grayScale-200/90 border-l-4 border-l-grayScale-700 p-5 shadow-sm">
|
|
||||||
<div className="mb-4 flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<GripVertical className="h-4 w-4 text-grayScale-400" />
|
|
||||||
<span className="font-semibold">Question {index + 1}</span>
|
|
||||||
</div>
|
|
||||||
<button type="button" onClick={() => removeQuestion(question.id)} className="text-grayScale-400 hover:text-red-500">
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<PracticeQuestionEditorFields
|
|
||||||
value={{
|
|
||||||
questionText: question.questionText,
|
|
||||||
questionType: question.questionType,
|
|
||||||
difficultyLevel: question.difficultyLevel,
|
|
||||||
points: question.points,
|
|
||||||
tips: question.tips,
|
|
||||||
explanation: question.explanation,
|
|
||||||
options: question.options,
|
|
||||||
voicePrompt: question.voicePrompt,
|
|
||||||
sampleAnswerVoicePrompt: question.sampleAnswerVoicePrompt,
|
|
||||||
audioCorrectAnswerText: question.audioCorrectAnswerText,
|
|
||||||
shortAnswer: question.shortAnswers[0] ?? "",
|
|
||||||
imageUrl: question.imageUrl,
|
|
||||||
questionTypeDefinitionId: question.questionTypeDefinitionId,
|
|
||||||
dynamicStimulusRows: question.dynamicStimulusRows,
|
|
||||||
dynamicResponseRows: question.dynamicResponseRows,
|
|
||||||
dynamicFieldValues: question.dynamicFieldValues,
|
|
||||||
}}
|
|
||||||
onChange={(next) =>
|
|
||||||
updateQuestion(question.id, {
|
|
||||||
questionText: next.questionText,
|
|
||||||
questionType: next.questionType as QuestionType,
|
|
||||||
difficultyLevel: next.difficultyLevel as DifficultyLevel,
|
|
||||||
points: next.points,
|
|
||||||
tips: next.tips,
|
|
||||||
explanation: next.explanation,
|
|
||||||
options: next.options,
|
|
||||||
voicePrompt: next.voicePrompt,
|
|
||||||
sampleAnswerVoicePrompt: next.sampleAnswerVoicePrompt,
|
|
||||||
audioCorrectAnswerText: next.audioCorrectAnswerText,
|
|
||||||
shortAnswers: next.shortAnswer.trim() ? [next.shortAnswer.trim()] : [],
|
|
||||||
imageUrl: next.imageUrl,
|
|
||||||
questionTypeDefinitionId: next.questionTypeDefinitionId,
|
|
||||||
dynamicStimulusRows: next.dynamicStimulusRows,
|
|
||||||
dynamicResponseRows: next.dynamicResponseRows,
|
|
||||||
dynamicFieldValues: next.dynamicFieldValues,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
mediaBusy={saving}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
<Button variant="outline" onClick={addQuestion} className="w-full border-dashed">
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
Add another question
|
|
||||||
</Button>
|
|
||||||
<div className="flex items-center justify-between rounded-2xl border border-grayScale-200/80 bg-grayScale-50/30 px-4 py-4 sm:px-6 sm:py-5">
|
|
||||||
<Button variant="outline" onClick={handleBack}>
|
|
||||||
Back
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleNext}>
|
|
||||||
Next: Review
|
|
||||||
<ArrowRight className="ml-2 h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentStep === 3 ? (
|
|
||||||
<Card className="overflow-hidden border-grayScale-200/80 shadow-sm">
|
|
||||||
<div className="border-b border-grayScale-100 bg-gradient-to-r from-grayScale-50/80 to-white px-5 py-5 sm:px-8 sm:py-6">
|
|
||||||
<h2 className="text-lg font-semibold tracking-tight text-grayScale-900 sm:text-xl">Step 3: Review & publish</h2>
|
|
||||||
<p className="mt-1.5 text-sm text-grayScale-500">Confirm lesson details and questions before saving or publishing.</p>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-4 p-5 sm:p-8">
|
|
||||||
<div className="grid gap-4 lg:grid-cols-2">
|
|
||||||
<div className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white">
|
|
||||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-3">
|
|
||||||
<h3 className="text-base font-semibold text-grayScale-900">Basic Information</h3>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="text-sm font-medium text-brand-500 hover:text-brand-600"
|
|
||||||
onClick={() => setCurrentStep(1)}
|
|
||||||
>
|
|
||||||
Edit
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="divide-y divide-grayScale-100">
|
|
||||||
<div className="flex items-center justify-between px-4 py-3 text-sm">
|
|
||||||
<span className="text-grayScale-500">Title</span>
|
|
||||||
<span className="font-medium text-grayScale-800">{lessonTitle || "Untitled Lesson"}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between px-4 py-3 text-sm">
|
|
||||||
<span className="text-grayScale-500">Description</span>
|
|
||||||
<span className="max-w-[55%] truncate text-right font-medium text-grayScale-800">
|
|
||||||
{lessonDescription || <UnassignedLabel />}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between px-4 py-3 text-sm">
|
|
||||||
<span className="text-grayScale-500">Intro video URL</span>
|
|
||||||
<span className="max-w-[55%] truncate text-right font-medium text-grayScale-800">{introVideoUrl || <UnassignedLabel />}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between px-4 py-3 text-sm">
|
|
||||||
<span className="text-grayScale-500">Sub-module</span>
|
|
||||||
<span className="font-medium text-grayScale-800">{subModuleId ?? <UnassignedLabel />}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white">
|
|
||||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-3">
|
|
||||||
<h3 className="text-base font-semibold text-grayScale-900">
|
|
||||||
Questions
|
|
||||||
<span className="ml-2 rounded-full bg-brand-100 px-2 py-0.5 text-xs font-semibold text-brand-700">
|
|
||||||
{reviewQuestions.length}
|
|
||||||
</span>
|
|
||||||
</h3>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="text-sm font-medium text-brand-500 hover:text-brand-600"
|
|
||||||
onClick={() => setCurrentStep(2)}
|
|
||||||
>
|
|
||||||
Edit
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-3 p-3">
|
|
||||||
{reviewQuestions.length === 0 ? (
|
|
||||||
<div className="rounded-xl border border-dashed border-grayScale-200 bg-grayScale-50/50 p-4 text-sm text-grayScale-500">
|
|
||||||
No question content added yet.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
reviewQuestions.map((question, idx) => (
|
|
||||||
<div key={question.id} className="rounded-xl border border-grayScale-200 bg-grayScale-50/35 p-3">
|
|
||||||
<div className="mb-2 flex items-center gap-2">
|
|
||||||
<span className="inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-brand-100 px-1.5 text-[11px] font-semibold text-brand-700">
|
|
||||||
{idx + 1}
|
|
||||||
</span>
|
|
||||||
<span className="rounded-md bg-indigo-50 px-2 py-0.5 text-[11px] font-semibold text-indigo-700">
|
|
||||||
{questionTypeLabel(question.questionType)}
|
|
||||||
</span>
|
|
||||||
<span className="rounded-md bg-grayScale-100 px-2 py-0.5 text-[11px] font-semibold text-grayScale-600">
|
|
||||||
{question.difficultyLevel}
|
|
||||||
</span>
|
|
||||||
<span className="text-[11px] font-semibold text-grayScale-500">{question.points} pt</span>
|
|
||||||
</div>
|
|
||||||
<p className="mb-2 line-clamp-2 text-sm font-medium text-grayScale-800">
|
|
||||||
{question.questionText.trim() || `Question ${idx + 1}`}
|
|
||||||
</p>
|
|
||||||
{question.questionType === "MCQ" ? (
|
|
||||||
<div className="space-y-1">
|
|
||||||
{question.options.map((option, optionIdx) => (
|
|
||||||
<div
|
|
||||||
key={`${question.id}-option-${optionIdx}`}
|
|
||||||
className={`rounded px-2 py-1 text-xs ${
|
|
||||||
option.isCorrect
|
|
||||||
? "bg-green-50 font-medium text-green-700"
|
|
||||||
: "text-grayScale-500"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{option.text || `Option ${optionIdx + 1}`}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between border-t border-grayScale-100 bg-grayScale-50/30 px-5 py-4 sm:px-8 sm:py-5">
|
|
||||||
<Button variant="outline" onClick={handleBack}>
|
|
||||||
Back
|
|
||||||
</Button>
|
|
||||||
<div className="flex gap-3">
|
|
||||||
<Button variant="outline" onClick={() => void saveLesson("DRAFT")} disabled={saving}>
|
|
||||||
{saving ? "Saving..." : "Save as Draft"}
|
|
||||||
</Button>
|
|
||||||
<Button onClick={() => void saveLesson("PUBLISHED")} disabled={saving}>
|
|
||||||
<Rocket className="mr-2 h-4 w-4" />
|
|
||||||
{saving ? "Publishing..." : "Publish Now"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentStep === 4 && resultStatus ? (
|
|
||||||
<div className="mx-auto flex max-w-xl flex-col items-center py-16 text-center">
|
|
||||||
<div className={`mb-5 grid h-24 w-24 place-items-center rounded-full ${resultStatus === "success" ? "bg-gradient-to-br from-brand-200 to-brand-400" : "bg-gradient-to-br from-red-200 to-red-400"}`}>
|
|
||||||
<Check className="h-10 w-10 text-white" />
|
|
||||||
</div>
|
|
||||||
<h2 className="text-4xl font-bold tracking-tight text-grayScale-900">
|
|
||||||
{resultStatus === "success" ? "Lesson Published Successfully!" : "Lesson save failed"}
|
|
||||||
</h2>
|
|
||||||
<p className="mt-3 text-sm text-grayScale-500">{resultStatus === "success" ? "Your lesson is now active." : resultMessage}</p>
|
|
||||||
<div className="mt-8 w-full space-y-3">
|
|
||||||
<Button
|
|
||||||
className="h-11 w-full text-base"
|
|
||||||
onClick={() =>
|
|
||||||
navigate(lastSavedStatus === "PUBLISHED" ? "/content/human-language" : backTo)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
Go back to Course
|
|
||||||
</Button>
|
|
||||||
{resultStatus === "success" ? (
|
|
||||||
<Button variant="outline" className="h-11 w-full text-base" onClick={() => navigate(0)}>
|
|
||||||
Add Another Lesson
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Button variant="outline" className="h-11 w-full text-base" onClick={() => setCurrentStep(3)}>
|
|
||||||
Back to Review
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -1,28 +1,29 @@
|
||||||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { ArrowLeft, ArrowRight, Check, ChevronDown, Grid3X3, GripVertical, Plus, Trash2, Upload } from "lucide-react";
|
||||||
import { useMemo, useRef, useState, type ChangeEvent } from "react";
|
import { useMemo, useRef, useState, type ChangeEvent } from "react";
|
||||||
import { Link, useLocation, useParams, useNavigate } from "react-router-dom";
|
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||||
import { ArrowLeft, ArrowRight, ChevronDown, Grid3X3, Check, Plus, Trash2, GripVertical, Upload } from "lucide-react";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Card } from "../../components/ui/card";
|
|
||||||
import { Button } from "../../components/ui/button";
|
|
||||||
import { Input } from "../../components/ui/input";
|
|
||||||
import { ToggleSwitch } from "../../components/ui/toggle-switch";
|
|
||||||
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields";
|
|
||||||
import { AddNewPracticeReviewStep } from "./components/AddNewPracticeReviewStep";
|
|
||||||
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
|
||||||
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
|
||||||
import {
|
import {
|
||||||
createQuestionSet,
|
|
||||||
createQuestion,
|
|
||||||
addQuestionToSet,
|
addQuestionToSet,
|
||||||
|
createQuestion,
|
||||||
|
createQuestionSet,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { uploadVideoFile } from "../../api/files.api";
|
import { uploadVideoFile } from "../../api/files.api";
|
||||||
|
import { PracticeQuestionEditorFields } from "../../components/content-management/PracticeQuestionEditorFields";
|
||||||
|
import type { PracticeQuestionDynamicRow } from "../../components/content-management/PracticeQuestionEditorFields.shared";
|
||||||
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { Card } from "../../components/ui/card";
|
||||||
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { ToggleSwitch } from "../../components/ui/toggle-switch";
|
||||||
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
|
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
|
||||||
|
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
||||||
import { useVideoUpload } from "../../hooks/useVideoUpload";
|
import { useVideoUpload } from "../../hooks/useVideoUpload";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
|
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
|
||||||
import type { QuestionOption } from "../../types/course.types";
|
import type { QuestionOption } from "../../types/course.types";
|
||||||
import type { PracticeQuestionDynamicRow } from "../../components/content-management/PracticeQuestionEditorFields";
|
import { AddNewPracticeReviewStep } from "./components/AddNewPracticeReviewStep";
|
||||||
|
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||||
|
|
||||||
import { buildDynamicQuestionPayload } from "../../lib/practiceDynamicQuestionPayload";
|
import { buildDynamicQuestionPayload } from "../../lib/practiceDynamicQuestionPayload";
|
||||||
|
|
||||||
type Step = 1 | 2 | 3 | 4 | 5;
|
type Step = 1 | 2 | 3 | 4 | 5;
|
||||||
|
|
|
||||||
|
|
@ -1,43 +1,44 @@
|
||||||
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
|
||||||
import { navigateBack } from "../../lib/navigateBack";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
|
||||||
|
import successIcon from "../../assets/success.svg";
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Stepper } from "../../components/ui/stepper";
|
import { Stepper } from "../../components/ui/stepper";
|
||||||
import successIcon from "../../assets/success.svg";
|
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors";
|
||||||
import type { PracticeParentKind } from "../../types/course.types";
|
|
||||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
|
||||||
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
|
|
||||||
import { emptyDynamicFieldValuesForDefinition } from "../../lib/learnEnglishDefinitionQuestion";
|
import { emptyDynamicFieldValuesForDefinition } from "../../lib/learnEnglishDefinitionQuestion";
|
||||||
import {
|
import {
|
||||||
validateLearnEnglishQuestionsWithDefinitions,
|
validateLearnEnglishQuestionsWithDefinitions,
|
||||||
} from "../../lib/learnEnglishPracticePublish";
|
} from "../../lib/learnEnglishPracticePublish";
|
||||||
|
import { navigateBack } from "../../lib/navigateBack";
|
||||||
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
|
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
|
||||||
import { syncStimulusBlocksAfterCreate } from "../../lib/practiceEditOrchestrator";
|
import { syncStimulusBlocksAfterCreate } from "../../lib/practiceEditOrchestrator";
|
||||||
import {
|
import type { PracticeFormState } from "../../lib/practiceFullMapper";
|
||||||
isIeltsSharedStimulusMode,
|
|
||||||
validatePracticeStimulusBlocks,
|
|
||||||
} from "../../lib/practiceStimulusBlocks";
|
|
||||||
import {
|
import {
|
||||||
buildCreatePracticeParentsPayload,
|
buildCreatePracticeParentsPayload,
|
||||||
dedupeParents,
|
dedupeParents,
|
||||||
formatPracticeParentsSummary,
|
formatPracticeParentsSummary,
|
||||||
validatePracticeParents,
|
validatePracticeParents,
|
||||||
} from "../../lib/practiceParents";
|
} from "../../lib/practiceParents";
|
||||||
|
import {
|
||||||
|
isIeltsSharedStimulusMode,
|
||||||
|
validatePracticeStimulusBlocks,
|
||||||
|
} from "../../lib/practiceStimulusBlocks";
|
||||||
import { hasRichTextContent } from "../../lib/richText";
|
import { hasRichTextContent } from "../../lib/richText";
|
||||||
|
import type { PracticeParentKind } from "../../types/course.types";
|
||||||
|
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
||||||
|
|
||||||
|
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
||||||
import { ContextStep } from "./components/practice-steps/ContextStep";
|
import { ContextStep } from "./components/practice-steps/ContextStep";
|
||||||
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
|
||||||
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||||
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
||||||
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
||||||
|
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||||
import {
|
import {
|
||||||
personaFromId,
|
personaFromId,
|
||||||
personaIdNumber,
|
personaIdNumber,
|
||||||
} from "./components/practice-steps/constants";
|
} from "./components/practice-steps/constants";
|
||||||
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
|
||||||
|
|
||||||
const STEP_LABELS = ["Practice", "Persona", "Questions", "Review"] as const;
|
const STEP_LABELS = ["Practice", "Persona", "Questions", "Review"] as const;
|
||||||
|
|
||||||
|
|
@ -137,6 +138,7 @@ export function AddPracticeFlow() {
|
||||||
}, [
|
}, [
|
||||||
lessonId,
|
lessonId,
|
||||||
lessonTitleDisplay,
|
lessonTitleDisplay,
|
||||||
|
isExamPrep,
|
||||||
isModuleContext,
|
isModuleContext,
|
||||||
isUnitContext,
|
isUnitContext,
|
||||||
isCourseContext,
|
isCourseContext,
|
||||||
|
|
@ -148,7 +150,7 @@ export function AddPracticeFlow() {
|
||||||
const programLabel = isExamPrep
|
const programLabel = isExamPrep
|
||||||
? programType === "skill"
|
? programType === "skill"
|
||||||
? "Skill-Based Courses"
|
? "Skill-Based Courses"
|
||||||
: "Duolingo/IELTS"
|
: "Makeup artistry"
|
||||||
: level
|
: level
|
||||||
? `Program ${level}`
|
? `Program ${level}`
|
||||||
: null;
|
: null;
|
||||||
|
|
@ -252,7 +254,7 @@ export function AddPracticeFlow() {
|
||||||
reload: reloadPersonas,
|
reload: reloadPersonas,
|
||||||
} = useActivePersonas();
|
} = useActivePersonas();
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState<PracticeFormState>({
|
||||||
title: "",
|
title: "",
|
||||||
description: "",
|
description: "",
|
||||||
storyImageUrl: "",
|
storyImageUrl: "",
|
||||||
|
|
@ -629,7 +631,7 @@ export function AddPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<ContextStep
|
<ContextStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
onCancel={goBack}
|
onCancel={goBack}
|
||||||
lessonTitle={lessonTitleDisplay}
|
lessonTitle={lessonTitleDisplay}
|
||||||
|
|
@ -653,7 +655,7 @@ export function AddPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<QuestionsStep
|
<QuestionsStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
prevStep={prevStep}
|
prevStep={prevStep}
|
||||||
typeDefinitions={typeDefinitions}
|
typeDefinitions={typeDefinitions}
|
||||||
|
|
@ -697,7 +699,7 @@ export function AddPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<ScenarioStep
|
<ScenarioStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
cancelHref={backPath}
|
cancelHref={backPath}
|
||||||
/>
|
/>
|
||||||
|
|
@ -719,7 +721,7 @@ export function AddPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<QuestionsStep
|
<QuestionsStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
prevStep={prevStep}
|
prevStep={prevStep}
|
||||||
typeDefinitions={typeDefinitions}
|
typeDefinitions={typeDefinitions}
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,20 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { ArrowLeft, Plus, X } from "lucide-react"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useNavigate, useParams } from "react-router-dom"
|
import { useNavigate, useParams } from "react-router-dom"
|
||||||
import { ArrowLeft, Plus, X } from "lucide-react"
|
|
||||||
import { navigateBack } from "../../lib/navigateBack"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
|
||||||
import { Input } from "../../components/ui/input"
|
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
|
||||||
import { Select } from "../../components/ui/select"
|
|
||||||
import { createQuestion, getQuestionById, updateQuestion } from "../../api/courses.api"
|
import { createQuestion, getQuestionById, updateQuestion } from "../../api/courses.api"
|
||||||
import {
|
import {
|
||||||
getQuestionTypeDefinitions,
|
getQuestionTypeDefinitions,
|
||||||
questionTypeDefinitionListLabel,
|
questionTypeDefinitionListLabel,
|
||||||
} from "../../api/questionTypeDefinitions.api"
|
} from "../../api/questionTypeDefinitions.api"
|
||||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { navigateBack } from "../../lib/navigateBack"
|
||||||
|
import type { DynamicQuestionPayload, QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||||
|
|
||||||
type QuestionType = "MCQ" | "TRUE_FALSE" | "SHORT_ANSWER" | "AUDIO" | "DYNAMIC"
|
type QuestionType = "MCQ" | "TRUE_FALSE" | "SHORT_ANSWER" | "AUDIO" | "DYNAMIC"
|
||||||
type Difficulty = "EASY" | "MEDIUM" | "HARD"
|
type Difficulty = "EASY" | "MEDIUM" | "HARD"
|
||||||
|
|
@ -294,13 +294,10 @@ export function AddQuestionPage() {
|
||||||
{ acceptable_answer: formData.correctAnswer.trim(), match_type: "CASE_INSENSITIVE" as const },
|
{ acceptable_answer: formData.correctAnswer.trim(), match_type: "CASE_INSENSITIVE" as const },
|
||||||
]
|
]
|
||||||
: undefined
|
: undefined
|
||||||
let dynamicPayload: { stimulus: unknown[]; response: unknown[] } | undefined
|
let dynamicPayload: DynamicQuestionPayload | undefined
|
||||||
if (formData.type === "DYNAMIC") {
|
if (formData.type === "DYNAMIC") {
|
||||||
try {
|
try {
|
||||||
dynamicPayload = JSON.parse(formData.dynamicPayloadJson) as {
|
dynamicPayload = JSON.parse(formData.dynamicPayloadJson) as DynamicQuestionPayload
|
||||||
stimulus: unknown[]
|
|
||||||
response: unknown[]
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
dynamicPayload = { stimulus: [], response: [] }
|
dynamicPayload = { stimulus: [], response: [] }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,24 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { BookOpen, ChevronDown, ChevronLeft, ChevronRight, Edit2, Plus, RefreshCw, Search, ToggleLeft, ToggleRight } from "lucide-react"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom"
|
||||||
import { Search, Plus, RefreshCw, Edit2, ToggleLeft, ToggleRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
import { toast } from "sonner"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { createCourse, getCourseCategories, getCoursesByCategory, updateCourse, updateCourseStatus, updateCourseThumbnail } from "../../api/courses.api"
|
||||||
|
import { uploadImageFile } from "../../api/files.api"
|
||||||
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
|
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../../components/ui/dialog"
|
||||||
|
import { FileUpload } from "../../components/ui/file-upload"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import { Select } from "../../components/ui/select"
|
import { Select } from "../../components/ui/select"
|
||||||
import {
|
import {
|
||||||
|
|
@ -15,26 +29,13 @@ import {
|
||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "../../components/ui/table"
|
} from "../../components/ui/table"
|
||||||
import { Badge } from "../../components/ui/badge"
|
|
||||||
import { FileUpload } from "../../components/ui/file-upload"
|
|
||||||
import { getCourseCategories, getCoursesByCategory, createCourse, updateCourseStatus, updateCourse, updateCourseThumbnail } from "../../api/courses.api"
|
|
||||||
import { uploadImageFile } from "../../api/files.api"
|
|
||||||
import type { Course, CourseCategory } from "../../types/course.types"
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "../../components/ui/dialog"
|
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
import { toast } from "sonner"
|
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { readCreatedEntityId } from "../../lib/apiResponse"
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
import { cn } from "../../lib/utils"
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
import type { Course, CourseCategory } from "../../types/course.types"
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
|
||||||
|
|
||||||
type CourseWithCategory = Course & { category_name: string }
|
type CourseWithCategory = Course & { category_name: string }
|
||||||
|
|
||||||
|
|
@ -54,7 +55,7 @@ export function AllCoursesPage() {
|
||||||
const [createTitle, setCreateTitle] = useState("")
|
const [createTitle, setCreateTitle] = useState("")
|
||||||
const [createDescription, setCreateDescription] = useState("")
|
const [createDescription, setCreateDescription] = useState("")
|
||||||
const [createThumbnail, setCreateThumbnail] = useState<File | null>(null)
|
const [createThumbnail, setCreateThumbnail] = useState<File | null>(null)
|
||||||
const [createVideo, setCreateVideo] = useState<File | null>(null)
|
const [, setCreateVideo] = useState<File | null>(null)
|
||||||
const [creating, setCreating] = useState(false)
|
const [creating, setCreating] = useState(false)
|
||||||
const [togglingId, setTogglingId] = useState<number | null>(null)
|
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||||
const [editOpen, setEditOpen] = useState(false)
|
const [editOpen, setEditOpen] = useState(false)
|
||||||
|
|
@ -147,14 +148,9 @@ export function AllCoursesPage() {
|
||||||
description: createDescription.trim(),
|
description: createDescription.trim(),
|
||||||
})
|
})
|
||||||
|
|
||||||
const createdIdRaw =
|
const createdId = readCreatedEntityId(createdRes.data, "course")
|
||||||
(createdRes.data?.data as any)?.id ??
|
|
||||||
(createdRes.data?.data as any)?.course?.id ??
|
|
||||||
(createdRes.data?.data as any)?.data?.id
|
|
||||||
|
|
||||||
const createdId = Number(createdIdRaw)
|
if (createThumbnail && createdId != null) {
|
||||||
|
|
||||||
if (createThumbnail && Number.isFinite(createdId)) {
|
|
||||||
const uploadRes = await uploadImageFile(createThumbnail)
|
const uploadRes = await uploadImageFile(createThumbnail)
|
||||||
const thumbnailUrl = uploadRes.data?.data?.url?.trim()
|
const thumbnailUrl = uploadRes.data?.data?.url?.trim()
|
||||||
if (thumbnailUrl) {
|
if (thumbnailUrl) {
|
||||||
|
|
@ -174,7 +170,7 @@ export function AllCoursesPage() {
|
||||||
setCreateThumbnail(null)
|
setCreateThumbnail(null)
|
||||||
setCreateVideo(null)
|
setCreateVideo(null)
|
||||||
await fetchAllCourses()
|
await fetchAllCourses()
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
console.error("Failed to create course:", err)
|
console.error("Failed to create course:", err)
|
||||||
notifyApiError(err, "Failed to create sub-category")
|
notifyApiError(err, "Failed to create sub-category")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -221,7 +217,7 @@ export function AllCoursesPage() {
|
||||||
setEditOpen(false)
|
setEditOpen(false)
|
||||||
setCourseToEdit(null)
|
setCourseToEdit(null)
|
||||||
await fetchAllCourses()
|
await fetchAllCourses()
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
console.error("Failed to update course:", err)
|
console.error("Failed to update course:", err)
|
||||||
notifyApiError(err, "Failed to update sub-category")
|
notifyApiError(err, "Failed to update sub-category")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -560,7 +556,7 @@ export function AllCoursesPage() {
|
||||||
Sub-category title
|
Sub-category title
|
||||||
</label>
|
</label>
|
||||||
<Input
|
<Input
|
||||||
placeholder="e.g. Beginner English A1"
|
placeholder="e.g. Makeup Artistry Foundations"
|
||||||
value={createTitle}
|
value={createTitle}
|
||||||
onChange={(e) => setCreateTitle(e.target.value)}
|
onChange={(e) => setCreateTitle(e.target.value)}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
|
import { ArrowLeft, Check, Clock } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { ArrowLeft, Clock, FileVideo, Check } from "lucide-react";
|
import successIcon from "../../assets/success.svg";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Stepper } from "../../components/ui/stepper";
|
import { Stepper } from "../../components/ui/stepper";
|
||||||
import successIcon from "../../assets/success.svg";
|
|
||||||
|
|
||||||
import { AttachPracticeStep1 } from "./components/practice-steps/AttachPracticeStep1";
|
|
||||||
import { AttachPracticeReviewStep } from "./components/practice-steps/AttachPracticeReviewStep";
|
import { AttachPracticeReviewStep } from "./components/practice-steps/AttachPracticeReviewStep";
|
||||||
|
import { AttachPracticeStep1 } from "./components/practice-steps/AttachPracticeStep1";
|
||||||
|
|
||||||
export function AttachPracticeFlow() {
|
export function AttachPracticeFlow() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
@ -25,9 +25,9 @@ export function AttachPracticeFlow() {
|
||||||
program:
|
program:
|
||||||
programType === "skill"
|
programType === "skill"
|
||||||
? "Skill-Based Courses"
|
? "Skill-Based Courses"
|
||||||
: "Duolingo/IELTS",
|
: "Makeup artistry",
|
||||||
module: "Module 4: Interactive Speaking",
|
module: "Module 4: Consultation practice",
|
||||||
video: "Intro to Interactive Speaking",
|
video: "Introduction to bridal consultation",
|
||||||
questionType: "speaking",
|
questionType: "speaking",
|
||||||
version: "v1",
|
version: "v1",
|
||||||
});
|
});
|
||||||
|
|
@ -71,7 +71,7 @@ export function AttachPracticeFlow() {
|
||||||
</div>
|
</div>
|
||||||
<div className="text-left space-y-1.5">
|
<div className="text-left space-y-1.5">
|
||||||
<h4 className="text-[14px] font-medium text-grayScale-900">
|
<h4 className="text-[14px] font-medium text-grayScale-900">
|
||||||
Intro to IELTS Speaking Part 1
|
Introduction to bridal consultation
|
||||||
</h4>
|
</h4>
|
||||||
<div className="flex items-center gap-3 text-grayScale-400 font-medium text-[12px]">
|
<div className="flex items-center gap-3 text-grayScale-400 font-medium text-[12px]">
|
||||||
<div className="flex items-center gap-1.5 uppercase tracking-wide">
|
<div className="flex items-center gap-1.5 uppercase tracking-wide">
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
|
import { ArrowLeft } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { ArrowLeft, Check } from "lucide-react";
|
import successIcon from "../../assets/success.svg";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { Stepper } from "../../components/ui/stepper";
|
import { Stepper } from "../../components/ui/stepper";
|
||||||
import successIcon from "../../assets/success.svg";
|
|
||||||
|
|
||||||
import { ProgramAttachStep1 } from "./components/practice-steps/ProgramAttachStep1";
|
|
||||||
import { ProgramAttachReviewStep } from "./components/practice-steps/ProgramAttachReviewStep";
|
import { ProgramAttachReviewStep } from "./components/practice-steps/ProgramAttachReviewStep";
|
||||||
|
import { ProgramAttachStep1 } from "./components/practice-steps/ProgramAttachStep1";
|
||||||
|
|
||||||
export function AttachProgramPracticeFlow() {
|
export function AttachProgramPracticeFlow() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
@ -17,7 +17,7 @@ export function AttachProgramPracticeFlow() {
|
||||||
const [isPublished, setIsPublished] = useState(false);
|
const [isPublished, setIsPublished] = useState(false);
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
program: "Duolingo/IELTS",
|
program: "Makeup artistry",
|
||||||
test: "Mock Exam 1",
|
test: "Mock Exam 1",
|
||||||
questionType: "Speaking Practice",
|
questionType: "Speaking Practice",
|
||||||
version: "V 1.0",
|
version: "V 1.0",
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,12 @@
|
||||||
import { useEffect, useState } from "react"
|
import { ArrowLeft, ArrowRight, BookOpen, Briefcase, ChevronRight, HelpCircle, Mic, Search } from "lucide-react"
|
||||||
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import { Link, useParams } from "react-router-dom"
|
import { Link, useParams } from "react-router-dom"
|
||||||
import { BookOpen, Mic, Briefcase, HelpCircle, ArrowLeft, ArrowRight, ChevronRight, Search } from "lucide-react"
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../../components/ui/card"
|
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { Input } from "../../components/ui/input"
|
|
||||||
import { getCourseCategories } from "../../api/courses.api"
|
import { getCourseCategories } from "../../api/courses.api"
|
||||||
import type { CourseCategory } from "../../types/course.types"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { CourseCategory } from "../../types/course.types"
|
||||||
|
|
||||||
const contentSections = [
|
const contentSections = [
|
||||||
{
|
{
|
||||||
|
|
@ -65,17 +64,49 @@ type ContentSection = (typeof contentSections)[number]
|
||||||
export function ContentOverviewPage() {
|
export function ContentOverviewPage() {
|
||||||
const { categoryId } = useParams<{ categoryId: string }>()
|
const { categoryId } = useParams<{ categoryId: string }>()
|
||||||
const [category, setCategory] = useState<CourseCategory | null>(null)
|
const [category, setCategory] = useState<CourseCategory | null>(null)
|
||||||
const [sections, setSections] = useState<ContentSection[]>(() => [...contentSections])
|
const [sections, setSections] = useState<ContentSection[]>(() => {
|
||||||
|
try {
|
||||||
|
const raw = window.localStorage.getItem("content_sections_order")
|
||||||
|
if (!raw) return [...contentSections]
|
||||||
|
const savedKeys: string[] = JSON.parse(raw)
|
||||||
|
const byKey = new Map(contentSections.map((s) => [s.key, s]))
|
||||||
|
const reordered: ContentSection[] = []
|
||||||
|
savedKeys.forEach((k) => {
|
||||||
|
const item = byKey.get(k as ContentSection["key"])
|
||||||
|
if (item) {
|
||||||
|
reordered.push(item)
|
||||||
|
byKey.delete(k as ContentSection["key"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Append any new sections that weren't in saved order
|
||||||
|
byKey.forEach((item) => reordered.push(item))
|
||||||
|
if (reordered.length) {
|
||||||
|
return reordered
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore corrupted localStorage
|
||||||
|
}
|
||||||
|
return [...contentSections]
|
||||||
|
})
|
||||||
const [searchQuery, setSearchQuery] = useState("")
|
const [searchQuery, setSearchQuery] = useState("")
|
||||||
const [dragKey, setDragKey] = useState<string | null>(null)
|
const [dragKey, setDragKey] = useState<string | null>(null)
|
||||||
const [flowSteps, setFlowSteps] = useState<
|
const flowSteps = useMemo<
|
||||||
{
|
{
|
||||||
id: string
|
id: string
|
||||||
type: "lesson" | "practice" | "exam" | "feedback" | "course" | "speaking" | "new_course"
|
type: "lesson" | "practice" | "exam" | "feedback" | "course" | "speaking" | "new_course"
|
||||||
title: string
|
title: string
|
||||||
description?: string
|
description?: string
|
||||||
}[]
|
}[]
|
||||||
>([])
|
>(() => {
|
||||||
|
if (!categoryId) return []
|
||||||
|
try {
|
||||||
|
const raw = window.localStorage.getItem(`category_flow_${categoryId}`)
|
||||||
|
const parsed: unknown = raw ? JSON.parse(raw) : null
|
||||||
|
return Array.isArray(parsed) ? parsed : []
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}, [categoryId])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchCategory = async () => {
|
const fetchCategory = async () => {
|
||||||
|
|
@ -93,55 +124,6 @@ export function ContentOverviewPage() {
|
||||||
}
|
}
|
||||||
}, [categoryId])
|
}, [categoryId])
|
||||||
|
|
||||||
// Load category-level flow sequence (if any) from localStorage
|
|
||||||
useEffect(() => {
|
|
||||||
if (!categoryId) {
|
|
||||||
setFlowSteps([])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const key = `category_flow_${categoryId}`
|
|
||||||
try {
|
|
||||||
const raw = window.localStorage.getItem(key)
|
|
||||||
if (raw) {
|
|
||||||
const parsed = JSON.parse(raw)
|
|
||||||
if (Array.isArray(parsed)) {
|
|
||||||
setFlowSteps(parsed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore and fall back to default
|
|
||||||
}
|
|
||||||
|
|
||||||
// No explicit flow saved; fall back to an empty sequence
|
|
||||||
setFlowSteps([])
|
|
||||||
}, [categoryId])
|
|
||||||
|
|
||||||
// Load persisted section order from localStorage
|
|
||||||
useEffect(() => {
|
|
||||||
try {
|
|
||||||
const raw = window.localStorage.getItem("content_sections_order")
|
|
||||||
if (!raw) return
|
|
||||||
const savedKeys: string[] = JSON.parse(raw)
|
|
||||||
const byKey = new Map(contentSections.map((s) => [s.key, s]))
|
|
||||||
const reordered: ContentSection[] = []
|
|
||||||
savedKeys.forEach((k) => {
|
|
||||||
const item = byKey.get(k as ContentSection["key"])
|
|
||||||
if (item) {
|
|
||||||
reordered.push(item)
|
|
||||||
byKey.delete(k as ContentSection["key"])
|
|
||||||
}
|
|
||||||
})
|
|
||||||
// Append any new sections that weren't in saved order
|
|
||||||
byKey.forEach((item) => reordered.push(item))
|
|
||||||
if (reordered.length) {
|
|
||||||
setSections(reordered)
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore corrupted localStorage
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
// Persist order whenever it changes
|
// Persist order whenever it changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const keys = sections.map((s) => s.key)
|
const keys = sections.map((s) => s.key)
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { BookOpen, FolderOpen, Plus, RefreshCw, Trash2 } from "lucide-react"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { Link } from "react-router-dom"
|
import { Link } from "react-router-dom"
|
||||||
import { FolderOpen, RefreshCw, BookOpen, Plus, Trash2 } from "lucide-react"
|
import { toast } from "sonner"
|
||||||
|
import { createCourseCategory, deleteCourseCategory, getCourseCategories } from "../../api/courses.api"
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
import alertSrc from "../../assets/Alert.svg"
|
import alertSrc from "../../assets/Alert.svg"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import { Select } from "../../components/ui/select"
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
|
|
@ -16,10 +16,11 @@ import {
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog"
|
} from "../../components/ui/dialog"
|
||||||
import { getCourseCategories, createCourseCategory, deleteCourseCategory } from "../../api/courses.api"
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { readCreatedEntityId } from "../../lib/apiResponse"
|
||||||
import type { CourseCategory } from "../../types/course.types"
|
import type { CourseCategory } from "../../types/course.types"
|
||||||
import { toast } from "sonner"
|
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
|
||||||
|
|
||||||
export function CourseCategoryPage() {
|
export function CourseCategoryPage() {
|
||||||
const [categories, setCategories] = useState<CourseCategory[]>([])
|
const [categories, setCategories] = useState<CourseCategory[]>([])
|
||||||
|
|
@ -216,7 +217,7 @@ export function CourseCategoryPage() {
|
||||||
Category name
|
Category name
|
||||||
</label>
|
</label>
|
||||||
<Input
|
<Input
|
||||||
placeholder="e.g. Beginner English, Duolingo/IELTS"
|
placeholder="e.g. Makeup Foundations, Bridal Artistry"
|
||||||
value={newCategoryName}
|
value={newCategoryName}
|
||||||
onChange={(e) => setNewCategoryName(e.target.value)}
|
onChange={(e) => setNewCategoryName(e.target.value)}
|
||||||
/>
|
/>
|
||||||
|
|
@ -337,19 +338,7 @@ export function CourseCategoryPage() {
|
||||||
try {
|
try {
|
||||||
const name = newCategoryName.trim()
|
const name = newCategoryName.trim()
|
||||||
const parentRes = await createCourseCategory({ name })
|
const parentRes = await createCourseCategory({ name })
|
||||||
let createdCategoryId: number | null = null
|
const createdCategoryId = readCreatedEntityId(parentRes.data, "category")
|
||||||
try {
|
|
||||||
const data: any = parentRes?.data
|
|
||||||
createdCategoryId =
|
|
||||||
data?.data?.id ??
|
|
||||||
data?.data?.category?.id ??
|
|
||||||
data?.data?.id ??
|
|
||||||
data?.category?.id ??
|
|
||||||
data?.id ??
|
|
||||||
null
|
|
||||||
} catch {
|
|
||||||
createdCategoryId = null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (createdCategoryId && pendingSubCategories.length > 0) {
|
if (createdCategoryId && pendingSubCategories.length > 0) {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,32 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Plus,
|
|
||||||
Calendar,
|
Calendar,
|
||||||
Layers,
|
Layers,
|
||||||
Pencil,
|
Pencil,
|
||||||
|
Plus,
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
deleteParentLinkedPractice,
|
||||||
|
deleteTopLevelCourseModule,
|
||||||
|
getModuleLessons,
|
||||||
|
getPracticesByParentCourse,
|
||||||
|
getProgramCourses,
|
||||||
|
getTopLevelCourseModules,
|
||||||
|
setLearnEnglishPracticePublishStatus,
|
||||||
|
setTopLevelCourseModuleAccessTier,
|
||||||
|
setTopLevelCourseModulePublishStatus,
|
||||||
|
updateTopLevelCourseModule,
|
||||||
|
} from "../../api/courses.api";
|
||||||
|
import { refreshFileUrl, resolveFileUrl } from "../../api/files.api";
|
||||||
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
||||||
|
import alertSrc from "../../assets/Alert.svg";
|
||||||
|
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
|
||||||
import { Card } from "../../components/ui/card";
|
import { Card } from "../../components/ui/card";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
|
|
@ -24,58 +38,44 @@ import {
|
||||||
} 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 { Textarea } from "../../components/ui/textarea";
|
||||||
import { cn } from "../../lib/utils";
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
|
||||||
import alertSrc from "../../assets/Alert.svg";
|
|
||||||
import {
|
|
||||||
deleteTopLevelCourseModule,
|
|
||||||
deleteParentLinkedPractice,
|
|
||||||
getModuleLessons,
|
|
||||||
getPracticesByParentCourse,
|
|
||||||
getProgramCourses,
|
|
||||||
getTopLevelCourseModules,
|
|
||||||
setLearnEnglishPracticePublishStatus,
|
|
||||||
setTopLevelCourseModuleAccessTier,
|
|
||||||
setTopLevelCourseModulePublishStatus,
|
|
||||||
updateTopLevelCourseModule,
|
|
||||||
} from "../../api/courses.api";
|
|
||||||
import { refreshFileUrl, resolveFileUrl } from "../../api/files.api";
|
|
||||||
import type {
|
|
||||||
ParentContextPractice,
|
|
||||||
ContentAccessTier,
|
|
||||||
PracticeParent,
|
|
||||||
PracticePublishStatus,
|
|
||||||
ProgramCourseListItem,
|
|
||||||
TopLevelCourseModuleItem,
|
|
||||||
TopLevelModuleLessonItem,
|
|
||||||
} from "../../types/course.types";
|
|
||||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
|
||||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
|
||||||
import {
|
import {
|
||||||
filterBySearchAndPublishStatus,
|
filterBySearchAndPublishStatus,
|
||||||
type PublishStatusFilter,
|
type PublishStatusFilter,
|
||||||
} from "../../lib/contentListFilters";
|
} from "../../lib/contentListFilters";
|
||||||
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
import { DisplayValue } from "../../lib/displayValue";
|
||||||
import {
|
import {
|
||||||
fetchAllOffsetPages,
|
fetchAllOffsetPages,
|
||||||
offsetPageFromListEnvelope,
|
offsetPageFromListEnvelope,
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
import { AddModuleModal } from "./components/AddModuleModal";
|
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||||
import { ModuleIconUploadField } from "./components/ModuleIconUploadField";
|
|
||||||
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
|
||||||
import { PublishPracticeButton } from "./components/PublishPracticeButton";
|
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
|
||||||
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents"
|
|
||||||
import {
|
import {
|
||||||
hasCourseDirectPracticeLink,
|
hasCourseDirectPracticeLink,
|
||||||
isPracticeParentUnlinkNotLinkedError,
|
isPracticeParentUnlinkNotLinkedError,
|
||||||
listCourseContextUnlinkParents,
|
listCourseContextUnlinkParents,
|
||||||
practiceUnlinkBlockedMessage,
|
practiceUnlinkBlockedMessage,
|
||||||
unlinkPracticeFromParent,
|
unlinkPracticeFromParent,
|
||||||
} from "../../lib/practiceParentUnlink"
|
} from "../../lib/practiceParentUnlink";
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
import type {
|
||||||
|
ContentAccessTier,
|
||||||
|
ParentContextPractice,
|
||||||
|
PracticeParent,
|
||||||
|
PracticePublishStatus,
|
||||||
|
ProgramCourseListItem,
|
||||||
|
TopLevelCourseModuleItem,
|
||||||
|
TopLevelModuleLessonItem,
|
||||||
|
} from "../../types/course.types";
|
||||||
|
import { AddModuleModal } from "./components/AddModuleModal";
|
||||||
|
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||||
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
|
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||||
|
import { ModuleIconUploadField } from "./components/ModuleIconUploadField";
|
||||||
|
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||||
|
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
||||||
|
import { PublishPracticeButton } from "./components/PublishPracticeButton";
|
||||||
|
|
||||||
const MODULE_CARD_GRADIENT = "from-[#27272A] to-[#52525B]" as const;
|
const MODULE_CARD_GRADIENT = "from-[#27272A] to-[#52525B]" as const;
|
||||||
|
|
||||||
|
|
@ -317,7 +317,7 @@ export function CourseDetailPage() {
|
||||||
} else {
|
} else {
|
||||||
console.error(modulesOutcome.reason);
|
console.error(modulesOutcome.reason);
|
||||||
setModules([]);
|
setModules([]);
|
||||||
notifyApiError(err, "Could not load modules");
|
notifyApiError(modulesOutcome.reason, "Could not load modules");
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,3 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useEffect, useMemo, useState } from "react"
|
|
||||||
import {
|
|
||||||
ChevronDown,
|
|
||||||
ChevronRight,
|
|
||||||
GripVertical,
|
|
||||||
RefreshCw,
|
|
||||||
Sparkles,
|
|
||||||
} from "lucide-react"
|
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
KeyboardSensor,
|
KeyboardSensor,
|
||||||
|
|
@ -25,23 +16,34 @@ import {
|
||||||
verticalListSortingStrategy,
|
verticalListSortingStrategy,
|
||||||
} from "@dnd-kit/sortable"
|
} from "@dnd-kit/sortable"
|
||||||
import { CSS } from "@dnd-kit/utilities"
|
import { CSS } from "@dnd-kit/utilities"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import {
|
||||||
import { Button } from "../../components/ui/button"
|
ChevronDown,
|
||||||
import { Select } from "../../components/ui/select"
|
ChevronRight,
|
||||||
import { Badge } from "../../components/ui/badge"
|
GripVertical,
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
RefreshCw,
|
||||||
|
Sparkles,
|
||||||
|
} from "lucide-react"
|
||||||
|
import { useEffect, useMemo, useState } from "react"
|
||||||
import {
|
import {
|
||||||
getCourseCategories,
|
getCourseCategories,
|
||||||
getCoursesByCategory,
|
getCoursesByCategory,
|
||||||
|
getQuestionSetsByOwner,
|
||||||
getSubModulesByCourse,
|
getSubModulesByCourse,
|
||||||
getVideosBySubModule,
|
getVideosBySubModule,
|
||||||
getQuestionSetsByOwner,
|
|
||||||
reorderCategories,
|
reorderCategories,
|
||||||
reorderCourses,
|
reorderCourses,
|
||||||
|
reorderPractices,
|
||||||
reorderSubModules,
|
reorderSubModules,
|
||||||
reorderVideos,
|
reorderVideos,
|
||||||
reorderPractices,
|
|
||||||
} from "../../api/courses.api"
|
} from "../../api/courses.api"
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
import type {
|
import type {
|
||||||
Course,
|
Course,
|
||||||
CourseCategory,
|
CourseCategory,
|
||||||
|
|
@ -51,9 +53,6 @@ import type {
|
||||||
QuestionSet,
|
QuestionSet,
|
||||||
ReorderItem,
|
ReorderItem,
|
||||||
} from "../../types/course.types"
|
} from "../../types/course.types"
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
|
||||||
|
|
||||||
type PracticeListItem = LearningPathPractice & { display_order: number }
|
type PracticeListItem = LearningPathPractice & { display_order: number }
|
||||||
|
|
||||||
|
|
@ -67,7 +66,7 @@ function mapPracticeSetsToPracticeItems(sets: QuestionSet[]): PracticeListItem[]
|
||||||
status: set.status,
|
status: set.status,
|
||||||
question_count: 0,
|
question_count: 0,
|
||||||
display_order:
|
display_order:
|
||||||
typeof (set as any).display_order === "number" ? (set as any).display_order : idx,
|
readDisplayOrder(set) ?? idx,
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
@ -79,10 +78,16 @@ function normalizeParentId(value: number | string | null | undefined): number |
|
||||||
return parsed <= 0 ? null : parsed
|
return parsed <= 0 ? null : parsed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readDisplayOrder(item: object): number | undefined {
|
||||||
|
return "display_order" in item && typeof item.display_order === "number"
|
||||||
|
? item.display_order
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
function sortByDisplayOrder<T extends { id: number }>(items: T[]) {
|
function sortByDisplayOrder<T extends { id: number }>(items: T[]) {
|
||||||
return [...items].sort((a, b) => {
|
return [...items].sort((a, b) => {
|
||||||
const ao = typeof (a as any).display_order === "number" ? (a as any).display_order : 0
|
const ao = readDisplayOrder(a) ?? 0
|
||||||
const bo = typeof (b as any).display_order === "number" ? (b as any).display_order : 0
|
const bo = readDisplayOrder(b) ?? 0
|
||||||
if (ao === bo) return a.id - b.id
|
if (ao === bo) return a.id - b.id
|
||||||
return ao - bo
|
return ao - bo
|
||||||
})
|
})
|
||||||
|
|
@ -211,7 +216,7 @@ export function CourseFlowBuilderPage() {
|
||||||
)
|
)
|
||||||
|
|
||||||
const topLevelCategories = useMemo(
|
const topLevelCategories = useMemo(
|
||||||
() => sortByDisplayOrder(categories.filter((c) => normalizeParentId(c.parent_id as any) === null)),
|
() => sortByDisplayOrder(categories.filter((c) => normalizeParentId(c.parent_id) === null)),
|
||||||
[categories],
|
[categories],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -227,7 +232,7 @@ export function CourseFlowBuilderPage() {
|
||||||
const res = await getCourseCategories()
|
const res = await getCourseCategories()
|
||||||
const all = sortByDisplayOrder(res.data.data.categories ?? [])
|
const all = sortByDisplayOrder(res.data.data.categories ?? [])
|
||||||
setCategories(all)
|
setCategories(all)
|
||||||
} catch {
|
} catch (err) {
|
||||||
notifyApiError(err, "Failed to load course categories.")
|
notifyApiError(err, "Failed to load course categories.")
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
@ -264,7 +269,7 @@ export function CourseFlowBuilderPage() {
|
||||||
)
|
)
|
||||||
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: items }))
|
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: items }))
|
||||||
setSelectedCourseId(items[0]?.id ?? null)
|
setSelectedCourseId(items[0]?.id ?? null)
|
||||||
} catch {
|
} catch (err) {
|
||||||
notifyApiError(err, "Failed to load course sub-categories.")
|
notifyApiError(err, "Failed to load course sub-categories.")
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingCourses(false)
|
setLoadingCourses(false)
|
||||||
|
|
@ -283,7 +288,7 @@ export function CourseFlowBuilderPage() {
|
||||||
try {
|
try {
|
||||||
const selectedCourse = activeCourses.find((course) => course.id === selectedCourseId)
|
const selectedCourse = activeCourses.find((course) => course.id === selectedCourseId)
|
||||||
const subRes = await getSubModulesByCourse(selectedCourseId)
|
const subRes = await getSubModulesByCourse(selectedCourseId)
|
||||||
const subCourses = sortByDisplayOrder((subRes.data.data.sub_courses ?? []) as any[]).map((sc) => ({
|
const subCourses = sortByDisplayOrder(subRes.data.data.sub_courses ?? []).map((sc) => ({
|
||||||
id: sc.id,
|
id: sc.id,
|
||||||
title: sc.title,
|
title: sc.title,
|
||||||
description: sc.description ?? "",
|
description: sc.description ?? "",
|
||||||
|
|
@ -328,7 +333,7 @@ export function CourseFlowBuilderPage() {
|
||||||
const videosRes = await getVideosBySubModule(sc.id)
|
const videosRes = await getVideosBySubModule(sc.id)
|
||||||
const rows = videosRes.data?.data?.videos ?? []
|
const rows = videosRes.data?.data?.videos ?? []
|
||||||
const mapped = sortByDisplayOrder(
|
const mapped = sortByDisplayOrder(
|
||||||
rows.map((video: any, idx: number) => ({
|
rows.map((video, idx) => ({
|
||||||
id: Number(video.id),
|
id: Number(video.id),
|
||||||
title: String(video.title ?? "Video"),
|
title: String(video.title ?? "Video"),
|
||||||
display_order: Number(video.display_order ?? idx),
|
display_order: Number(video.display_order ?? idx),
|
||||||
|
|
@ -352,7 +357,7 @@ export function CourseFlowBuilderPage() {
|
||||||
videoMap[subCourseId] = videos
|
videoMap[subCourseId] = videos
|
||||||
})
|
})
|
||||||
setVideosBySubCourse(videoMap)
|
setVideosBySubCourse(videoMap)
|
||||||
} catch {
|
} catch (err) {
|
||||||
notifyApiError(err, "Failed to load course flow detail.")
|
notifyApiError(err, "Failed to load course flow detail.")
|
||||||
setLearningPath(null)
|
setLearningPath(null)
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -390,7 +395,7 @@ export function CourseFlowBuilderPage() {
|
||||||
const videos =
|
const videos =
|
||||||
videosRes.status === "fulfilled"
|
videosRes.status === "fulfilled"
|
||||||
? sortByDisplayOrder(
|
? sortByDisplayOrder(
|
||||||
(videosRes.value.data?.data?.videos ?? []).map((video: any, idx: number) => ({
|
(videosRes.value.data?.data?.videos ?? []).map((video, idx) => ({
|
||||||
id: Number(video.id),
|
id: Number(video.id),
|
||||||
title: String(video.title ?? "Video"),
|
title: String(video.title ?? "Video"),
|
||||||
display_order: Number(video.display_order ?? idx),
|
display_order: Number(video.display_order ?? idx),
|
||||||
|
|
@ -403,7 +408,7 @@ export function CourseFlowBuilderPage() {
|
||||||
...prev,
|
...prev,
|
||||||
[subCourseId]: videos,
|
[subCourseId]: videos,
|
||||||
}))
|
}))
|
||||||
} catch {
|
} catch (err) {
|
||||||
notifyApiError(err, "Failed to load practice sets for course.")
|
notifyApiError(err, "Failed to load practice sets for course.")
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: false }))
|
setLoadingPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: false }))
|
||||||
|
|
@ -429,7 +434,7 @@ export function CourseFlowBuilderPage() {
|
||||||
setSavingKey("categories")
|
setSavingKey("categories")
|
||||||
try {
|
try {
|
||||||
await reorderCategories(toReorderItems(reordered))
|
await reorderCategories(toReorderItems(reordered))
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setCategories(previous)
|
setCategories(previous)
|
||||||
notifyApiError(err, "Failed to reorder categories.")
|
notifyApiError(err, "Failed to reorder categories.")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -455,7 +460,7 @@ export function CourseFlowBuilderPage() {
|
||||||
setSavingKey("courses")
|
setSavingKey("courses")
|
||||||
try {
|
try {
|
||||||
await reorderCourses(toReorderItems(reordered))
|
await reorderCourses(toReorderItems(reordered))
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: previous }))
|
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: previous }))
|
||||||
notifyApiError(err, "Failed to reorder courses.")
|
notifyApiError(err, "Failed to reorder courses.")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -481,7 +486,7 @@ export function CourseFlowBuilderPage() {
|
||||||
setSavingKey("sub-modules")
|
setSavingKey("sub-modules")
|
||||||
try {
|
try {
|
||||||
await reorderSubModules(toReorderItems(reordered))
|
await reorderSubModules(toReorderItems(reordered))
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setLearningPath((prev) => (prev ? { ...prev, sub_courses: previous } : prev))
|
setLearningPath((prev) => (prev ? { ...prev, sub_courses: previous } : prev))
|
||||||
notifyApiError(err, "Failed to reorder sub-modules.")
|
notifyApiError(err, "Failed to reorder sub-modules.")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -517,7 +522,7 @@ export function CourseFlowBuilderPage() {
|
||||||
setSavingKey(`videos-${subCourseId}`)
|
setSavingKey(`videos-${subCourseId}`)
|
||||||
try {
|
try {
|
||||||
await reorderVideos(toReorderItems(reordered))
|
await reorderVideos(toReorderItems(reordered))
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setLearningPath((prev) =>
|
setLearningPath((prev) =>
|
||||||
prev
|
prev
|
||||||
? {
|
? {
|
||||||
|
|
@ -552,7 +557,7 @@ export function CourseFlowBuilderPage() {
|
||||||
setSavingKey(`practices-${subCourseId}`)
|
setSavingKey(`practices-${subCourseId}`)
|
||||||
try {
|
try {
|
||||||
await reorderPractices(toReorderItems(reordered))
|
await reorderPractices(toReorderItems(reordered))
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
setPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: previous }))
|
setPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: previous }))
|
||||||
notifyApiError(err, "Failed to reorder practices.")
|
notifyApiError(err, "Failed to reorder practices.")
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
||||||
|
|
@ -1,68 +1,66 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { Link, useParams, useNavigate } from "react-router-dom";
|
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Plus,
|
|
||||||
LayoutGrid,
|
|
||||||
PlayCircle,
|
|
||||||
ClipboardCheck,
|
|
||||||
Pencil,
|
|
||||||
Trash2,
|
|
||||||
ChevronRight,
|
|
||||||
ArrowRight,
|
ArrowRight,
|
||||||
X,
|
ClipboardCheck,
|
||||||
FileText,
|
FileText,
|
||||||
|
LayoutGrid,
|
||||||
|
Pencil,
|
||||||
|
PlayCircle,
|
||||||
|
Plus,
|
||||||
|
Trash2
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Button } from "../../components/ui/button";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Card } from "../../components/ui/card";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
|
||||||
import { CatalogCoursePracticesPanel } from "./components/CatalogCoursePracticesPanel";
|
|
||||||
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
|
||||||
import { cn } from "../../lib/utils";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
DialogClose,
|
|
||||||
} from "../../components/ui/dialog";
|
|
||||||
import { Input } from "../../components/ui/input";
|
|
||||||
import uploadIcon from "../../assets/icons/upload.png";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
|
||||||
import {
|
import {
|
||||||
createExamPrepCatalogUnit,
|
createExamPrepCatalogUnit,
|
||||||
|
deleteExamPrepCatalogUnit,
|
||||||
getExamPrepCatalogCourses,
|
getExamPrepCatalogCourses,
|
||||||
|
getExamPrepCatalogUnits,
|
||||||
setExamPrepCatalogCoursePublishStatus,
|
setExamPrepCatalogCoursePublishStatus,
|
||||||
setExamPrepCatalogUnitAccessTier,
|
setExamPrepCatalogUnitAccessTier,
|
||||||
setExamPrepCatalogUnitPublishStatus,
|
setExamPrepCatalogUnitPublishStatus,
|
||||||
updateExamPrepCatalogUnit,
|
updateExamPrepCatalogUnit,
|
||||||
deleteExamPrepCatalogUnit,
|
|
||||||
getExamPrepCatalogUnits,
|
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { uploadImageFile } from "../../api/files.api";
|
import { uploadImageFile } from "../../api/files.api";
|
||||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
import uploadIcon from "../../assets/icons/upload.png";
|
||||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { Card } from "../../components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "../../components/ui/dialog";
|
||||||
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
|
import {
|
||||||
|
filterBySearchAndPublishStatus,
|
||||||
|
type PublishStatusFilter,
|
||||||
|
} from "../../lib/contentListFilters";
|
||||||
|
import { DisplayValue } from "../../lib/displayValue";
|
||||||
|
import {
|
||||||
|
fetchAllOffsetPages,
|
||||||
|
offsetPageFromListEnvelope,
|
||||||
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
import type {
|
import type {
|
||||||
ContentAccessTier,
|
ContentAccessTier,
|
||||||
ExamPrepCatalogCourseItem,
|
ExamPrepCatalogCourseItem,
|
||||||
ExamPrepCatalogUnitItem,
|
ExamPrepCatalogUnitItem,
|
||||||
PracticePublishStatus,
|
PracticePublishStatus,
|
||||||
} from "../../types/course.types";
|
} from "../../types/course.types";
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
import { CatalogCoursePracticesPanel } from "./components/CatalogCoursePracticesPanel";
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||||
import {
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
fetchAllOffsetPages,
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
offsetPageFromListEnvelope,
|
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
||||||
import {
|
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||||
filterBySearchAndPublishStatus,
|
|
||||||
type PublishStatusFilter,
|
|
||||||
} from "../../lib/contentListFilters";
|
|
||||||
|
|
||||||
export function CourseManagementPage() {
|
export function CourseManagementPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
|
||||||
|
|
@ -1,43 +1,47 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { ArrowLeft, Plus, Video } from "lucide-react";
|
import { ArrowLeft, Plus, Video } from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import { Button } from "../../components/ui/button";
|
|
||||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
|
||||||
import {
|
|
||||||
buildPracticeContentPaths,
|
|
||||||
type PracticeContentPathOptions,
|
|
||||||
} from "../../lib/practiceContentPaths";
|
|
||||||
import { cn } from "../../lib/utils";
|
|
||||||
import { Card } from "../../components/ui/card";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
DialogClose,
|
|
||||||
} from "../../components/ui/dialog";
|
|
||||||
import { Input } from "../../components/ui/input";
|
|
||||||
import { Textarea } from "../../components/ui/textarea";
|
|
||||||
import uploadIcon from "../../assets/icons/upload.png";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
|
||||||
import { VideoCard } from "./components/VideoCard";
|
|
||||||
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
|
||||||
import {
|
import {
|
||||||
createExamPrepModuleLesson,
|
createExamPrepModuleLesson,
|
||||||
updateExamPrepModuleLesson,
|
|
||||||
deleteExamPrepModuleLesson,
|
deleteExamPrepModuleLesson,
|
||||||
getExamPrepModuleLessons,
|
getExamPrepModuleLessons,
|
||||||
getExamPrepUnitModules,
|
getExamPrepUnitModules,
|
||||||
setExamPrepModuleLessonAccessTier,
|
setExamPrepModuleLessonAccessTier,
|
||||||
setExamPrepModuleLessonPublishStatus,
|
setExamPrepModuleLessonPublishStatus,
|
||||||
setExamPrepUnitModulePublishStatus,
|
setExamPrepUnitModulePublishStatus,
|
||||||
|
updateExamPrepModuleLesson,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { uploadImageFile } from "../../api/files.api";
|
import { uploadImageFile } from "../../api/files.api";
|
||||||
|
import uploadIcon from "../../assets/icons/upload.png";
|
||||||
|
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||||
|
import { Button } from "../../components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "../../components/ui/dialog";
|
||||||
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { Textarea } from "../../components/ui/textarea";
|
||||||
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
|
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar";
|
||||||
import { useVideoUpload } from "../../hooks/useVideoUpload";
|
import { useVideoUpload } from "../../hooks/useVideoUpload";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
|
import {
|
||||||
|
filterBySearchAndPublishStatus,
|
||||||
|
type PublishStatusFilter,
|
||||||
|
} from "../../lib/contentListFilters";
|
||||||
|
import { DisplayValue } from "../../lib/displayValue";
|
||||||
|
import {
|
||||||
|
fetchAllOffsetPages,
|
||||||
|
offsetPageFromListEnvelope,
|
||||||
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
|
import {
|
||||||
|
buildPracticeContentPaths,
|
||||||
|
type PracticeContentPathOptions,
|
||||||
|
} from "../../lib/practiceContentPaths";
|
||||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
|
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
|
||||||
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -49,15 +53,9 @@ import type {
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
||||||
import {
|
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||||
filterBySearchAndPublishStatus,
|
import { VideoCard } from "./components/VideoCard";
|
||||||
type PublishStatusFilter,
|
|
||||||
} from "../../lib/contentListFilters";
|
|
||||||
import {
|
|
||||||
fetchAllOffsetPages,
|
|
||||||
offsetPageFromListEnvelope,
|
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
|
||||||
|
|
||||||
const LESSON_THUMB_GRADIENTS = [
|
const LESSON_THUMB_GRADIENTS = [
|
||||||
"from-[#D4D4D8] to-[#71717A]",
|
"from-[#D4D4D8] to-[#71717A]",
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,34 @@
|
||||||
import { getApiErrorMessage } from "../../lib/apiErrors"
|
|
||||||
import { useEffect, useMemo, useState } from "react"
|
|
||||||
import { Link, useParams, useNavigate } from "react-router-dom"
|
|
||||||
import {
|
import {
|
||||||
Plus,
|
|
||||||
ArrowLeft,
|
|
||||||
ToggleLeft,
|
|
||||||
ToggleRight,
|
|
||||||
X,
|
|
||||||
Trash2,
|
|
||||||
Edit,
|
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
ArrowLeft,
|
||||||
|
BookOpen,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Search,
|
Edit,
|
||||||
BookOpen,
|
|
||||||
Eye,
|
Eye,
|
||||||
|
Plus,
|
||||||
|
Search,
|
||||||
|
ToggleLeft,
|
||||||
|
ToggleRight,
|
||||||
|
Trash2,
|
||||||
|
X,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import practiceSrc from "../../assets/Practice.svg"
|
import { useEffect, useMemo, useState } from "react"
|
||||||
|
import { Link, useNavigate, useParams } from "react-router-dom"
|
||||||
|
import {
|
||||||
|
createSubCategory,
|
||||||
|
deleteCourseSubCategory,
|
||||||
|
getCourseCategories,
|
||||||
|
getSubCategoriesByCategoryId,
|
||||||
|
updateSubCategory,
|
||||||
|
} from "../../api/courses.api"
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
import alertSrc from "../../assets/Alert.svg"
|
import alertSrc from "../../assets/Alert.svg"
|
||||||
import { Button } from "../../components/ui/button"
|
import practiceSrc from "../../assets/Practice.svg"
|
||||||
|
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
import { Input } from "../../components/ui/input"
|
import { Input } from "../../components/ui/input"
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
|
|
@ -31,18 +38,11 @@ import {
|
||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "../../components/ui/table"
|
} from "../../components/ui/table"
|
||||||
import {
|
import { getApiErrorMessage } from "../../lib/apiErrors"
|
||||||
getSubCategoriesByCategoryId,
|
|
||||||
getCourseCategories,
|
|
||||||
createSubCategory,
|
|
||||||
deleteCourseSubCategory,
|
|
||||||
updateSubCategory,
|
|
||||||
} from "../../api/courses.api"
|
|
||||||
import type { CategorySubCategoryListItem, CourseCategory } from "../../types/course.types"
|
|
||||||
import { cn } from "../../lib/utils"
|
|
||||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
import { DisplayValue } from "../../lib/displayValue"
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { CategorySubCategoryListItem, CourseCategory } from "../../types/course.types"
|
||||||
|
|
||||||
export function CoursesPage() {
|
export function CoursesPage() {
|
||||||
const { categoryId } = useParams<{ categoryId: string }>()
|
const { categoryId } = useParams<{ categoryId: string }>()
|
||||||
|
|
@ -151,7 +151,7 @@ export function CoursesPage() {
|
||||||
})
|
})
|
||||||
handleCloseModal()
|
handleCloseModal()
|
||||||
await fetchSubCategories()
|
await fetchSubCategories()
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
console.error("Failed to create course:", err)
|
console.error("Failed to create course:", err)
|
||||||
setSaveError(getApiErrorMessage(err, "Failed to create sub-category"))
|
setSaveError(getApiErrorMessage(err, "Failed to create sub-category"))
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -231,7 +231,7 @@ export function CoursesPage() {
|
||||||
|
|
||||||
handleCloseEditModal()
|
handleCloseEditModal()
|
||||||
await fetchSubCategories()
|
await fetchSubCategories()
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
console.error("Failed to update course:", err)
|
console.error("Failed to update course:", err)
|
||||||
setUpdateError(getApiErrorMessage(err, "Failed to update sub-category"))
|
setUpdateError(getApiErrorMessage(err, "Failed to update sub-category"))
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
||||||
|
|
@ -1,52 +1,53 @@
|
||||||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||||
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||||
|
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors";
|
||||||
|
import type { PracticeFormState } from "../../lib/practiceFullMapper";
|
||||||
|
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
|
||||||
import { navigateBack } from "../../lib/navigateBack";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Button } from "../../components/ui/button";
|
|
||||||
import { Stepper } from "../../components/ui/stepper";
|
|
||||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
|
||||||
import {
|
import {
|
||||||
getExamPrepPracticeFull,
|
getExamPrepPracticeFull,
|
||||||
getLearnEnglishPracticeFull,
|
getLearnEnglishPracticeFull,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
|
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||||
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { Stepper } from "../../components/ui/stepper";
|
||||||
import {
|
import {
|
||||||
validateLearnEnglishQuestionsWithDefinitions,
|
validateLearnEnglishQuestionsWithDefinitions,
|
||||||
} from "../../lib/learnEnglishPracticePublish";
|
} from "../../lib/learnEnglishPracticePublish";
|
||||||
|
import { navigateBack } from "../../lib/navigateBack";
|
||||||
|
import {
|
||||||
|
buildPracticeEditSnapshot,
|
||||||
|
hasPracticeEditChanges,
|
||||||
|
} from "../../lib/practiceEditDirty";
|
||||||
import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator";
|
import { executePracticeUpdate } from "../../lib/practiceEditOrchestrator";
|
||||||
import {
|
|
||||||
isIeltsSharedStimulusMode,
|
|
||||||
validatePracticeStimulusBlocks,
|
|
||||||
} from "../../lib/practiceStimulusBlocks";
|
|
||||||
import {
|
|
||||||
dedupeParents,
|
|
||||||
formatPracticeParentsSummary,
|
|
||||||
practiceParentsEqual,
|
|
||||||
validatePracticeParents,
|
|
||||||
} from "../../lib/practiceParents";
|
|
||||||
import type { PracticeParent } from "../../types/course.types";
|
|
||||||
import {
|
import {
|
||||||
mapPracticeFullToFormState,
|
mapPracticeFullToFormState,
|
||||||
unwrapPracticeFullData,
|
unwrapPracticeFullData,
|
||||||
type PreservedQuestionSetFields,
|
type PreservedQuestionSetFields,
|
||||||
} from "../../lib/practiceFullMapper";
|
} from "../../lib/practiceFullMapper";
|
||||||
import {
|
import {
|
||||||
buildPracticeEditSnapshot,
|
dedupeParents,
|
||||||
hasPracticeEditChanges,
|
formatPracticeParentsSummary,
|
||||||
} from "../../lib/practiceEditDirty";
|
practiceParentsEqual,
|
||||||
|
validatePracticeParents,
|
||||||
|
} from "../../lib/practiceParents";
|
||||||
|
import {
|
||||||
|
isIeltsSharedStimulusMode,
|
||||||
|
validatePracticeStimulusBlocks,
|
||||||
|
} from "../../lib/practiceStimulusBlocks";
|
||||||
|
import type { PracticeParent } from "../../types/course.types";
|
||||||
|
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
||||||
|
|
||||||
|
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
||||||
|
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 { PersonaStep } from "./components/practice-steps/PersonaStep";
|
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||||
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
||||||
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
||||||
|
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||||
import { personaIdNumber } from "./components/practice-steps/constants";
|
import { personaIdNumber } from "./components/practice-steps/constants";
|
||||||
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;
|
||||||
|
|
||||||
|
|
@ -150,6 +151,7 @@ export function EditPracticeFlow() {
|
||||||
}, [
|
}, [
|
||||||
lessonId,
|
lessonId,
|
||||||
lessonTitleDisplay,
|
lessonTitleDisplay,
|
||||||
|
isExamPrep,
|
||||||
isModuleContext,
|
isModuleContext,
|
||||||
isUnitContext,
|
isUnitContext,
|
||||||
isCourseContext,
|
isCourseContext,
|
||||||
|
|
@ -161,7 +163,7 @@ export function EditPracticeFlow() {
|
||||||
const programLabel = isExamPrep
|
const programLabel = isExamPrep
|
||||||
? programType === "skill"
|
? programType === "skill"
|
||||||
? "Skill-Based Courses"
|
? "Skill-Based Courses"
|
||||||
: "Duolingo/IELTS"
|
: "Makeup artistry"
|
||||||
: level
|
: level
|
||||||
? `Program ${level}`
|
? `Program ${level}`
|
||||||
: null;
|
: null;
|
||||||
|
|
@ -263,7 +265,7 @@ export function EditPracticeFlow() {
|
||||||
reload: reloadPersonas,
|
reload: reloadPersonas,
|
||||||
} = useActivePersonas({ ensurePersonaId: loadedPersonaId });
|
} = useActivePersonas({ ensurePersonaId: loadedPersonaId });
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState<PracticeFormState>({
|
||||||
title: "",
|
title: "",
|
||||||
description: "",
|
description: "",
|
||||||
storyImageUrl: "",
|
storyImageUrl: "",
|
||||||
|
|
@ -621,7 +623,7 @@ export function EditPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<ContextStep
|
<ContextStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
onCancel={() => goBack()}
|
onCancel={() => goBack()}
|
||||||
lessonTitle={lessonTitleDisplay}
|
lessonTitle={lessonTitleDisplay}
|
||||||
|
|
@ -661,7 +663,7 @@ export function EditPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<QuestionsStep
|
<QuestionsStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
prevStep={prevStep}
|
prevStep={prevStep}
|
||||||
typeDefinitions={typeDefinitions}
|
typeDefinitions={typeDefinitions}
|
||||||
|
|
@ -703,7 +705,7 @@ export function EditPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<ScenarioStep
|
<ScenarioStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
cancelHref={backPath}
|
cancelHref={backPath}
|
||||||
/>
|
/>
|
||||||
|
|
@ -725,7 +727,7 @@ export function EditPracticeFlow() {
|
||||||
return (
|
return (
|
||||||
<QuestionsStep
|
<QuestionsStep
|
||||||
formData={formData}
|
formData={formData}
|
||||||
setFormData={setFormData}
|
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||||
nextStep={nextStep}
|
nextStep={nextStep}
|
||||||
prevStep={prevStep}
|
prevStep={prevStep}
|
||||||
typeDefinitions={typeDefinitions}
|
typeDefinitions={typeDefinitions}
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,7 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react"
|
||||||
import { type Dispatch, type SetStateAction, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
import { type Dispatch, type SetStateAction, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||||
import { Link } from "react-router-dom"
|
import { Link } from "react-router-dom"
|
||||||
import { BookOpen, ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Badge } from "../../components/ui/badge"
|
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
|
||||||
import { Input } from "../../components/ui/input"
|
|
||||||
import { Select } from "../../components/ui/select"
|
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
|
||||||
import {
|
import {
|
||||||
createModule,
|
createModule,
|
||||||
deleteModule,
|
deleteModule,
|
||||||
|
|
@ -21,7 +11,17 @@ import {
|
||||||
updateModule,
|
updateModule,
|
||||||
} from "../../api/courses.api"
|
} from "../../api/courses.api"
|
||||||
import { uploadImageFile } from "../../api/files.api"
|
import { uploadImageFile } from "../../api/files.api"
|
||||||
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||||
|
import { Badge } from "../../components/ui/badge"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
|
import { Card, CardContent } from "../../components/ui/card"
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
|
import { Select } from "../../components/ui/select"
|
||||||
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
||||||
|
|
||||||
type IdFilterValue = number | "ALL"
|
type IdFilterValue = number | "ALL"
|
||||||
|
|
@ -270,10 +270,6 @@ export function HumanLanguageHierarchyPage() {
|
||||||
() => (selectedSubCategoryId === "ALL" ? [] : toCourseOptions(hierarchyRows, selectedSubCategoryId)),
|
() => (selectedSubCategoryId === "ALL" ? [] : toCourseOptions(hierarchyRows, selectedSubCategoryId)),
|
||||||
[hierarchyRows, selectedSubCategoryId],
|
[hierarchyRows, selectedSubCategoryId],
|
||||||
)
|
)
|
||||||
const selectedCourse = useMemo(
|
|
||||||
() => (selectedCourseId === "ALL" ? null : courseOptions.find((item) => item.id === selectedCourseId) ?? null),
|
|
||||||
[selectedCourseId, courseOptions],
|
|
||||||
)
|
|
||||||
|
|
||||||
const targetCourseIds = useMemo(() => {
|
const targetCourseIds = useMemo(() => {
|
||||||
if (selectedSubCategoryId === "ALL") return []
|
if (selectedSubCategoryId === "ALL") return []
|
||||||
|
|
@ -300,12 +296,23 @@ export function HumanLanguageHierarchyPage() {
|
||||||
setHierarchyError(null)
|
setHierarchyError(null)
|
||||||
try {
|
try {
|
||||||
const res = await getHumanLanguageHierarchy()
|
const res = await getHumanLanguageHierarchy()
|
||||||
setHierarchyRows(res.data?.data ?? [])
|
const tree = res.data.data
|
||||||
|
setHierarchyRows(tree.sub_categories.flatMap((subCategory) => {
|
||||||
|
const base = {
|
||||||
|
category_id: tree.category_id,
|
||||||
|
category_name: tree.category_name,
|
||||||
|
sub_category_id: subCategory.sub_category_id,
|
||||||
|
sub_category_name: subCategory.sub_category_name,
|
||||||
|
}
|
||||||
|
return subCategory.courses.length > 0
|
||||||
|
? subCategory.courses.map((course) => ({ ...base, course_id: course.course_id, course_title: course.course_name }))
|
||||||
|
: [base]
|
||||||
|
}))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
setHierarchyRows([])
|
setHierarchyRows([])
|
||||||
setHierarchyError("Could not load Human Language hierarchy")
|
setHierarchyError("Could not load academy hierarchy")
|
||||||
notifyApiError(err, "Failed to load Human Language hierarchy")
|
notifyApiError(err, "Failed to load academy hierarchy")
|
||||||
} finally {
|
} finally {
|
||||||
setHierarchyLoading(false)
|
setHierarchyLoading(false)
|
||||||
}
|
}
|
||||||
|
|
@ -675,7 +682,7 @@ export function HumanLanguageHierarchyPage() {
|
||||||
<Languages className="h-5 w-5" aria-hidden />
|
<Languages className="h-5 w-5" aria-hidden />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold tracking-tight text-grayScale-900">Human Language</h1>
|
<h1 className="text-2xl font-bold tracking-tight text-grayScale-900">Academy content</h1>
|
||||||
<p className="text-sm text-grayScale-500">Hierarchy management</p>
|
<p className="text-sm text-grayScale-500">Hierarchy management</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -379,7 +379,7 @@ export function HumanLanguageSubModulePage() {
|
||||||
|
|
||||||
const courseStructurePath = `/content/category/${categoryId}/courses/${courseId}/sub-modules`
|
const courseStructurePath = `/content/category/${categoryId}/courses/${courseId}/sub-modules`
|
||||||
const backHref = isHumanLanguageRoute ? "/content/human-language" : courseStructurePath
|
const backHref = isHumanLanguageRoute ? "/content/human-language" : courseStructurePath
|
||||||
const backLabel = isHumanLanguageRoute ? "Back to Human Language" : "Back to course structure"
|
const backLabel = isHumanLanguageRoute ? "Back to academy content" : "Back to course structure"
|
||||||
|
|
||||||
const goQuestions = (questionSetId: number) => {
|
const goQuestions = (questionSetId: number) => {
|
||||||
navigate(`${basePath}/practices/${questionSetId}/questions`)
|
navigate(`${basePath}/practices/${questionSetId}/questions`)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
|
||||||
import {
|
import {
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
ClipboardList,
|
ClipboardList,
|
||||||
|
|
@ -11,7 +10,9 @@ import {
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
import { updateQuestion } from "../../api/courses.api"
|
||||||
import {
|
import {
|
||||||
createAndAttachPlacementQuestion,
|
createAndAttachPlacementQuestion,
|
||||||
detachPlacementQuestion,
|
detachPlacementQuestion,
|
||||||
|
|
@ -23,10 +24,6 @@ import {
|
||||||
type PlacementQuestionDetail,
|
type PlacementQuestionDetail,
|
||||||
type PlacementQuestionRow,
|
type PlacementQuestionRow,
|
||||||
} from "../../api/initial-assessment.api"
|
} from "../../api/initial-assessment.api"
|
||||||
import { updateQuestion } from "../../api/courses.api"
|
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
|
||||||
import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab"
|
|
||||||
import { TablePagination } from "../../components/admin/TablePagination"
|
import { TablePagination } from "../../components/admin/TablePagination"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
|
@ -45,9 +42,12 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||||
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 { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { UnassignedLabel } from "../../lib/displayValue"
|
||||||
|
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
||||||
import { cn } from "../../lib/utils"
|
import { cn } from "../../lib/utils"
|
||||||
import type { QuestionSetDetail } from "../../types/course.types"
|
import type { QuestionSetDetail } from "../../types/course.types"
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab"
|
||||||
|
|
||||||
type TabId = "set" | "questions" | "thresholds"
|
type TabId = "set" | "questions" | "thresholds"
|
||||||
type DraftQuestionType = "MCQ" | "TRUE_FALSE"
|
type DraftQuestionType = "MCQ" | "TRUE_FALSE"
|
||||||
|
|
@ -204,7 +204,7 @@ export function InitialAssessmentPage() {
|
||||||
const [pendingDelete, setPendingDelete] = useState<PlacementQuestionRow | null>(null)
|
const [pendingDelete, setPendingDelete] = useState<PlacementQuestionRow | null>(null)
|
||||||
const [statusUpdatingId, setStatusUpdatingId] = useState<number | null>(null)
|
const [statusUpdatingId, setStatusUpdatingId] = useState<number | null>(null)
|
||||||
const [questionsPage, setQuestionsPage] = useState(1)
|
const [questionsPage, setQuestionsPage] = useState(1)
|
||||||
const [questionsPageSize, setQuestionsPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [questionsPageSize, setQuestionsPageSize] = useState<number>(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [questionsSearch, setQuestionsSearch] = useState("")
|
const [questionsSearch, setQuestionsSearch] = useState("")
|
||||||
|
|
||||||
const setFormDirty = useMemo(() => {
|
const setFormDirty = useMemo(() => {
|
||||||
|
|
|
||||||
|
|
@ -425,7 +425,7 @@ export function LearnEnglishPage() {
|
||||||
<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">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">
|
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">
|
||||||
Learn English
|
Academy Content
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mt-1 text-sm text-grayScale-500">
|
<p className="mt-1 text-sm text-grayScale-500">
|
||||||
Manage learning content by program
|
Manage learning content by program
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
||||||
import { ArrowLeft, BookOpen, Calendar, RefreshCw } from "lucide-react";
|
import { ArrowLeft, BookOpen, Calendar, RefreshCw } from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
|
|
@ -12,20 +11,7 @@ import {
|
||||||
setExamPrepPracticePublishStatus,
|
setExamPrepPracticePublishStatus,
|
||||||
setLearnEnglishPracticePublishStatus,
|
setLearnEnglishPracticePublishStatus,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import {
|
|
||||||
learnEnglishPracticeLimitHint,
|
|
||||||
parentsFromPractice,
|
|
||||||
} from "../../lib/practiceParents";
|
|
||||||
import {
|
|
||||||
hasLessonDirectPracticeLink,
|
|
||||||
isPracticeParentUnlinkNotLinkedError,
|
|
||||||
listLessonContextUnlinkParents,
|
|
||||||
practiceUnlinkBlockedMessage,
|
|
||||||
unlinkPracticeFromParent,
|
|
||||||
} from "../../lib/practiceParentUnlink";
|
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
|
||||||
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
|
|
@ -33,6 +19,24 @@ import {
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog";
|
} from "../../components/ui/dialog";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
|
import {
|
||||||
|
filterBySearchAndPublishStatus,
|
||||||
|
type PublishStatusFilter,
|
||||||
|
} from "../../lib/contentListFilters";
|
||||||
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages";
|
||||||
|
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||||
|
import {
|
||||||
|
hasLessonDirectPracticeLink,
|
||||||
|
isPracticeParentUnlinkNotLinkedError,
|
||||||
|
listLessonContextUnlinkParents,
|
||||||
|
practiceUnlinkBlockedMessage,
|
||||||
|
unlinkPracticeFromParent,
|
||||||
|
} from "../../lib/practiceParentUnlink";
|
||||||
|
import {
|
||||||
|
learnEnglishPracticeLimitHint,
|
||||||
|
parentsFromPractice,
|
||||||
|
} from "../../lib/practiceParents";
|
||||||
import type {
|
import type {
|
||||||
ExamPrepLessonPractice,
|
ExamPrepLessonPractice,
|
||||||
GetExamPrepLessonPracticesResponse,
|
GetExamPrepLessonPracticesResponse,
|
||||||
|
|
@ -41,13 +45,8 @@ import type {
|
||||||
} from "../../types/course.types";
|
} from "../../types/course.types";
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
import {
|
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||||
filterBySearchAndPublishStatus,
|
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
||||||
type PublishStatusFilter,
|
|
||||||
} from "../../lib/contentListFilters";
|
|
||||||
import { cn } from "../../lib/utils";
|
|
||||||
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages";
|
|
||||||
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
|
||||||
|
|
||||||
function unwrapExamPrepPracticesEnvelope(
|
function unwrapExamPrepPracticesEnvelope(
|
||||||
res: { data?: GetExamPrepLessonPracticesResponse & { Data?: GetExamPrepLessonPracticesResponse["data"] } },
|
res: { data?: GetExamPrepLessonPracticesResponse & { Data?: GetExamPrepLessonPracticesResponse["data"] } },
|
||||||
|
|
@ -495,8 +494,8 @@ export function LessonPracticesPage() {
|
||||||
parentsFromPractice(practiceToUnlink).filter(
|
parentsFromPractice(practiceToUnlink).filter(
|
||||||
(p) =>
|
(p) =>
|
||||||
!(
|
!(
|
||||||
p.parent_kind === lessonParent.parent_kind &&
|
p.parent_kind === "LESSON" &&
|
||||||
p.parent_id === lessonParent.parent_id
|
p.parent_id === lid
|
||||||
),
|
),
|
||||||
).length === 0
|
).length === 0
|
||||||
? " The practice will be unlinked until you attach it again. Questions are kept."
|
? " The practice will be unlinked until you attach it again. Questions are kept."
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
import { ArrowLeft, Calendar, Trash2, Video, X } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { ArrowLeft, Video, Calendar, Trash2, X } from "lucide-react";
|
|
||||||
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
|
|
@ -14,31 +13,7 @@ import {
|
||||||
setTopLevelModuleLessonAccessTier,
|
setTopLevelModuleLessonAccessTier,
|
||||||
updateTopLevelModuleLesson,
|
updateTopLevelModuleLesson,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import type {
|
|
||||||
ContentAccessTier,
|
|
||||||
ParentContextPractice,
|
|
||||||
PracticeParent,
|
|
||||||
PracticePublishStatus,
|
|
||||||
TopLevelCourseModuleItem,
|
|
||||||
TopLevelModuleLessonItem,
|
|
||||||
} from "../../types/course.types";
|
|
||||||
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
|
||||||
import {
|
|
||||||
fetchAllOffsetPages,
|
|
||||||
offsetPageFromListEnvelope,
|
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
|
||||||
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents";
|
|
||||||
import {
|
|
||||||
hasModuleDirectPracticeLink,
|
|
||||||
isPracticeParentUnlinkNotLinkedError,
|
|
||||||
listModuleContextUnlinkParents,
|
|
||||||
practiceUnlinkBlockedMessage,
|
|
||||||
unlinkPracticeFromParent,
|
|
||||||
} from "../../lib/practiceParentUnlink";
|
|
||||||
import { Button } from "../../components/ui/button";
|
import { Button } from "../../components/ui/button";
|
||||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
|
||||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
|
||||||
import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../lib/practiceContentPaths";
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
|
|
@ -49,18 +24,43 @@ import {
|
||||||
} 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 { Textarea } from "../../components/ui/textarea";
|
||||||
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
import { cn } from "../../lib/utils";
|
|
||||||
import { LessonMediaUploadField } from "./components/LessonMediaUploadField";
|
|
||||||
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
|
||||||
import { VideoCard } from "./components/VideoCard";
|
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
|
||||||
import {
|
import {
|
||||||
filterBySearchAndPublishStatus,
|
filterBySearchAndPublishStatus,
|
||||||
type PublishStatusFilter,
|
type PublishStatusFilter,
|
||||||
} from "../../lib/contentListFilters";
|
} from "../../lib/contentListFilters";
|
||||||
|
import { UnassignedLabel } from "../../lib/displayValue";
|
||||||
|
import {
|
||||||
|
fetchAllOffsetPages,
|
||||||
|
offsetPageFromListEnvelope,
|
||||||
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
|
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||||
|
import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../lib/practiceContentPaths";
|
||||||
|
import {
|
||||||
|
hasModuleDirectPracticeLink,
|
||||||
|
isPracticeParentUnlinkNotLinkedError,
|
||||||
|
listModuleContextUnlinkParents,
|
||||||
|
practiceUnlinkBlockedMessage,
|
||||||
|
unlinkPracticeFromParent,
|
||||||
|
} from "../../lib/practiceParentUnlink";
|
||||||
|
import { learnEnglishPracticeLimitHint, parentsFromPractice } from "../../lib/practiceParents";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
||||||
|
import type {
|
||||||
|
ContentAccessTier,
|
||||||
|
ParentContextPractice,
|
||||||
|
PracticeParent,
|
||||||
|
PracticePublishStatus,
|
||||||
|
TopLevelCourseModuleItem,
|
||||||
|
TopLevelModuleLessonItem,
|
||||||
|
} from "../../types/course.types";
|
||||||
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
|
import { LessonMediaUploadField } from "./components/LessonMediaUploadField";
|
||||||
|
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||||
|
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||||
|
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
||||||
|
import { VideoCard } from "./components/VideoCard";
|
||||||
|
|
||||||
const LESSON_THUMB_GRADIENTS = [
|
const LESSON_THUMB_GRADIENTS = [
|
||||||
"from-[#D4D4D8] to-[#71717A]",
|
"from-[#D4D4D8] to-[#71717A]",
|
||||||
|
|
@ -263,7 +263,7 @@ export function ModuleDetailPage() {
|
||||||
if (showPageLoading) {
|
if (showPageLoading) {
|
||||||
setLessonsLoadError(null);
|
setLessonsLoadError(null);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (err) {
|
||||||
if (showPageLoading) {
|
if (showPageLoading) {
|
||||||
setLessons([]);
|
setLessons([]);
|
||||||
setLessonsLoadError("Failed to load lessons. Please try again.");
|
setLessonsLoadError("Failed to load lessons. Please try again.");
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ export function NewContentPage() {
|
||||||
Learning Content
|
Learning Content
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||||
Build one curriculum for education courses and exam preparation.
|
Build a makeup artistry curriculum with technique demonstrations and guided practice.
|
||||||
Add practice activities and assessment exams to each hierarchy level.
|
Add practice activities and assessment exams to each hierarchy level.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -39,11 +39,11 @@ export function NewContentPage() {
|
||||||
</div>
|
</div>
|
||||||
<CardContent className="flex flex-col justify-center p-8">
|
<CardContent className="flex flex-col justify-center p-8">
|
||||||
<h2 className="text-xl font-bold text-grayScale-800">
|
<h2 className="text-xl font-bold text-grayScale-800">
|
||||||
Exam prep catalog
|
Makeup course catalog
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 max-w-2xl text-sm leading-relaxed text-grayScale-500">
|
<p className="mt-2 max-w-2xl text-sm leading-relaxed text-grayScale-500">
|
||||||
Organize catalog courses into units, modules, and lessons. Use the
|
Organize catalog courses into units, modules, and lessons. Use the
|
||||||
same structure for Education, IELTS, and Duolingo English Test
|
course structure for makeup foundations, bridal artistry, and creative techniques
|
||||||
content. Attach practice activities and assessment question sets
|
content. Attach practice activities and assessment question sets
|
||||||
where they belong.
|
where they belong.
|
||||||
</p>
|
</p>
|
||||||
|
|
|
||||||
|
|
@ -1,25 +1,7 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors";
|
import { Pencil, Plus, Trash2, X } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Plus, Pencil, Trash2, X } from "lucide-react";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { Card, CardContent } from "../../components/ui/card";
|
|
||||||
import { Button } from "../../components/ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogTrigger,
|
|
||||||
} from "../../components/ui/dialog";
|
|
||||||
import { Input } from "../../components/ui/input";
|
|
||||||
import { Textarea } from "../../components/ui/textarea";
|
|
||||||
import uploadIcon from "../../assets/icons/upload.png";
|
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
|
||||||
import alertSrc from "../../assets/Alert.svg";
|
|
||||||
import {
|
import {
|
||||||
createProgramCourse,
|
createProgramCourse,
|
||||||
deleteTopLevelCourse,
|
deleteTopLevelCourse,
|
||||||
|
|
@ -29,29 +11,46 @@ import {
|
||||||
setProgramCoursePublishStatus,
|
setProgramCoursePublishStatus,
|
||||||
updateTopLevelCourse,
|
updateTopLevelCourse,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
import { uploadImageFile } from "../../api/files.api";
|
||||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
import alertSrc from "../../assets/Alert.svg";
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
import uploadIcon from "../../assets/icons/upload.png";
|
||||||
|
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||||
|
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||||
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { Card, CardContent } from "../../components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "../../components/ui/dialog";
|
||||||
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { Textarea } from "../../components/ui/textarea";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
import {
|
import {
|
||||||
filterBySearchAndPublishStatus,
|
filterBySearchAndPublishStatus,
|
||||||
hasActiveContentFilters,
|
type PublishStatusFilter
|
||||||
type PublishStatusFilter,
|
|
||||||
} from "../../lib/contentListFilters";
|
} from "../../lib/contentListFilters";
|
||||||
import { uploadImageFile } from "../../api/files.api";
|
import { DisplayValue } from "../../lib/displayValue";
|
||||||
|
import {
|
||||||
|
fetchAllOffsetPages,
|
||||||
|
offsetPageFromListEnvelope,
|
||||||
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
import type {
|
import type {
|
||||||
ContentAccessTier,
|
ContentAccessTier,
|
||||||
LearningProgramListItem,
|
LearningProgramListItem,
|
||||||
PracticePublishStatus,
|
PracticePublishStatus,
|
||||||
ProgramCourseListItem,
|
ProgramCourseListItem,
|
||||||
} from "../../types/course.types";
|
} from "../../types/course.types";
|
||||||
|
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||||
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
|
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||||
import { PublishPracticeButton } from "./components/PublishPracticeButton";
|
import { PublishPracticeButton } from "./components/PublishPracticeButton";
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
|
||||||
import {
|
|
||||||
fetchAllOffsetPages,
|
|
||||||
offsetPageFromListEnvelope,
|
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
|
||||||
|
|
||||||
export function ProgramCoursesPage() {
|
export function ProgramCoursesPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,15 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { Link, useParams, useNavigate } from "react-router-dom";
|
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
Plus,
|
ChevronRight,
|
||||||
ClipboardList,
|
ClipboardList,
|
||||||
ListChecks,
|
ListChecks,
|
||||||
ChevronRight,
|
|
||||||
Pencil,
|
Pencil,
|
||||||
Trash2,
|
Plus,
|
||||||
X,
|
Trash2
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Button } from "../../components/ui/button";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Card } from "../../components/ui/card";
|
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
DialogClose,
|
|
||||||
} from "../../components/ui/dialog";
|
|
||||||
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 {
|
import {
|
||||||
createExamPrepCatalogCourse,
|
createExamPrepCatalogCourse,
|
||||||
deleteExamPrepCatalogCourse,
|
deleteExamPrepCatalogCourse,
|
||||||
|
|
@ -33,29 +18,43 @@ import {
|
||||||
setExamPrepCatalogCoursePublishStatus,
|
setExamPrepCatalogCoursePublishStatus,
|
||||||
updateExamPrepCatalogCourse,
|
updateExamPrepCatalogCourse,
|
||||||
} from "../../api/courses.api";
|
} from "../../api/courses.api";
|
||||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
import { uploadImageFile } from "../../api/files.api";
|
||||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
import uploadIcon from "../../assets/icons/upload.png";
|
||||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||||
|
import { Button } from "../../components/ui/button";
|
||||||
|
import { Card } from "../../components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "../../components/ui/dialog";
|
||||||
|
import { Input } from "../../components/ui/input";
|
||||||
|
import { Textarea } from "../../components/ui/textarea";
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors";
|
||||||
|
import {
|
||||||
|
filterBySearchAndPublishStatus,
|
||||||
|
hasActiveContentFilters,
|
||||||
|
type PublishStatusFilter,
|
||||||
|
} from "../../lib/contentListFilters";
|
||||||
|
import { DisplayValue } from "../../lib/displayValue";
|
||||||
|
import {
|
||||||
|
fetchAllOffsetPages,
|
||||||
|
offsetPageFromListEnvelope,
|
||||||
|
} from "../../lib/fetchAllOffsetPages";
|
||||||
import type {
|
import type {
|
||||||
ContentAccessTier,
|
ContentAccessTier,
|
||||||
ExamPrepCatalogCategory,
|
ExamPrepCatalogCategory,
|
||||||
ExamPrepCatalogCourseItem,
|
ExamPrepCatalogCourseItem,
|
||||||
PracticePublishStatus,
|
PracticePublishStatus,
|
||||||
} from "../../types/course.types";
|
} from "../../types/course.types";
|
||||||
import {
|
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||||
filterBySearchAndPublishStatus,
|
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||||
hasActiveContentFilters,
|
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||||
type PublishStatusFilter,
|
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||||
} from "../../lib/contentListFilters";
|
|
||||||
import { uploadImageFile } from "../../api/files.api";
|
|
||||||
import uploadIcon from "../../assets/icons/upload.png";
|
|
||||||
import { DisplayValue } from "../../lib/displayValue"
|
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
|
||||||
import {
|
|
||||||
fetchAllOffsetPages,
|
|
||||||
offsetPageFromListEnvelope,
|
|
||||||
} from "../../lib/fetchAllOffsetPages";
|
|
||||||
|
|
||||||
type CourseListRow = {
|
type CourseListRow = {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -109,9 +108,9 @@ export function ProgramDetailPage() {
|
||||||
const [deletingCourse, setDeletingCourse] = useState(false);
|
const [deletingCourse, setDeletingCourse] = useState(false);
|
||||||
|
|
||||||
const categoryLabels: Record<ExamPrepCatalogCategory, string> = {
|
const categoryLabels: Record<ExamPrepCatalogCategory, string> = {
|
||||||
EDUCATION: "Education",
|
EDUCATION: "Makeup Artistry",
|
||||||
IELTS: "IELTS",
|
IELTS: "Legacy: IELTS",
|
||||||
DUOLINGO: "Duolingo English Test",
|
DUOLINGO: "Legacy: Duolingo English Test",
|
||||||
};
|
};
|
||||||
const currentProgram = category
|
const currentProgram = category
|
||||||
? {
|
? {
|
||||||
|
|
@ -563,7 +562,7 @@ export function ProgramDetailPage() {
|
||||||
<Input
|
<Input
|
||||||
value={createName}
|
value={createName}
|
||||||
onChange={(e) => setCreateName(e.target.value)}
|
onChange={(e) => setCreateName(e.target.value)}
|
||||||
placeholder="e.g. English for Professionals or IELTS Academic"
|
placeholder="e.g. Bridal and Occasion Makeup"
|
||||||
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}
|
||||||
/>
|
/>
|
||||||
|
|
@ -724,7 +723,7 @@ export function ProgramDetailPage() {
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
filteredCourses.map((course: any) => (
|
filteredCourses.map((course) => (
|
||||||
<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"
|
||||||
|
|
@ -790,7 +789,7 @@ export function ProgramDetailPage() {
|
||||||
</div>
|
</div>
|
||||||
{isExamPrepCatalog && course.category ? (
|
{isExamPrepCatalog && course.category ? (
|
||||||
<p className="text-[12px] font-semibold uppercase tracking-wide text-brand-500">
|
<p className="text-[12px] font-semibold uppercase tracking-wide text-brand-500">
|
||||||
{course.category === "DUOLINGO" ? "Duolingo" : course.category}
|
{categoryLabels[course.category as ExamPrepCatalogCategory] ?? course.category}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
<h3 className="text-[18px] font-medium text-grayScale-900">
|
<h3 className="text-[18px] font-medium text-grayScale-900">
|
||||||
|
|
@ -891,9 +890,9 @@ export function ProgramDetailPage() {
|
||||||
disabled={savingEdit || uploadingEditThumbnail}
|
disabled={savingEdit || uploadingEditThumbnail}
|
||||||
>
|
>
|
||||||
<option value="">Select a category…</option>
|
<option value="">Select a category…</option>
|
||||||
<option value="EDUCATION">Education</option>
|
<option value="EDUCATION">Makeup Artistry</option>
|
||||||
<option value="IELTS">IELTS</option>
|
<option value="IELTS">Legacy: IELTS</option>
|
||||||
<option value="DUOLINGO">Duolingo</option>
|
<option value="DUOLINGO">Legacy: Duolingo</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
|
||||||
|
|
@ -5,20 +5,20 @@ import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||||
const categories = [
|
const categories = [
|
||||||
{
|
{
|
||||||
slug: "education",
|
slug: "education",
|
||||||
title: "Education",
|
title: "Makeup Artistry",
|
||||||
description: "Structured learning courses with lessons, practice, and assessments.",
|
description: "Teach makeup foundations, bridal looks, and editorial artistry through demonstrations and assessments.",
|
||||||
icon: BookOpen,
|
icon: BookOpen,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: "ielts",
|
slug: "ielts",
|
||||||
title: "IELTS",
|
title: "Legacy: IELTS",
|
||||||
description: "Prepare learners for IELTS sections, skills, and exam practice.",
|
description: "Historical language courses retained for existing learners.",
|
||||||
icon: Target,
|
icon: Target,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: "duolingo",
|
slug: "duolingo",
|
||||||
title: "Duolingo English Test",
|
title: "Legacy: Duolingo English Test",
|
||||||
description: "Build courses and exam preparation for the Duolingo English Test.",
|
description: "Historical language courses retained for existing learners.",
|
||||||
icon: Languages,
|
icon: Languages,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
@ -36,7 +36,7 @@ export function ProgramTypeSelectionPage() {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid max-w-6xl grid-cols-1 gap-6 md:grid-cols-3">
|
<div className="grid max-w-6xl grid-cols-1 gap-6 md:grid-cols-3">
|
||||||
{categories.map(({ slug, title, description, icon: Icon }) => (
|
{categories.slice(0, 1).map(({ slug, title, description, icon: Icon }) => (
|
||||||
<Link key={slug} to={`/new-content/courses/${slug}`} className="group h-full">
|
<Link key={slug} to={`/new-content/courses/${slug}`} className="group h-full">
|
||||||
<div className="flex h-full min-h-64 flex-col rounded-xl border border-grayScale-100 bg-white p-7 shadow-sm transition hover:border-brand-200 hover:shadow-md">
|
<div className="flex h-full min-h-64 flex-col rounded-xl border border-grayScale-100 bg-white p-7 shadow-sm transition hover:border-brand-200 hover:shadow-md">
|
||||||
<div className="mb-6 flex h-14 w-14 items-center justify-center rounded-full bg-brand-50">
|
<div className="mb-6 flex h-14 w-14 items-center justify-center rounded-full bg-brand-50">
|
||||||
|
|
@ -51,6 +51,12 @@ export function ProgramTypeSelectionPage() {
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<details className="text-sm text-grayScale-500">
|
||||||
|
<summary className="cursor-pointer">Historical language catalogs</summary>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-4">
|
||||||
|
{categories.slice(1).map(({slug, title}) => <Link key={slug} to={`/new-content/courses/${slug}`} className="underline">{title}</Link>)}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,3 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
|
||||||
import { Link, useNavigate, useSearchParams } from "react-router-dom"
|
|
||||||
import {
|
import {
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
|
|
@ -12,10 +9,16 @@ import {
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
import { Link, useNavigate, useSearchParams } from "react-router-dom"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { Button } from "../../components/ui/button"
|
import {
|
||||||
|
deleteQuestionTypeDefinition,
|
||||||
|
getQuestionTypeDefinitions,
|
||||||
|
} from "../../api/questionTypeDefinitions.api"
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Input } from "../../components/ui/input"
|
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||||
|
import { Button } from "../../components/ui/button"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
|
|
@ -25,18 +28,15 @@ import {
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../components/ui/dialog"
|
} from "../../components/ui/dialog"
|
||||||
|
import { Input } from "../../components/ui/input"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
import { cn } from "../../lib/utils"
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
|
import { cn } from "../../lib/utils"
|
||||||
|
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||||
import { QuestionTypeDefinitionPracticesDialog } from "./components/QuestionTypeDefinitionPracticesDialog"
|
import { QuestionTypeDefinitionPracticesDialog } from "./components/QuestionTypeDefinitionPracticesDialog"
|
||||||
import {
|
|
||||||
deleteQuestionTypeDefinition,
|
|
||||||
getQuestionTypeDefinitions,
|
|
||||||
} from "../../api/questionTypeDefinitions.api"
|
|
||||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
|
||||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
|
||||||
|
|
||||||
type StatusFilter = "All" | "ACTIVE" | "INACTIVE"
|
type StatusFilter = "All" | "ACTIVE" | "INACTIVE"
|
||||||
type ScopeFilter = "all" | "system" | "custom"
|
type ScopeFilter = "all" | "system" | "custom"
|
||||||
|
|
@ -64,7 +64,7 @@ export function QuestionTypeLibraryPage() {
|
||||||
const [query, setQuery] = useState("")
|
const [query, setQuery] = useState("")
|
||||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
const [statusFilter, setStatusFilter] = useState<StatusFilter>("All")
|
||||||
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
|
const [scopeFilter, setScopeFilter] = useState<ScopeFilter>("all")
|
||||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [pageSize, setPageSize] = useState<number>(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [offset, setOffset] = useState(0)
|
const [offset, setOffset] = useState(0)
|
||||||
const [definitionPendingDelete, setDefinitionPendingDelete] = useState<QuestionTypeDefinition | null>(null)
|
const [definitionPendingDelete, setDefinitionPendingDelete] = useState<QuestionTypeDefinition | null>(null)
|
||||||
const [deleteSubmitting, setDeleteSubmitting] = useState(false)
|
const [deleteSubmitting, setDeleteSubmitting] = useState(false)
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,25 @@
|
||||||
import { notifyApiError } from "../../lib/apiErrors"
|
|
||||||
import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
|
||||||
import { ArrowLeft, ChevronDown, ChevronRight, Image as ImageIcon, Mic, Plus, Trash2, Upload } from "lucide-react"
|
import { ArrowLeft, ChevronDown, ChevronRight, Image as ImageIcon, Mic, Plus, Trash2, Upload } from "lucide-react"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
import { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
import { toast } from "sonner"
|
||||||
import { Button } from "../../components/ui/button"
|
|
||||||
import { Input } from "../../components/ui/input"
|
|
||||||
import { Textarea } from "../../components/ui/textarea"
|
|
||||||
import { Stepper } from "../../components/ui/stepper"
|
|
||||||
import {
|
import {
|
||||||
addQuestionToSet,
|
addQuestionToSet,
|
||||||
|
createQuestion,
|
||||||
|
createQuestionSet,
|
||||||
deleteQuestion,
|
deleteQuestion,
|
||||||
getCourseCategories,
|
getCourseCategories,
|
||||||
getCoursesByCategory,
|
getCoursesByCategory,
|
||||||
getQuestionById,
|
|
||||||
getSubModulesByCourse,
|
|
||||||
createQuestion,
|
|
||||||
createQuestionSet,
|
|
||||||
// getQuestions,
|
// getQuestions,
|
||||||
getPracticeQuestionsByPractice,
|
getPracticeQuestionsByPractice,
|
||||||
|
getQuestionById,
|
||||||
getQuestionSets,
|
getQuestionSets,
|
||||||
|
getSubModulesByCourse,
|
||||||
updateQuestion,
|
updateQuestion,
|
||||||
} from "../../api/courses.api"
|
} from "../../api/courses.api"
|
||||||
import { resolveFileUrl, uploadAudioFile, uploadImageFile } from "../../api/files.api"
|
import { resolveFileUrl, uploadAudioFile, uploadImageFile } from "../../api/files.api"
|
||||||
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
|
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||||
import { useVideoUpload } from "../../hooks/useVideoUpload"
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
|
import { Button } from "../../components/ui/button"
|
||||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
|
|
@ -33,13 +27,19 @@ import {
|
||||||
DropdownMenuRadioItem,
|
DropdownMenuRadioItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "../../components/ui/dropdown-menu"
|
} from "../../components/ui/dropdown-menu"
|
||||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
import { Input } from "../../components/ui/input"
|
||||||
import { toast } from "sonner"
|
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||||
|
import { Stepper } from "../../components/ui/stepper"
|
||||||
|
import { Textarea } from "../../components/ui/textarea"
|
||||||
|
import { VideoUploadProgressBar } from "../../components/video-upload/VideoUploadProgressBar"
|
||||||
|
import { useVideoUpload } from "../../hooks/useVideoUpload"
|
||||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||||
|
import { notifyApiError } from "../../lib/apiErrors"
|
||||||
|
import { UnassignedLabel } from "../../lib/displayValue"
|
||||||
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||||
import { UnassignedLabel } from "../../lib/displayValue"
|
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
|
||||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||||
|
|
||||||
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
||||||
const ALLOWED_AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "m4a", "aac", "webm", "flac"])
|
const ALLOWED_AUDIO_EXTENSIONS = new Set(["mp3", "wav", "ogg", "m4a", "aac", "webm", "flac"])
|
||||||
|
|
@ -147,7 +147,7 @@ export function SpeakingPage() {
|
||||||
const [audioQuestions, setAudioQuestions] = useState<AudioListQuestion[]>([])
|
const [audioQuestions, setAudioQuestions] = useState<AudioListQuestion[]>([])
|
||||||
const [audioTotalCount, setAudioTotalCount] = useState(0)
|
const [audioTotalCount, setAudioTotalCount] = useState(0)
|
||||||
const [audioPage, setAudioPage] = useState(1)
|
const [audioPage, setAudioPage] = useState(1)
|
||||||
const [audioPageSize, setAudioPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
const [audioPageSize, setAudioPageSize] = useState<number>(DEFAULT_TABLE_PAGE_SIZE)
|
||||||
const [practiceOptions, setPracticeOptions] = useState<PracticeFilterOption[]>([])
|
const [practiceOptions, setPracticeOptions] = useState<PracticeFilterOption[]>([])
|
||||||
const [selectedPracticeId, setSelectedPracticeId] = useState<string>("")
|
const [selectedPracticeId, setSelectedPracticeId] = useState<string>("")
|
||||||
const [practiceFilterOpen, setPracticeFilterOpen] = useState(false)
|
const [practiceFilterOpen, setPracticeFilterOpen] = useState(false)
|
||||||
|
|
@ -1277,7 +1277,7 @@ export function SpeakingPage() {
|
||||||
const groupedAudioQuestions = useMemo(() => {
|
const groupedAudioQuestions = useMemo(() => {
|
||||||
const groups = new Map<string, { practiceId: number | null; practiceTitle: string; questions: AudioListQuestion[] }>()
|
const groups = new Map<string, { practiceId: number | null; practiceTitle: string; questions: AudioListQuestion[] }>()
|
||||||
for (const q of audioQuestions) {
|
for (const q of audioQuestions) {
|
||||||
const key = q.practice_id ? String(q.practice_id) : <UnassignedLabel />
|
const key = q.practice_id ? String(q.practice_id) : "unassigned"
|
||||||
const title = q.practice_title || "Unknown practice"
|
const title = q.practice_title || "Unknown practice"
|
||||||
if (!groups.has(key)) {
|
if (!groups.has(key)) {
|
||||||
groups.set(key, { practiceId: q.practice_id, practiceTitle: title, questions: [] })
|
groups.set(key, { practiceId: q.practice_id, practiceTitle: title, questions: [] })
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useState } from "react"
|
import { useCallback, useEffect, useState } from "react"
|
||||||
import { Link, useParams, useNavigate } from "react-router-dom"
|
import { Link, useParams, useNavigate } from "react-router-dom"
|
||||||
import { ArrowLeft, Plus, FileText, Layers, Edit, Trash2, X, Video, MoreVertical, Star, ChevronLeft, ChevronRight, MessageSquare, Play } from "lucide-react"
|
import { ArrowLeft, Plus, FileText, Layers, Edit, Trash2, X, Video, MoreVertical, Star, ChevronLeft, ChevronRight, MessageSquare, Play } from "lucide-react"
|
||||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||||
|
|
@ -128,7 +128,7 @@ export function SubModuleContentPage() {
|
||||||
fetchData()
|
fetchData()
|
||||||
}, [subModuleId, courseId])
|
}, [subModuleId, courseId])
|
||||||
|
|
||||||
const fetchPractices = async () => {
|
const fetchPractices = useCallback(async () => {
|
||||||
if (!subModuleId) return
|
if (!subModuleId) return
|
||||||
setPracticesLoading(true)
|
setPracticesLoading(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -141,9 +141,9 @@ export function SubModuleContentPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setPracticesLoading(false)
|
setPracticesLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}, [subModuleId])
|
||||||
|
|
||||||
const fetchVideos = async () => {
|
const fetchVideos = useCallback(async () => {
|
||||||
if (!subModuleId) return
|
if (!subModuleId) return
|
||||||
setVideosLoading(true)
|
setVideosLoading(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -155,9 +155,9 @@ export function SubModuleContentPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setVideosLoading(false)
|
setVideosLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}, [subModuleId])
|
||||||
|
|
||||||
const fetchRatings = async (offset = 0) => {
|
const fetchRatings = useCallback(async (offset = 0) => {
|
||||||
if (!subModuleId) return
|
if (!subModuleId) return
|
||||||
setRatingsLoading(true)
|
setRatingsLoading(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -173,7 +173,7 @@ export function SubModuleContentPage() {
|
||||||
} finally {
|
} finally {
|
||||||
setRatingsLoading(false)
|
setRatingsLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}, [subModuleId, ratingsPageSize])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeTab === "practice") {
|
if (activeTab === "practice") {
|
||||||
|
|
@ -183,13 +183,8 @@ export function SubModuleContentPage() {
|
||||||
} else if (activeTab === "ratings") {
|
} else if (activeTab === "ratings") {
|
||||||
fetchRatings(ratingsPage * ratingsPageSize)
|
fetchRatings(ratingsPage * ratingsPageSize)
|
||||||
}
|
}
|
||||||
}, [activeTab, subModuleId])
|
}, [activeTab, fetchPractices, fetchVideos, fetchRatings, ratingsPage, ratingsPageSize])
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (activeTab === "ratings") {
|
|
||||||
fetchRatings(ratingsPage * ratingsPageSize)
|
|
||||||
}
|
|
||||||
}, [ratingsPage])
|
|
||||||
|
|
||||||
const handleAddPractice = () => {
|
const handleAddPractice = () => {
|
||||||
navigate(`/content/category/${categoryId}/courses/${courseId}/sub-modules/${subModuleId}/add-practice`)
|
navigate(`/content/category/${categoryId}/courses/${courseId}/sub-modules/${subModuleId}/add-practice`)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
import type { ContentAccessTier } from "../../../types/course.types"
|
||||||
|
|
||||||
|
export function accessTierConfirmTitle(
|
||||||
|
nextTier: ContentAccessTier,
|
||||||
|
contentLabel = "content",
|
||||||
|
): string {
|
||||||
|
if (nextTier === "PREMIUM") {
|
||||||
|
return `Set this ${contentLabel} to Premium?`
|
||||||
|
}
|
||||||
|
return `Set this ${contentLabel} to Free?`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function accessTierConfirmDescription(
|
||||||
|
nextTier: ContentAccessTier,
|
||||||
|
contentLabel = "content",
|
||||||
|
): string {
|
||||||
|
if (nextTier === "PREMIUM") {
|
||||||
|
return `Learners will need a premium subscription to access this ${contentLabel}.`
|
||||||
|
}
|
||||||
|
return `This ${contentLabel} will be available to all learners at no extra cost.`
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import type { ContentAccessTier } from "../../../types/course.types"
|
|
||||||
import { Button } from "../../../components/ui/button"
|
import { Button } from "../../../components/ui/button"
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
|
|
@ -8,26 +7,8 @@ import {
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../../components/ui/dialog"
|
} from "../../../components/ui/dialog"
|
||||||
|
import type { ContentAccessTier } from "../../../types/course.types"
|
||||||
export function accessTierConfirmTitle(
|
import { accessTierConfirmDescription, accessTierConfirmTitle } from "./AccessTierConfirmDialog.shared"
|
||||||
nextTier: ContentAccessTier,
|
|
||||||
contentLabel = "content",
|
|
||||||
): string {
|
|
||||||
if (nextTier === "PREMIUM") {
|
|
||||||
return `Set this ${contentLabel} to Premium?`
|
|
||||||
}
|
|
||||||
return `Set this ${contentLabel} to Free?`
|
|
||||||
}
|
|
||||||
|
|
||||||
export function accessTierConfirmDescription(
|
|
||||||
nextTier: ContentAccessTier,
|
|
||||||
contentLabel = "content",
|
|
||||||
): string {
|
|
||||||
if (nextTier === "PREMIUM") {
|
|
||||||
return `Learners will need a premium subscription to access this ${contentLabel}.`
|
|
||||||
}
|
|
||||||
return `This ${contentLabel} will be available to all learners at no extra cost.`
|
|
||||||
}
|
|
||||||
|
|
||||||
type AccessTierConfirmDialogProps = {
|
type AccessTierConfirmDialogProps = {
|
||||||
open: boolean
|
open: boolean
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,42 @@
|
||||||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||||
import { notifyApiError } from "../../../lib/apiErrors"
|
import { BookOpen, RefreshCw } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom"
|
import { useNavigate } from "react-router-dom";
|
||||||
import { BookOpen, RefreshCw } from "lucide-react"
|
import { toast } from "sonner";
|
||||||
import { toast } from "sonner"
|
|
||||||
import {
|
import {
|
||||||
deleteExamPrepPractice,
|
deleteExamPrepPractice,
|
||||||
getExamPrepCatalogCoursePractices,
|
getExamPrepCatalogCoursePractices,
|
||||||
setExamPrepPracticePublishStatus,
|
setExamPrepPracticePublishStatus,
|
||||||
} from "../../../api/courses.api"
|
} from "../../../api/courses.api";
|
||||||
import { unwrapPracticesList } from "../../../lib/parentContextPractice"
|
import { Button } from "../../../components/ui/button";
|
||||||
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages"
|
|
||||||
import { parentsFromPractice } from "../../../lib/practiceParents"
|
|
||||||
import {
|
|
||||||
hasCatalogCourseDirectPracticeLink,
|
|
||||||
isPracticeParentUnlinkNotLinkedError,
|
|
||||||
listCatalogCourseContextUnlinkParents,
|
|
||||||
practiceUnlinkBlockedMessage,
|
|
||||||
unlinkPracticeFromParent,
|
|
||||||
} from "../../../lib/practiceParentUnlink"
|
|
||||||
import { Button } from "../../../components/ui/button"
|
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "../../../components/ui/dialog"
|
} from "../../../components/ui/dialog";
|
||||||
import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar"
|
import { notifyApiError } from "../../../lib/apiErrors";
|
||||||
import { PracticeSelectableGrid } from "./PracticeSelectableGrid"
|
|
||||||
import {
|
import {
|
||||||
filterBySearchAndPublishStatus,
|
filterBySearchAndPublishStatus,
|
||||||
type PublishStatusFilter,
|
type PublishStatusFilter,
|
||||||
} from "../../../lib/contentListFilters"
|
} from "../../../lib/contentListFilters";
|
||||||
|
import { fetchAllOffsetPages } from "../../../lib/fetchAllOffsetPages";
|
||||||
|
import { unwrapPracticesList } from "../../../lib/parentContextPractice";
|
||||||
|
import {
|
||||||
|
hasCatalogCourseDirectPracticeLink,
|
||||||
|
isPracticeParentUnlinkNotLinkedError,
|
||||||
|
listCatalogCourseContextUnlinkParents,
|
||||||
|
practiceUnlinkBlockedMessage,
|
||||||
|
unlinkPracticeFromParent,
|
||||||
|
} from "../../../lib/practiceParentUnlink";
|
||||||
|
import { parentsFromPractice } from "../../../lib/practiceParents";
|
||||||
import type {
|
import type {
|
||||||
ParentContextPractice,
|
ParentContextPractice,
|
||||||
PracticePublishStatus,
|
PracticePublishStatus,
|
||||||
} from "../../../types/course.types"
|
} from "../../../types/course.types";
|
||||||
|
import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar";
|
||||||
|
import { PracticeSelectableGrid } from "./PracticeSelectableGrid";
|
||||||
|
|
||||||
function extractPracticesPage(
|
function extractPracticesPage(
|
||||||
res: Awaited<ReturnType<typeof getExamPrepCatalogCoursePractices>>,
|
res: Awaited<ReturnType<typeof getExamPrepCatalogCoursePractices>>,
|
||||||
|
|
@ -313,8 +313,8 @@ export function CatalogCoursePracticesPanel({
|
||||||
parentsFromPractice(practiceToUnlink).filter(
|
parentsFromPractice(practiceToUnlink).filter(
|
||||||
(p) =>
|
(p) =>
|
||||||
!(
|
!(
|
||||||
p.parent_kind === catalogParent.parent_kind &&
|
p.parent_kind === "CATALOG_COURSE" &&
|
||||||
p.parent_id === catalogParent.parent_id
|
p.parent_id === catalogCourseId
|
||||||
),
|
),
|
||||||
).length === 0
|
).length === 0
|
||||||
? " The practice will be unlinked until re-attached."
|
? " The practice will be unlinked until re-attached."
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
|
||||||
|
export function sortBySortOrder<T extends { sort_order?: number }>(items: T[]): T[] {
|
||||||
|
return [...items].sort(
|
||||||
|
(a, b) => Number(a.sort_order ?? 0) - Number(b.sort_order ?? 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user