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 |
|
||||
|--------|---------|-------------|
|
||||
| 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 |
|
||||
| Lint | `npm run lint` | ESLint |
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<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>
|
||||
(function () {
|
||||
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/sortable": "^10.0.0",
|
||||
"@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-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
|
|
@ -1041,10 +1042,19 @@
|
|||
"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@fontsource/inter": {
|
||||
"version": "5.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.2.8.tgz",
|
||||
"integrity": "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg==",
|
||||
"node_modules/@fontsource/cormorant-garamond": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/cormorant-garamond/-/cormorant-garamond-5.3.0.tgz",
|
||||
"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",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@
|
|||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build": "npm run typecheck && vite build",
|
||||
"typecheck": "tsc -b",
|
||||
"test:learning": "node --test scripts/learning-integration.test.mjs",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
|
|
@ -14,7 +15,8 @@
|
|||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@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-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { createRequire } from "node:module"
|
||||
import { build } from "esbuild"
|
||||
|
||||
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("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 { AppRoutes } from "./app/AppRoutes"
|
||||
import { useTheme } from "./contexts/ThemeContext"
|
||||
import { useTheme } from "./contexts/ThemeContext.shared"
|
||||
|
||||
import { clearTeamSession } from "./lib/teamAuthStorage"
|
||||
|
||||
const SESSION_KEY = "rezina_session_active"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import http from "./http";
|
||||
import type {
|
||||
DashboardData,
|
||||
DashboardFilters,
|
||||
|
|
@ -6,6 +5,7 @@ import type {
|
|||
DateCount,
|
||||
LabelCount,
|
||||
} from "../types/analytics.types";
|
||||
import http from "./http";
|
||||
|
||||
function buildDashboardQueryParams(filters?: DashboardFilters): 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");
|
||||
|
||||
return {
|
||||
...(root as DashboardData),
|
||||
...(root as unknown as DashboardData),
|
||||
users: normalizeDashboardUsers(usersRaw, root),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,141 +1,140 @@
|
|||
import http from "./http"
|
||||
import type {
|
||||
GetCourseCategoriesResponse,
|
||||
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,
|
||||
AccessTierOnlyRequest,
|
||||
AddQuestionToSetRequest,
|
||||
CreateQuestionRequest,
|
||||
CreateQuestionResponse,
|
||||
GetQuestionDetailResponse,
|
||||
GetQuestionsParams,
|
||||
GetQuestionsResponse,
|
||||
CreateVimeoVideoRequest,
|
||||
CreateCourseCategoryRequest,
|
||||
GetCategorySubCategoriesResponse,
|
||||
GetSubCategoryCoursesResponse,
|
||||
GetSubCoursePrerequisitesResponse,
|
||||
AddSubCoursePrerequisiteRequest,
|
||||
GetLearningPathResponse,
|
||||
GetHumanLanguageLessonsResponse,
|
||||
GetHumanLanguageHierarchyResponse,
|
||||
GetCourseHierarchyResponse,
|
||||
CreateHumanLanguageLessonRequest,
|
||||
GetSubModuleLessonsResponse,
|
||||
GetSubModuleLessonDetailResponse,
|
||||
UpdateSubModuleLessonRequest,
|
||||
UpdateSubModuleLessonResponse,
|
||||
GetCourseLevelsForCourseResponse,
|
||||
GetSubModulesByModuleResponse,
|
||||
SubCourse,
|
||||
GetSubCourseEntryAssessmentResponse,
|
||||
ReorderItem,
|
||||
ReorderOrderedIdsRequest,
|
||||
GetVimeoSampleResponse,
|
||||
GetVimeoVideoResponse,
|
||||
VimeoSampleVideo,
|
||||
CreateCourseCategoryRequest,
|
||||
CreateCourseRequest,
|
||||
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,
|
||||
CreateExamPrepCatalogCoursePracticeResponse,
|
||||
CreateExamPrepUnitPracticeRequest,
|
||||
CreateExamPrepUnitPracticeResponse,
|
||||
CreateExamPrepCatalogCourseRequest,
|
||||
CreateExamPrepCatalogCourseResponse,
|
||||
CreateExamPrepCatalogUnitRequest,
|
||||
CreateExamPrepCatalogUnitResponse,
|
||||
CreateExamPrepLessonPracticeRequest,
|
||||
CreateExamPrepLessonPracticeResponse,
|
||||
CreateExamPrepModuleLessonRequest,
|
||||
CreateExamPrepModuleLessonResponse,
|
||||
CreateExamPrepPracticeRequest,
|
||||
CreateExamPrepPracticeResponse,
|
||||
GetExamPrepUnitPracticesResponse,
|
||||
GetExamPrepPracticesListResponse,
|
||||
CreateExamPrepUnitModuleRequest,
|
||||
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,
|
||||
GetExamPrepCatalogCoursesResponse,
|
||||
GetExamPrepCatalogUnitsResponse,
|
||||
GetExamPrepLessonPracticesResponse,
|
||||
GetExamPrepModuleLessonsResponse,
|
||||
GetTopLevelModuleLessonsResponse,
|
||||
GetExamPrepPracticesListResponse,
|
||||
GetExamPrepUnitModulesResponse,
|
||||
GetExamPrepUnitPracticesResponse,
|
||||
GetHumanLanguageHierarchyResponse,
|
||||
GetHumanLanguageLessonsResponse,
|
||||
GetLearningPathResponse,
|
||||
GetLearningProgramsResponse,
|
||||
GetLevelsResponse,
|
||||
GetModulesResponse,
|
||||
GetPracticeFullResponse,
|
||||
GetPracticeQuestionsByPracticeResponse,
|
||||
GetPracticesByParentContextResponse,
|
||||
GetPracticesListParams,
|
||||
GetPracticesListResponse,
|
||||
CreateParentLinkedPracticeRequest,
|
||||
CreateParentLinkedPracticeResponse,
|
||||
UpdateParentLinkedPracticeRequest,
|
||||
GetPracticeFullResponse,
|
||||
UpdatePracticeFullRequest,
|
||||
UpdatePracticeFullResponse,
|
||||
UpdateParentLinkedPracticeResponse,
|
||||
UpdatePracticeParentsRequest,
|
||||
UpdatePracticeParentsResponse,
|
||||
GetPracticesResponse,
|
||||
GetProgramCoursesResponse,
|
||||
GetProgramsResponse,
|
||||
GetQuestionDetailResponse,
|
||||
GetQuestionSetDetailResponse,
|
||||
GetQuestionSetQuestionsResponse,
|
||||
GetQuestionSetsParams,
|
||||
GetQuestionSetsResponse,
|
||||
GetQuestionsParams,
|
||||
GetQuestionsResponse,
|
||||
GetSubCategoryCoursesResponse,
|
||||
GetSubCourseEntryAssessmentResponse,
|
||||
GetSubCourseVideosResponse,
|
||||
GetSubCoursesResponse,
|
||||
GetSubModuleLessonDetailResponse,
|
||||
GetSubModuleLessonsResponse,
|
||||
GetSubModulesByModuleResponse,
|
||||
GetTopLevelCourseModulesResponse,
|
||||
GetTopLevelModuleLessonsResponse,
|
||||
GetVimeoSampleResponse,
|
||||
GetVimeoVideoResponse,
|
||||
PracticeParent,
|
||||
PublishExamPrepModuleLessonRequest,
|
||||
PublishParentLinkedPracticeRequest,
|
||||
PublishStatusOnlyRequest,
|
||||
AccessTierOnlyRequest,
|
||||
UpdateTopLevelModuleLessonRequest,
|
||||
PublishTopLevelModuleLessonRequest,
|
||||
CreateTopLevelModuleLessonRequest,
|
||||
CreateTopLevelModuleLessonResponse,
|
||||
ReorderItem,
|
||||
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"
|
||||
import http from "./http"
|
||||
|
||||
type UnifiedHierarchyRow = {
|
||||
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 {
|
||||
addQuestionToSet,
|
||||
createQuestion,
|
||||
|
|
@ -10,15 +17,8 @@ import {
|
|||
removeQuestionFromSet,
|
||||
updateQuestionSet,
|
||||
} from "./courses.api"
|
||||
import http from "./http"
|
||||
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"
|
||||
|
||||
|
|
@ -316,7 +316,7 @@ export async function listPlacementQuestions(setId: number): Promise<PlacementQu
|
|||
return rows.map((raw, index) => {
|
||||
const detail = normalizePlacementQuestionDetail(raw)
|
||||
const record = isRecord(raw) ? raw : {}
|
||||
const questionId = detail?.id ?? Number(record.question_id ?? record.id) ?? index
|
||||
const questionId = detail?.id ?? (Number(record.question_id ?? record.id) || index)
|
||||
return {
|
||||
setItemId: Number(record.id) || index,
|
||||
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 {
|
||||
BulkInAppRequest,
|
||||
BulkSendResult,
|
||||
|
|
@ -13,8 +14,7 @@ import type {
|
|||
UnreadCountResponse,
|
||||
} from "../types/notification.types"
|
||||
import { isNumericNotificationId } from "../types/notification.types"
|
||||
import { isScheduledNotification, parseBulkResponseData } from "../lib/notificationBulk"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||
import http from "./http"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
|
|
@ -375,6 +375,7 @@ function normalizeScheduledNotification(raw: unknown): ScheduledNotification | n
|
|||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
if (!id) return null
|
||||
const target = isRecord(raw.target_raw) ? raw.target_raw : undefined
|
||||
return {
|
||||
id,
|
||||
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_team_member_ids: Array.isArray(raw.target_team_member_ids)
|
||||
? raw.target_team_member_ids.map((v) => Number(v))
|
||||
: Array.isArray(raw.target_raw?.team_member_ids)
|
||||
? (raw.target_raw as { team_member_ids: unknown[] }).team_member_ids.map((v) =>
|
||||
: Array.isArray(target?.team_member_ids)
|
||||
? target.team_member_ids.map((v) =>
|
||||
Number(v),
|
||||
)
|
||||
: undefined,
|
||||
target_team_role:
|
||||
raw.target_team_role != null
|
||||
? String(raw.target_team_role)
|
||||
: raw.target_raw?.team_role != null
|
||||
? String((raw.target_raw as { team_role: unknown }).team_role)
|
||||
: target?.team_role != null
|
||||
? String(target.team_role)
|
||||
: undefined,
|
||||
target_raw: isRecord(raw.target_raw)
|
||||
? {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import http from "./http"
|
||||
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
||||
import type { GetPaymentsParams, Payment, PaymentsListData, PaymentsListResponse } from "../types/payment.types"
|
||||
import http from "./http"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
|
|
@ -108,7 +108,7 @@ export function paymentsFilterParams(
|
|||
} else if (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.reference?.trim()) next.reference = params.reference.trim()
|
||||
if (params.created_from?.trim()) next.created_from = params.created_from.trim()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import http from "./http"
|
||||
import type {
|
||||
CreateSubscriptionPlanPayload,
|
||||
SubscriptionPlan,
|
||||
|
|
@ -6,6 +5,7 @@ import type {
|
|||
SubscriptionPlansListResponse,
|
||||
UpdateSubscriptionPlanPayload,
|
||||
} from "../types/subscription.types"
|
||||
import http from "./http"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
|
|
@ -16,11 +16,14 @@ function normalizeSubscriptionPlan(raw: unknown): SubscriptionPlan | null {
|
|||
const id = Number(raw.id)
|
||||
if (!Number.isFinite(id)) return null
|
||||
|
||||
const category = raw.category
|
||||
if (category !== "EDUCATION" && category !== "LEARN_ENGLISH" && category !== "IELTS" && category !== "DUOLINGO") return null
|
||||
|
||||
return {
|
||||
id,
|
||||
name: String(raw.name ?? ""),
|
||||
description: String(raw.description ?? ""),
|
||||
category: String(raw.category ?? ""),
|
||||
category,
|
||||
duration_value: Number(raw.duration_value ?? 0),
|
||||
duration_unit: String(raw.duration_unit ?? "MONTH"),
|
||||
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 { cn } from "../lib/utils"
|
||||
|
||||
export function getSearchTokens(query: string): string[] {
|
||||
return query.trim().split(/\s+/).filter(Boolean)
|
||||
}
|
||||
import { getSearchTokens } from "./SearchHighlight.shared"
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
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 { useEffect, useRef, useState } from "react"
|
||||
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"
|
||||
|
||||
const MONTH_LABELS = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
] as const
|
||||
|
||||
const MIN_SELECTABLE_YEAR = 2000
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
import { Select } from "../ui/select"
|
||||
import { MONTH_LABELS, getYearOptions } from "./AnalyticsTimeRangeFilter.shared"
|
||||
|
||||
export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
|
||||
{ value: "", label: "All methods" },
|
||||
|
|
@ -33,15 +15,6 @@ export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
|
|||
{ value: "ADMIN_EXTEND", label: "Admin extend" },
|
||||
] 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 {
|
||||
const next = { ...base }
|
||||
if (paymentMethod?.trim()) {
|
||||
|
|
@ -52,30 +25,6 @@ function withPaymentMethod(base: DashboardFilters, paymentMethod?: string): Dash
|
|||
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 = {
|
||||
value: DashboardFilters
|
||||
onChange: (filters: DashboardFilters) => void
|
||||
|
|
@ -95,18 +44,21 @@ export function AnalyticsTimeRangeFilter({ value, onChange, className }: Analyti
|
|||
const years = getYearOptions()
|
||||
const paymentMethod = value.payment_method ?? ""
|
||||
|
||||
useEffect(() => {
|
||||
if (value.year != null) {
|
||||
setContextYear(value.year)
|
||||
}
|
||||
}, [value.year])
|
||||
const [previousYear, setPreviousYear] = useState(value.year)
|
||||
if (previousYear !== value.year) {
|
||||
setPreviousYear(value.year)
|
||||
if (value.year != null) setContextYear(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") {
|
||||
setCustomFrom(value.from ?? "")
|
||||
setCustomTo(value.to ?? "")
|
||||
}
|
||||
}, [value.from, value.mode, value.to])
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
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 type { ReactNode } from "react"
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Cell,
|
||||
Pie,
|
||||
PieChart,
|
||||
LabelList,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { formatPercentRate } from "../../lib/analytics"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card"
|
||||
import { SensitiveChart, SensitiveRevealToggle, SensitiveValue } from "../ui/sensitive-value"
|
||||
|
||||
export const SUBSCRIPTION_CHART_COLORS = [
|
||||
"#2563EB",
|
||||
"#0F766E",
|
||||
"#C2410C",
|
||||
"#7C3AED",
|
||||
"#BE123C",
|
||||
"#15803D",
|
||||
"#A16207",
|
||||
"#0891B2",
|
||||
"#4F46E5",
|
||||
"#D97706",
|
||||
"#DB2777",
|
||||
"#65A30D",
|
||||
]
|
||||
|
||||
const BRAND = "#2563EB"
|
||||
import type { PieSlice } from "./SubscriptionRevenueVisuals.shared"
|
||||
|
||||
const chartTooltipStyle = {
|
||||
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)",
|
||||
fontSize: 12,
|
||||
}
|
||||
|
||||
export const analyticsSoftCardClass =
|
||||
"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>
|
||||
)
|
||||
}
|
||||
"min-w-0 rounded-xl border border-grayScale-200/70 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]"
|
||||
|
||||
export function MonthlyRevenueTrendPanel({
|
||||
title = "Monthly Revenue Trend",
|
||||
|
|
@ -107,7 +56,7 @@ export function MonthlyRevenueTrendPanel({
|
|||
</div>
|
||||
<p className="text-xs text-grayScale-400">{subtitle}</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex min-w-0 flex-wrap items-start gap-3">
|
||||
{trailing}
|
||||
<div className="text-right">
|
||||
<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,
|
||||
gradientId = "monthlyRevenueFill",
|
||||
dataKey = "revenue",
|
||||
xKey = "month",
|
||||
height = 240,
|
||||
yTickFormatter,
|
||||
}: {
|
||||
data: Record<string, string | number>[]
|
||||
gradientId?: string
|
||||
dataKey?: string
|
||||
xKey?: string
|
||||
data: { revenue: number; month?: string; date?: string; monthIndex?: number }[]
|
||||
dataKey?: "revenue" | "month" | "date" | "monthIndex"
|
||||
xKey?: "revenue" | "month" | "date" | "monthIndex"
|
||||
height?: number
|
||||
yTickFormatter?: (value: number) => string
|
||||
}) {
|
||||
const peakIndex = data.reduce((best, row, idx) => {
|
||||
const v = Number(row[dataKey] ?? 0)
|
||||
const bestV = Number(data[best]?.[dataKey] ?? 0)
|
||||
return v > bestV ? idx : best
|
||||
}, 0)
|
||||
const peakRevenue = Math.max(0, ...data.map(row => Number(row[dataKey] ?? 0)))
|
||||
|
||||
return (
|
||||
<SensitiveChart>
|
||||
<ResponsiveContainer width="100%" height={height}>
|
||||
<AreaChart data={data} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={BRAND} stopOpacity={0.32} />
|
||||
<stop offset="100%" stopColor={BRAND} stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
|
||||
<XAxis
|
||||
dataKey={xKey}
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
fontSize={11}
|
||||
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>
|
||||
<div className="min-w-0 w-full" style={{ height }}>
|
||||
<SensitiveChart>
|
||||
<ResponsiveContainer width="100%" height="100%" minWidth={0}>
|
||||
<BarChart data={data} margin={{ left: 0, right: 8, top: 16, bottom: 4 }} barCategoryGap="25%">
|
||||
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||
<XAxis dataKey={xKey} tickLine={false} axisLine={false} fontSize={10} minTickGap={16} tick={{ fill: "var(--gs-500)" }} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={10} width={48} tick={{ fill: "var(--gs-500)" }} tickFormatter={yTickFormatter} />
|
||||
<Tooltip cursor={{ fill: "var(--gs-100)" }} formatter={(value) => [`ETB ${Number(value).toLocaleString()}`, "Revenue"]} contentStyle={chartTooltipStyle} />
|
||||
<Bar dataKey={dataKey} name="Revenue" radius={[5, 5, 0, 0]} maxBarSize={30} isAnimationActive={false}>
|
||||
{data.map((row, index) => <Cell key={String(row[xKey] ?? index)} fill={Number(row[dataKey]) === peakRevenue && peakRevenue > 0 ? "#775166" : "#B87891"} />)}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</SensitiveChart>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DonutBreakdownCard({
|
||||
export function BreakdownBarCard({
|
||||
title,
|
||||
data,
|
||||
countSuffix = "Users",
|
||||
|
|
@ -224,60 +126,25 @@ export function DonutBreakdownCard({
|
|||
|
||||
return (
|
||||
<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>
|
||||
{total > 0 && <p className="text-xs text-grayScale-500">{total.toLocaleString()} {(total === 1 ? countSuffix.replace(/s$/i, "") : countSuffix).toLowerCase()} in total</p>}
|
||||
</CardHeader>
|
||||
<CardContent className="px-5 pb-5 pt-0">
|
||||
{data.length > 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]">
|
||||
<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>
|
||||
<CardContent className="min-w-0 space-y-5 px-5 pb-6 pt-0">
|
||||
{total > 0 ? (
|
||||
<>
|
||||
<VerticalCategoryChart data={data} label={title} />
|
||||
<div className="space-y-3">
|
||||
{data.map((s) => (
|
||||
<div key={s.name} className="flex items-start gap-3">
|
||||
<span
|
||||
className="mt-0.5 h-10 w-1.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: s.color }}
|
||||
/>
|
||||
<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>
|
||||
{data.map((row, index) => (
|
||||
<div key={row.name} className="flex items-start gap-2 text-xs">
|
||||
<span className="mt-1 h-2.5 w-2.5 shrink-0 rounded-sm" style={{ backgroundColor: row.color }} />
|
||||
<span className="min-w-0 flex-1 break-words text-grayScale-700 [overflow-wrap:anywhere]">{row.name.length > 14 ? `${index + 1}. ` : ""}{row.name}</span>
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-12 text-center text-xs text-grayScale-400">{emptyMessage}</div>
|
||||
)}
|
||||
</>
|
||||
) : <div className="py-10 text-center text-xs text-grayScale-500">{emptyMessage}</div>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
|
@ -293,7 +160,7 @@ export function ActivePlansBreakdownCard({
|
|||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<DonutBreakdownCard
|
||||
<BreakdownBarCard
|
||||
title={title}
|
||||
data={data}
|
||||
countSuffix="Users"
|
||||
|
|
@ -307,25 +174,16 @@ export function RenewalRateCard({
|
|||
renewalRate,
|
||||
autoRenewCount,
|
||||
cancelledCount,
|
||||
activeNow,
|
||||
tip = "Enable automated email reminders for manual renewal users to improve retention by estimated 3–5%.",
|
||||
tip = "Review upcoming expiry dates and follow up with learners before their access ends.",
|
||||
className,
|
||||
}: {
|
||||
renewalRate: number
|
||||
autoRenewCount: number
|
||||
cancelledCount: number
|
||||
activeNow: number
|
||||
tip?: string
|
||||
className?: string
|
||||
}) {
|
||||
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 (
|
||||
<Card className={cn(analyticsSoftCardClass, className)}>
|
||||
|
|
@ -333,58 +191,25 @@ export function RenewalRateCard({
|
|||
<CardTitle className="text-base font-bold text-grayScale-900">Renewal Rate</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="px-5 pb-5 pt-0">
|
||||
<div className="flex flex-col gap-5 sm:flex-row sm:items-center">
|
||||
<div className="relative mx-auto flex h-40 w-40 shrink-0 items-center justify-center">
|
||||
<svg viewBox="0 0 120 120" className="h-full w-full -rotate-90">
|
||||
<circle cx="60" cy="60" r="48" fill="none" stroke="#F0F0F0" strokeWidth="10" />
|
||||
<circle
|
||||
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 className="rounded-xl border border-grayScale-100 bg-grayScale-100/30 p-4">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-[0.12em] text-grayScale-500">Learner retention</p>
|
||||
<div className="mb-4 mt-3 flex items-baseline gap-2">
|
||||
<span className="text-4xl font-semibold tracking-tight text-grayScale-900">{formatPercentRate(renewalRate, 0)}</span>
|
||||
<span className="text-xs text-grayScale-500">renewal rate</span>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 space-y-4">
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2 text-xs">
|
||||
<span className="font-semibold text-grayScale-800">Auto-Renew</span>
|
||||
<span className="text-grayScale-400">
|
||||
{autoRenewCount.toLocaleString()} Users
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2.5 overflow-hidden rounded-full bg-grayScale-100">
|
||||
<div
|
||||
className="h-full rounded-full transition-all"
|
||||
style={{ width: `${autoRenewPct}%`, backgroundColor: BRAND }}
|
||||
/>
|
||||
</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 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="h-full rounded-full bg-[#578E83]" style={{ width: `${ratePct}%` }} />
|
||||
</div>
|
||||
<div className="mt-1.5 flex justify-between text-[10px] text-grayScale-500"><span>0%</span><span>100%</span></div>
|
||||
</div>
|
||||
<div className="mt-5 grid grid-cols-2 gap-3">
|
||||
<div className="min-w-0 border-l-2 border-[#578E83] pl-3">
|
||||
<p className="text-xl font-semibold tabular-nums text-grayScale-900">{autoRenewCount.toLocaleString()}</p>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-grayScale-500">Auto-renew enabled</p>
|
||||
</div>
|
||||
<div className="min-w-0 border-l-2 border-[#BE6F7C] pl-3">
|
||||
<p className="text-xl font-semibold tabular-nums text-grayScale-900">{cancelledCount.toLocaleString()}</p>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-grayScale-500">Canceled</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -400,17 +225,26 @@ export function RenewalRateCard({
|
|||
)
|
||||
}
|
||||
|
||||
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],
|
||||
}))
|
||||
function VerticalCategoryChart({ data, label }: { data: PieSlice[]; label: string }) {
|
||||
const chartData = data.map((row, index) => ({ ...row, axisLabel: row.name.length > 14 ? `#${index + 1}` : row.name.toLowerCase().replace(/(^|\s)\S/g, letter => letter.toUpperCase()) }))
|
||||
return (
|
||||
<div className={cn("min-w-0", data.length > 4 ? "overflow-x-auto overscroll-x-contain" : "overflow-hidden")} role="img" aria-label={label}>
|
||||
<div className="h-[210px] w-full" style={{ minWidth: data.length > 4 ? data.length * 64 : undefined }}>
|
||||
<ResponsiveContainer width="100%" height="100%" minWidth={0}>
|
||||
<BarChart data={chartData} margin={{ top: 24, right: 8, bottom: 4, left: 0 }} barCategoryGap="28%">
|
||||
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||
<XAxis dataKey="axisLabel" interval={0} height={32} tickLine={false} axisLine={false} fontSize={10} tick={{ fill: "var(--gs-500)" }} />
|
||||
<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 }) {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import { useMemo } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { useMemo } from "react"
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import {
|
||||
createEmptyTable,
|
||||
|
|
@ -10,6 +7,9 @@ import {
|
|||
serializeTableSlotValue,
|
||||
type DynamicTableValue,
|
||||
} from "../../lib/dynamicTableValue"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
|
||||
export type DynamicTableBuilderProps = {
|
||||
value: string
|
||||
|
|
@ -91,7 +91,7 @@ export function DynamicTableBuilder({
|
|||
|
||||
const previewColumns = table.columns.map((c, i) => c.trim() || `Column ${i + 1}`)
|
||||
const previewRows = table.rows.map((row) =>
|
||||
row.map((cell, ci) => cell.trim() || ""),
|
||||
row.map((cell) => cell.trim() || ""),
|
||||
)
|
||||
|
||||
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 {
|
||||
useCallback,
|
||||
useEffect,
|
||||
|
|
@ -6,34 +6,26 @@ import {
|
|||
useState,
|
||||
type ChangeEvent,
|
||||
} from "react"
|
||||
import { Check, Image as ImageIcon, Mic, Plus, Upload, X } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { resolveMediaPreviewUrl } from "../../lib/practiceMedia"
|
||||
import { uploadAudioFile, uploadImageFile } from "../../api/files.api"
|
||||
import {
|
||||
getQuestionTypeDefinitionById,
|
||||
getQuestionTypeDefinitions,
|
||||
questionTypeDefinitionListLabel,
|
||||
} from "../../api/questionTypeDefinitions.api"
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||
import { Input } from "../ui/input"
|
||||
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 { notifyApiError } from "../../lib/apiErrors"
|
||||
import { resolveMediaPreviewUrl } from "../../lib/practiceMedia"
|
||||
import { isNoInputComponentKind } from "../../lib/questionComponentKinds"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||
import { ResolvedAudio } from "../media/ResolvedAudio"
|
||||
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"
|
||||
|
||||
export type PracticeQuestionEditorType = "MCQ" | "TRUE_FALSE" | "SHORT" | "AUDIO" | "DYNAMIC"
|
||||
export type PracticeQuestionEditorDifficulty = "EASY" | "MEDIUM" | "HARD"
|
||||
|
||||
export interface PracticeQuestionOptionDraft {
|
||||
text: string
|
||||
isCorrect: boolean
|
||||
}
|
||||
import type { PracticeQuestionDynamicRow, PracticeQuestionEditorDifficulty, PracticeQuestionEditorType, PracticeQuestionEditorValue, PracticeQuestionOptionDraft } from "./PracticeQuestionEditorFields.shared"
|
||||
|
||||
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 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) {
|
||||
const [debounced, setDebounced] = useState(value)
|
||||
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 { 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 {
|
||||
MonthlyRevenueAreaChart,
|
||||
MonthlyRevenueBarChart,
|
||||
MonthlyRevenueTrendPanel,
|
||||
SensitiveYtdValue,
|
||||
} from "../analytics/SubscriptionRevenueVisuals"
|
||||
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 }) {
|
||||
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" />
|
||||
</div>
|
||||
) : (
|
||||
<MonthlyRevenueAreaChart
|
||||
<MonthlyRevenueBarChart
|
||||
data={chartData}
|
||||
gradientId="dashboardMonthlyRevenueFill"
|
||||
|
||||
yTickFormatter={formatRevenueAxisTick}
|
||||
/>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -27,20 +27,20 @@ export function StatCard({
|
|||
<Card
|
||||
className={cn(
|
||||
analyticsSoftCardClass,
|
||||
"ui-3d-card-interactive",
|
||||
"dashboard-stat ui-3d-card-interactive",
|
||||
)}
|
||||
>
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<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}
|
||||
</div>
|
||||
<div className="mt-1.5 text-[1.75rem] font-semibold leading-none tracking-tight text-grayScale-900">
|
||||
{value}
|
||||
</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" />
|
||||
</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 { Badge } from "../ui/badge"
|
||||
import { Button } from "../ui/button"
|
||||
|
|
@ -33,11 +33,12 @@ export function AdminFiltersPanel({
|
|||
const [open, setOpen] = useState(defaultOpen || activeFilterCount > 0)
|
||||
const inlineActions = Boolean(actions)
|
||||
|
||||
useEffect(() => {
|
||||
if (!inlineActions && activeFilterCount > 0) {
|
||||
setOpen(true)
|
||||
}
|
||||
}, [activeFilterCount, inlineActions])
|
||||
const filterState = `${activeFilterCount}:${inlineActions}`
|
||||
const [previousFilterState, setPreviousFilterState] = useState(filterState)
|
||||
if (previousFilterState !== filterState) {
|
||||
setPreviousFilterState(filterState)
|
||||
if (!inlineActions && activeFilterCount > 0) setOpen(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -1,24 +1,24 @@
|
|||
import { useState } from "react";
|
||||
import { Bell } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
|
||||
import { SpinnerIcon } from "../ui/spinner-icon";
|
||||
import { useState } from "react";
|
||||
import { UnassignedLabel } from "../../lib/displayValue";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||
NOTIFICATION_TYPE_CONFIG,
|
||||
formatNotificationDateTime,
|
||||
formatNotificationTimestamp,
|
||||
formatNotificationTypeLabel,
|
||||
isMeaningfulExpiry,
|
||||
NOTIFICATION_TYPE_CONFIG,
|
||||
} from "../../lib/notificationDisplay";
|
||||
import { cn } from "../../lib/utils";
|
||||
import {
|
||||
getNotificationMessage,
|
||||
getNotificationTitle,
|
||||
type Notification,
|
||||
} from "../../types/notification.types";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
|
||||
import { SpinnerIcon } from "../ui/spinner-icon";
|
||||
|
||||
type NotificationDetailDialogProps = {
|
||||
open: boolean;
|
||||
|
|
@ -150,8 +150,6 @@ export function NotificationDetailDialog({
|
|||
) : (
|
||||
<PreviewTab
|
||||
notification={notification}
|
||||
config={config}
|
||||
Icon={Icon}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -249,12 +247,8 @@ function DetailsTab({
|
|||
|
||||
function PreviewTab({
|
||||
notification,
|
||||
config,
|
||||
Icon,
|
||||
}: {
|
||||
notification: Notification;
|
||||
config: { bg: string; color: string };
|
||||
Icon: React.ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
const title = getNotificationTitle(notification) || "Notification";
|
||||
const message = getNotificationMessage(notification) || "";
|
||||
|
|
|
|||
|
|
@ -154,9 +154,9 @@ const SUBSCRIPTION_STATUS_OPTIONS = [
|
|||
]
|
||||
|
||||
const PLAN_CATEGORY_OPTIONS = [
|
||||
{ code: "LEARN_ENGLISH", label: "Learn English" },
|
||||
{ code: "IELTS", label: "IELTS" },
|
||||
{ code: "DUOLINGO", label: "Duolingo" },
|
||||
{ code: "LEARN_ENGLISH", label: "Legacy: Learn English" },
|
||||
{ code: "IELTS", label: "Legacy: IELTS" },
|
||||
{ code: "DUOLINGO", label: "Legacy: Duolingo" },
|
||||
]
|
||||
|
||||
const BOOL_OPTIONS = [
|
||||
|
|
@ -307,7 +307,7 @@ export function PlatformAudienceFilterPanel({
|
|||
/>
|
||||
<FilterDropdown
|
||||
id="audience-language-goal"
|
||||
label="Language goal"
|
||||
label="Artistry focus"
|
||||
value={filters.languageGoal}
|
||||
allLabel="Any language goal"
|
||||
options={PROFILE_FILTER_LANGUAGE_GOALS}
|
||||
|
|
|
|||
|
|
@ -239,7 +239,7 @@ export function Sidebar({
|
|||
Admin workspace
|
||||
</p>
|
||||
<p className="mt-0.5 truncate text-xs font-semibold text-grayScale-600">
|
||||
Learning operations
|
||||
Makeup artistry academy
|
||||
</p>
|
||||
</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">
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useTheme } from "../../contexts/ThemeContext.shared"
|
||||
import { BrandLogo } from "../brand/BrandLogo"
|
||||
import { useTheme } from "../../contexts/ThemeContext"
|
||||
|
||||
|
||||
type SidebarLogoProps = {
|
||||
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 { useNavigate } from "react-router-dom"
|
||||
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
|
||||
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 { useNotifications } from "../../hooks/useNotifications"
|
||||
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
||||
import { showNotificationRealtimePopup } from "../notifications/showNotificationRealtimePopup"
|
||||
import { notifyApiError } from "../../lib/apiErrors"
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||
formatNotificationTimestamp,
|
||||
NOTIFICATION_TYPE_CONFIG,
|
||||
formatNotificationTimestamp,
|
||||
} from "../../lib/notificationDisplay"
|
||||
import {
|
||||
getNotificationPopupEnabled,
|
||||
NOTIFICATION_POPUP_PREFERENCE_EVENT,
|
||||
getNotificationPopupEnabled,
|
||||
setNotificationPopupEnabled,
|
||||
} from "../../lib/notificationPopupPreference"
|
||||
import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket"
|
||||
import { cn } from "../../lib/utils"
|
||||
import {
|
||||
getNotificationMessage,
|
||||
getNotificationTitle,
|
||||
hasNotificationContent,
|
||||
type Notification,
|
||||
} 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 DELETE_UNDO_MS = 5000
|
||||
|
|
@ -58,18 +58,17 @@ function NotificationItem({
|
|||
const [slideOut, setSlideOut] = useState(false)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isDismissing) {
|
||||
setSlideOut(false)
|
||||
return
|
||||
}
|
||||
if (!isDismissing) return
|
||||
|
||||
const el = slideRef.current
|
||||
if (!el) return
|
||||
|
||||
setSlideOut(false)
|
||||
void el.offsetHeight
|
||||
const frame = requestAnimationFrame(() => setSlideOut(true))
|
||||
return () => cancelAnimationFrame(frame)
|
||||
return () => {
|
||||
cancelAnimationFrame(frame)
|
||||
setSlideOut(false)
|
||||
}
|
||||
}, [isDismissing])
|
||||
|
||||
return (
|
||||
|
|
@ -78,7 +77,7 @@ function NotificationItem({
|
|||
ref={slideRef}
|
||||
className={cn(
|
||||
"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
|
||||
|
|
@ -212,7 +211,7 @@ export function NotificationDropdown() {
|
|||
setSelectedNotification(null)
|
||||
setSelectedNotificationId(null)
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
setHiddenIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(pending.notification.id)
|
||||
|
|
@ -285,7 +284,7 @@ export function NotificationDropdown() {
|
|||
if (markReadIfNeeded && !resolved.is_read) {
|
||||
void markOneRead(resolved.id)
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (hasNotificationContent(notification)) {
|
||||
setSelectedNotification(notification)
|
||||
if (markReadIfNeeded && !notification.is_read) {
|
||||
|
|
@ -349,16 +348,24 @@ export function NotificationDropdown() {
|
|||
setOpen(false)
|
||||
}
|
||||
}
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setOpen(false)
|
||||
}
|
||||
if (open) {
|
||||
document.addEventListener("mousedown", handleMouseDown)
|
||||
document.addEventListener("keydown", handleKeyDown)
|
||||
}
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleMouseDown)
|
||||
document.removeEventListener("keydown", handleKeyDown)
|
||||
}
|
||||
return () => document.removeEventListener("mousedown", handleMouseDown)
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
const slideTimers = slideTimersRef.current
|
||||
return () => {
|
||||
slideTimersRef.current.forEach((timer) => clearTimeout(timer))
|
||||
slideTimersRef.current.clear()
|
||||
slideTimers.forEach((timer) => clearTimeout(timer))
|
||||
slideTimers.clear()
|
||||
const current = pendingDeleteRef.current
|
||||
if (current) clearTimeout(current.timeoutId)
|
||||
pendingDeleteRef.current = null
|
||||
|
|
@ -374,6 +381,7 @@ export function NotificationDropdown() {
|
|||
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"
|
||||
aria-label="Notifications"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<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 { cn } from "../../lib/utils"
|
||||
import { NotificationDropdown } from "./NotificationDropdown"
|
||||
import { ArrowUpRight, CalendarDays, ChevronDown, ChevronRight, LogOut, Menu, Paintbrush, Search, Settings, UserCircle2 } from "lucide-react"
|
||||
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 { Avatar, AvatarFallback } from "../ui/avatar"
|
||||
import { NotificationDropdown } from "./NotificationDropdown"
|
||||
|
||||
type TopbarProps = {
|
||||
onSidebarToggle: () => void
|
||||
const destinations = [
|
||||
{ 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 [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(() => {
|
||||
const updateShortName = () => {
|
||||
const first = localStorage.getItem("user_first_name") ?? "A"
|
||||
const last = localStorage.getItem("user_last_name") ?? "A"
|
||||
setShortName(first.charAt(0).toUpperCase() + last.charAt(0).toUpperCase())
|
||||
const update = () => setAccount(readAccount())
|
||||
window.addEventListener("user-profile-updated", update)
|
||||
window.addEventListener(TEAM_SESSION_UPDATED_EVENT, update)
|
||||
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) => {
|
||||
switch (option) {
|
||||
case "profile":
|
||||
navigate("/profile")
|
||||
break
|
||||
case "settings":
|
||||
navigate("/settings")
|
||||
break
|
||||
case "logout":
|
||||
localStorage.clear()
|
||||
window.location.href = "/login"
|
||||
break
|
||||
}
|
||||
const openPage = (path: string) => {
|
||||
setSearch("")
|
||||
setSearchOpen(false)
|
||||
navigate(path)
|
||||
}
|
||||
|
||||
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">
|
||||
{/* Sidebar toggle */}
|
||||
<button
|
||||
type="button"
|
||||
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"
|
||||
onClick={onSidebarToggle}
|
||||
aria-label="Open menu"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
<header className="studio-topbar relative z-40 shrink-0 border-b">
|
||||
<div className="flex min-h-[76px] items-center justify-between gap-3 px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<button type="button" onClick={onSidebarToggle} aria-label="Open menu" className="studio-header-control lg:hidden">
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
<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} />
|
||||
</span>
|
||||
<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">
|
||||
<NotificationDropdown />
|
||||
<div className="flex shrink-0 items-center gap-2 sm:gap-4">
|
||||
<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" />
|
||||
|
||||
{/* Avatar + Radix Dropdown */}
|
||||
<DropdownMenu.Root>
|
||||
<DropdownMenu.Trigger asChild>
|
||||
<button className="focus:outline-none">
|
||||
<Avatar className="h-10 w-10 ring-2 ring-brand-100">
|
||||
<AvatarImage src="" alt="Admin" />
|
||||
<AvatarFallback className="bg-brand-500 text-sm font-medium text-white">
|
||||
{shortName}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</button>
|
||||
</DropdownMenu.Trigger>
|
||||
|
||||
<DropdownMenu.Content
|
||||
side="bottom"
|
||||
align="end"
|
||||
className="z-50 w-48 rounded-lg bg-white p-2 shadow-lg ring-1 ring-black ring-opacity-5"
|
||||
>
|
||||
<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 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">
|
||||
<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>
|
||||
</div>
|
||||
<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) }}>
|
||||
<form role="search" onSubmit={event => { event.preventDefault(); if (search.trim() && matches[0]) openPage(matches[0].path) }}>
|
||||
<label className="studio-search-field flex h-9 items-center gap-2.5 rounded-md border px-3.5">
|
||||
<Search className="h-3.5 w-3.5 shrink-0 text-brand-500" />
|
||||
<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" />
|
||||
</label>
|
||||
</form>
|
||||
{searchOpen && search.trim() && (
|
||||
<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">
|
||||
<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>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ const badgeVariants = cva(
|
|||
{
|
||||
variants: {
|
||||
variant: {
|
||||
outline: "border-grayScale-200 text-grayScale-600",
|
||||
default: "border-transparent bg-primary text-primary-foreground",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||
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 { 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"
|
||||
|
||||
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
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
|
|
@ -51,6 +25,4 @@ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { buttonVariants }
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import * as React from "react";
|
||||
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>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import * as React from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
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>(
|
||||
({ 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"
|
||||
|
||||
type SensitiveRevealContextValue = {
|
||||
revealed: boolean
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
const SensitiveRevealContext = createContext<SensitiveRevealContextValue | null>(null)
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import {
|
||||
useCallback,
|
||||
useState,
|
||||
type ReactNode
|
||||
} from "react"
|
||||
import { SensitiveRevealContext, useSensitiveReveal } from "./sensitive-value.shared"
|
||||
|
||||
export function SensitiveRevealProvider({ children }: { children: ReactNode }) {
|
||||
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({
|
||||
className,
|
||||
label = "revenue",
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ type TableProps = React.HTMLAttributes<HTMLTableElement> & {
|
|||
export const Table = React.forwardRef<HTMLTableElement, TableProps>(
|
||||
({ className, noWrapper = false, ...props }, ref) => {
|
||||
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
|
||||
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) => (
|
||||
<th
|
||||
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}
|
||||
/>
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import * as React from "react"
|
||||
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>(
|
||||
({ 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 {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type ReactNode
|
||||
} from "react"
|
||||
import {
|
||||
applyTheme,
|
||||
|
|
@ -17,15 +15,7 @@ import {
|
|||
type ResolvedTheme,
|
||||
type ThemeMode,
|
||||
} from "../lib/theme"
|
||||
|
||||
type ThemeContextValue = {
|
||||
theme: ThemeMode
|
||||
resolvedTheme: ResolvedTheme
|
||||
systemTheme: ResolvedTheme
|
||||
setTheme: (mode: ThemeMode) => void
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null)
|
||||
import { ThemeContext } from "./ThemeContext.shared"
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<ThemeMode>(() => getStoredTheme())
|
||||
|
|
@ -60,17 +50,3 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
|||
|
||||
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"
|
||||
|
||||
export function usePracticeListSelection(
|
||||
|
|
@ -11,14 +11,17 @@ export function usePracticeListSelection(
|
|||
[visiblePractices],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const visibleKey = [...visibleIds].join(",")
|
||||
const [previousVisibleKey, setPreviousVisibleKey] = useState(visibleKey)
|
||||
if (previousVisibleKey !== visibleKey) {
|
||||
setPreviousVisibleKey(visibleKey)
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(
|
||||
[...prev].filter((id) => visibleIds.has(id)),
|
||||
)
|
||||
return next.size === prev.size ? prev : next
|
||||
})
|
||||
}, [visibleIds])
|
||||
}
|
||||
|
||||
const selectedPractices = useMemo(
|
||||
() => visiblePractices.filter((practice) => selectedIds.has(practice.id)),
|
||||
|
|
|
|||
|
|
@ -7,45 +7,25 @@ import {
|
|||
type PracticeParentTitleMap,
|
||||
} from "../lib/practiceParentTitles"
|
||||
|
||||
export function usePracticeParentTitles(
|
||||
parents: PracticeParent[],
|
||||
hints?: PracticeParentTitleHints,
|
||||
) {
|
||||
const [titles, setTitles] = useState<PracticeParentTitleMap>(() => new Map())
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const parentsKey = useMemo(
|
||||
() =>
|
||||
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],
|
||||
)
|
||||
export function usePracticeParentTitles(parents: PracticeParent[], hints?: PracticeParentTitleHints) {
|
||||
const parentsKey = useMemo(() => JSON.stringify(dedupeParents(parents)), [parents])
|
||||
const hintsKey = JSON.stringify({
|
||||
courses: hints?.courses ?? {},
|
||||
modules: hints?.modules ?? {},
|
||||
lessons: hints?.lessons ?? {},
|
||||
})
|
||||
const requestKey = `${parentsKey}:${hintsKey}`
|
||||
const [result, setResult] = useState<{ key: string; titles: PracticeParentTitleMap }>(() => ({ key: "", titles: new Map() }))
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
void resolvePracticeParentTitles(parents, hints).then((resolved) => {
|
||||
if (!cancelled) {
|
||||
setTitles(resolved)
|
||||
setLoading(false)
|
||||
}
|
||||
const currentParents: PracticeParent[] = JSON.parse(parentsKey)
|
||||
const currentHints: PracticeParentTitleHints = JSON.parse(hintsKey)
|
||||
void resolvePracticeParentTitles(currentParents, currentHints).then((titles) => {
|
||||
if (!cancelled) setResult({ key: requestKey, titles })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [parentsKey, hintsKey])
|
||||
return () => { cancelled = true }
|
||||
}, [parentsKey, hintsKey, requestKey])
|
||||
|
||||
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 components;
|
||||
|
|
@ -7,94 +12,113 @@
|
|||
@layer base {
|
||||
html {
|
||||
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-100: #f5f5f5;
|
||||
--gs-200: #e0e0e0;
|
||||
--gs-200: #e5e5e5;
|
||||
--gs-300: #bdbdbd;
|
||||
--gs-400: #9e9e9e;
|
||||
--gs-500: #757575;
|
||||
--gs-600: #616161;
|
||||
--gs-400: #737373;
|
||||
--gs-500: #626262;
|
||||
--gs-600: #525252;
|
||||
--gs-700: #404040;
|
||||
--gs-800: #262626;
|
||||
--gs-900: #171717;
|
||||
--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-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);
|
||||
--control-inset: inset 0 1px 2px rgba(24, 24, 27, 0.04);
|
||||
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 240 5.9% 10%;
|
||||
--background: 0 0% 98%;
|
||||
--foreground: 0 0% 9%;
|
||||
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 240 5.9% 10%;
|
||||
--card-foreground: 0 0% 9%;
|
||||
|
||||
--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%;
|
||||
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--secondary: 0 0% 94%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 240 3.8% 46.1%;
|
||||
--muted: 0 0% 95%;
|
||||
--muted-foreground: 0 0% 40%;
|
||||
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
--accent: 0 0% 94%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 240 3.7% 25%;
|
||||
--border: 0 0% 88%;
|
||||
--input: 0 0% 85%;
|
||||
--ring: 0 0% 20%;
|
||||
|
||||
--radius: 14px;
|
||||
--radius: 8px;
|
||||
}
|
||||
|
||||
html.dark {
|
||||
color-scheme: dark;
|
||||
--gs-50: #2b2b30;
|
||||
--gs-100: #18181b;
|
||||
--gs-200: #3f3f46;
|
||||
--gs-300: #52525b;
|
||||
--gs-400: #a1a1aa;
|
||||
--gs-500: #d4d4d8;
|
||||
--gs-600: #f4f4f5;
|
||||
--chart-primary: #e5e5e5;
|
||||
--brand-50: 38 38 38;
|
||||
--brand-100: 51 51 51;
|
||||
--brand-200: 82 82 82;
|
||||
--gs-50: #262626;
|
||||
--gs-100: #171717;
|
||||
--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-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);
|
||||
--surface-highlight: rgba(255, 255, 255, 0.04);
|
||||
--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%;
|
||||
|
||||
--card: 240 3.7% 15.9%;
|
||||
--card: 0 0% 15%;
|
||||
--card-foreground: 0 0% 96%;
|
||||
|
||||
--popover: 240 3.7% 15.9%;
|
||||
--popover: 0 0% 15%;
|
||||
--popover-foreground: 0 0% 96%;
|
||||
|
||||
--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%;
|
||||
|
||||
--muted: 240 3.7% 15.9%;
|
||||
--muted-foreground: 240 4.9% 83.9%;
|
||||
--muted: 0 0% 15%;
|
||||
--muted-foreground: 0 0% 84%;
|
||||
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent: 0 0% 15%;
|
||||
--accent-foreground: 0 0% 96%;
|
||||
|
||||
--destructive: 0 62% 50%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
|
||||
--border: 240 3.7% 25%;
|
||||
--input: 240 3.7% 25%;
|
||||
--border: 0 0% 25%;
|
||||
--input: 0 0% 25%;
|
||||
--ring: 0 0% 86%;
|
||||
}
|
||||
|
||||
h1, h2 {
|
||||
font-family: "Cormorant Garamond", Georgia, serif;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
|
@ -711,3 +735,186 @@
|
|||
height: 0;
|
||||
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 (
|
||||
<div className="flex h-dvh overflow-hidden bg-grayScale-100">
|
||||
<div className="admin-app flex h-dvh overflow-hidden bg-grayScale-100">
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
isCollapsed={sidebarCollapsed}
|
||||
|
|
@ -105,7 +105,7 @@ export function AppLayout() {
|
|||
<Topbar onSidebarToggle={handleSidebarToggle} />
|
||||
<main
|
||||
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 />
|
||||
</main>
|
||||
|
|
|
|||
|
|
@ -225,11 +225,11 @@ export const RESOURCE_TYPE_OPTIONS: { value: string; label: string }[] = [
|
|||
{ value: "CATEGORY", label: "Category" },
|
||||
{ value: "SUB_COURSE", label: "Sub-course" },
|
||||
{ value: "QUESTION_SET", label: "Question set" },
|
||||
{ value: "EXAM_PREP_CATALOG_COURSE", label: "Duolingo/IELTS course" },
|
||||
{ value: "EXAM_PREP_UNIT", label: "Duolingo/IELTS unit" },
|
||||
{ value: "EXAM_PREP_MODULE", label: "Duolingo/IELTS module" },
|
||||
{ value: "EXAM_PREP_LESSON", label: "Duolingo/IELTS lesson" },
|
||||
{ value: "EXAM_PREP_PRACTICE", label: "Duolingo/IELTS practice" },
|
||||
{ value: "EXAM_PREP_CATALOG_COURSE", label: "Makeup artistry course" },
|
||||
{ value: "EXAM_PREP_UNIT", label: "Makeup artistry unit" },
|
||||
{ value: "EXAM_PREP_MODULE", label: "Makeup artistry module" },
|
||||
{ value: "EXAM_PREP_LESSON", label: "Makeup artistry lesson" },
|
||||
{ value: "EXAM_PREP_PRACTICE", label: "Makeup artistry practice" },
|
||||
{ value: "APP_VERSION", label: "App version" },
|
||||
{ value: "FIELD_OPTION", label: "Field option" },
|
||||
{ value: "DEVICE", label: "Device" },
|
||||
|
|
|
|||
|
|
@ -15,10 +15,10 @@ export const SUBSCRIPTION_STATUS_BREAKDOWN = [
|
|||
] as const
|
||||
|
||||
const SUBSCRIPTION_STATUS_COLORS: Record<string, string> = {
|
||||
ACTIVE: "#27272A",
|
||||
PENDING: "#A1A1AA",
|
||||
EXPIRED: "#3F3F46",
|
||||
CANCELLED: "#3F3F46",
|
||||
ACTIVE: "#578E83",
|
||||
PENDING: "#C39A53",
|
||||
EXPIRED: "#8F7CA2",
|
||||
CANCELLED: "#BE6F7C",
|
||||
}
|
||||
|
||||
const INACTIVE_SUBSCRIPTION_STATUSES = new Set([
|
||||
|
|
@ -185,7 +185,7 @@ export function getPrimaryQuestionTypeSummary(questionsByType: LabelCount[]): st
|
|||
}
|
||||
|
||||
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 {
|
||||
|
|
|
|||
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 { 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 { SubscriptionPlanCategory } from "../types/subscription.types"
|
||||
import type { QueryParams } from "./csv-export"
|
||||
import { nextCalendarDay } from "./payments"
|
||||
|
||||
export function paymentListFiltersToExportQuery(filters: {
|
||||
status?: string
|
||||
provider?: string
|
||||
planCategory?: string
|
||||
planCategory?: SubscriptionPlanCategory
|
||||
currency?: string
|
||||
reference?: string
|
||||
/** 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 {
|
||||
const { limit: _limit, offset: _offset, ...rest } = filters
|
||||
return rest
|
||||
const query: QueryParams = { ...filters }
|
||||
delete query.limit
|
||||
delete query.offset
|
||||
return query
|
||||
}
|
||||
|
||||
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 { SearchHighlight } from "../components/SearchHighlight"
|
||||
import { UNASSIGNED_LABEL, isUnassignedLabel } from "./displayValue.shared"
|
||||
import { cn } from "./utils"
|
||||
|
||||
export const UNASSIGNED_LABEL = "unassigned"
|
||||
|
||||
/** @deprecated Prefer 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 }) {
|
||||
return (
|
||||
<span className={cn("italic text-grayScale-400", className)}>{UNASSIGNED_LABEL}</span>
|
||||
|
|
|
|||
|
|
@ -8,9 +8,6 @@ import {
|
|||
getExamPrepUnitModules,
|
||||
getExamPrepUnitPractices,
|
||||
} from "../api/courses.api"
|
||||
import { examPrepParentsFromPractice } from "./questionTypeDefinitionPractices"
|
||||
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
||||
import { dedupeParents, parentsFromPractice } from "./practiceParents"
|
||||
import type {
|
||||
ExamPrepCatalogCourseItem,
|
||||
ExamPrepCatalogUnitItem,
|
||||
|
|
@ -19,34 +16,16 @@ import type {
|
|||
PracticeParent,
|
||||
} from "../types/course.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 DEFAULT_PROGRAM_TYPE = "proficiency"
|
||||
|
||||
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 {
|
||||
const k = (kind || "").toUpperCase()
|
||||
if (k === "CATALOG_COURSE") return "catalog_course"
|
||||
|
|
@ -80,66 +59,34 @@ function buildLessonEditPath(
|
|||
}
|
||||
|
||||
async function fetchAllCatalogCourses(): Promise<ExamPrepCatalogCourseItem[]> {
|
||||
const all: ExamPrepCatalogCourseItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getExamPrepCatalogCourses({ limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<ExamPrepCatalogCourseItem>(async (offset, limit) => {
|
||||
const res = await getExamPrepCatalogCourses({ limit, offset })
|
||||
return offsetPageFromListEnvelope<ExamPrepCatalogCourseItem>(res, "catalog_courses")
|
||||
}, PAGE_SIZE)
|
||||
return all
|
||||
}
|
||||
|
||||
async function fetchAllCatalogUnits(catalogCourseId: number): Promise<ExamPrepCatalogUnitItem[]> {
|
||||
const all: ExamPrepCatalogUnitItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getExamPrepCatalogUnits(catalogCourseId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<ExamPrepCatalogUnitItem>(async (offset, limit) => {
|
||||
const res = await getExamPrepCatalogUnits(catalogCourseId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<ExamPrepCatalogUnitItem>(res, "units")
|
||||
}, PAGE_SIZE)
|
||||
return all
|
||||
}
|
||||
|
||||
async function fetchAllUnitModules(unitId: number): Promise<ExamPrepUnitModuleItem[]> {
|
||||
const all: ExamPrepUnitModuleItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getExamPrepUnitModules(unitId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<ExamPrepUnitModuleItem>(async (offset, limit) => {
|
||||
const res = await getExamPrepUnitModules(unitId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<ExamPrepUnitModuleItem>(res, "modules")
|
||||
}, PAGE_SIZE)
|
||||
return all
|
||||
}
|
||||
|
||||
async function fetchAllModuleLessons(moduleId: number): Promise<ExamPrepModuleLessonItem[]> {
|
||||
const all: ExamPrepModuleLessonItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getExamPrepModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<ExamPrepModuleLessonItem>(async (offset, limit) => {
|
||||
const res = await getExamPrepModuleLessons(moduleId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<ExamPrepModuleLessonItem>(res, "lessons")
|
||||
}, PAGE_SIZE)
|
||||
return all
|
||||
}
|
||||
|
||||
|
|
@ -157,9 +104,9 @@ async function parentListContainsPractice(
|
|||
: tab === "unit"
|
||||
? await getExamPrepUnitPractices(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
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && offset + page.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
|
|
|
|||
|
|
@ -30,6 +30,10 @@ export async function fetchAllOffsetPages<T>(
|
|||
fetchPage: (offset: number, limit: number) => Promise<OffsetPageResult<T>>,
|
||||
batchSize = DEFAULT_BATCH_SIZE,
|
||||
): Promise<T[]> {
|
||||
if (!Number.isSafeInteger(batchSize) || batchSize <= 0) {
|
||||
throw new RangeError("batchSize must be a positive safe integer")
|
||||
}
|
||||
|
||||
const all: T[] = []
|
||||
let offset = 0
|
||||
let totalCount = Number.POSITIVE_INFINITY
|
||||
|
|
@ -38,7 +42,7 @@ export async function fetchAllOffsetPages<T>(
|
|||
const { items, total_count } = await fetchPage(offset, batchSize)
|
||||
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
|
||||
} else if (items.length === 0) {
|
||||
break
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { getExamPrepPractices, getPractices } from "../api/courses.api"
|
||||
import type { ParentContextPractice } from "../types/course.types"
|
||||
import { fetchAllOffsetPages, offsetPageFromListEnvelope } from "./fetchAllOffsetPages"
|
||||
|
||||
const FETCH_PAGE_SIZE = 100
|
||||
|
||||
|
|
@ -12,29 +13,8 @@ export async function fetchAllPractices(
|
|||
options?: FetchAllPracticesOptions,
|
||||
): Promise<ParentContextPractice[]> {
|
||||
const listPractices = options?.isExamPrep ? getExamPrepPractices : getPractices
|
||||
const all: ParentContextPractice[] = []
|
||||
let offset = 0
|
||||
let totalCount = Number.POSITIVE_INFINITY
|
||||
|
||||
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
|
||||
return fetchAllOffsetPages<ParentContextPractice>(async (offset, limit) => {
|
||||
const res = await listPractices({ limit, offset, unlinked_only: unlinkedOnly })
|
||||
return offsetPageFromListEnvelope<ParentContextPractice>(res, "practices")
|
||||
}, FETCH_PAGE_SIZE)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,6 @@ import {
|
|||
getProgramCourses,
|
||||
getTopLevelCourseModules,
|
||||
} from "../api/courses.api"
|
||||
import { unwrapPracticeFullData } from "./practiceFullMapper"
|
||||
import { parentsFromPractice } from "./practiceParents"
|
||||
import type {
|
||||
LearningProgramListItem,
|
||||
ProgramCourseListItem,
|
||||
|
|
@ -17,6 +15,9 @@ import type {
|
|||
TopLevelModuleLessonItem,
|
||||
} from "../types/course.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
|
||||
|
||||
|
|
@ -41,89 +42,35 @@ function pickNum(...values: unknown[]): number | 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[]> {
|
||||
const all: LearningProgramListItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getLearningPrograms({ limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<LearningProgramListItem>(async (offset, limit) => {
|
||||
const res = await getLearningPrograms({ limit, offset })
|
||||
return offsetPageFromListEnvelope<LearningProgramListItem>(res, "programs")
|
||||
}, PAGE_SIZE)
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllProgramCourses(programId: number): Promise<ProgramCourseListItem[]> {
|
||||
const all: ProgramCourseListItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getProgramCourses(programId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<ProgramCourseListItem>(async (offset, limit) => {
|
||||
const res = await getProgramCourses(programId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<ProgramCourseListItem>(res, "courses")
|
||||
}, PAGE_SIZE)
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllCourseModules(courseId: number): Promise<TopLevelCourseModuleItem[]> {
|
||||
const all: TopLevelCourseModuleItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getTopLevelCourseModules(courseId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<TopLevelCourseModuleItem>(async (offset, limit) => {
|
||||
const res = await getTopLevelCourseModules(courseId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<TopLevelCourseModuleItem>(res, "modules")
|
||||
}, PAGE_SIZE)
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
async function fetchAllModuleLessons(moduleId: number): Promise<TopLevelModuleLessonItem[]> {
|
||||
const all: TopLevelModuleLessonItem[] = []
|
||||
let offset = 0
|
||||
while (true) {
|
||||
const res = await getModuleLessons(moduleId, { limit: PAGE_SIZE, offset })
|
||||
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
|
||||
}
|
||||
const all = await fetchAllOffsetPages<TopLevelModuleLessonItem>(async (offset, limit) => {
|
||||
const res = await getModuleLessons(moduleId, { limit, offset })
|
||||
return offsetPageFromListEnvelope<TopLevelModuleLessonItem>(res, "lessons")
|
||||
}, PAGE_SIZE)
|
||||
return sortBySortOrder(all)
|
||||
}
|
||||
|
||||
|
|
@ -141,9 +88,9 @@ async function parentListContainsPractice(
|
|||
: tab === "module"
|
||||
? await getPracticesByParentModule(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
|
||||
const total = totalFromEnvelope(res)
|
||||
if (page.length === 0) break
|
||||
if (total != null && offset + page.length >= total) break
|
||||
if (page.length < PAGE_SIZE) break
|
||||
|
|
@ -327,7 +274,7 @@ async function resolveLearnEnglishPath(
|
|||
}
|
||||
|
||||
const parentList =
|
||||
working.parents?.length > 0
|
||||
working.parents && working.parents.length > 0
|
||||
? working.parents
|
||||
: 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 {
|
||||
finalizeMatchingAnswerPayload,
|
||||
|
|
@ -9,6 +9,13 @@ import {
|
|||
parseMatchingAnswerSlotValue,
|
||||
parseMatchingInputsSlotValue,
|
||||
} from "./matchingSlotValue"
|
||||
import {
|
||||
multipleChoiceOptionHasValue,
|
||||
multipleChoiceSlotHasContent,
|
||||
normalizeMultipleChoiceValue,
|
||||
parseMultipleChoiceSlotValue,
|
||||
} from "./multipleChoiceSlotValue"
|
||||
import { isNoInputComponentKind } from "./questionComponentKinds"
|
||||
import {
|
||||
finalizeSelectMissingWordsResponsePayload,
|
||||
finalizeSelectMissingWordsStimulusPayload,
|
||||
|
|
@ -23,14 +30,6 @@ import {
|
|||
parseSequenceOrderSlotValue,
|
||||
sequenceOrderSlotHasContent,
|
||||
} 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. */
|
||||
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 (isMultipleChoiceKind(kind)) {
|
||||
return serializeMultipleChoiceSlotValue(value as { options: unknown[] })
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
if (typeof value === "object") return JSON.stringify(value)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type {
|
||||
AuthoringProfile,
|
||||
GetPracticeFullResponse,
|
||||
PracticeFullData,
|
||||
PracticeFullPractice,
|
||||
|
|
@ -6,7 +7,6 @@ import type {
|
|||
PracticeFullQuestionSet,
|
||||
PracticeParent,
|
||||
PracticePublishStatus,
|
||||
AuthoringProfile,
|
||||
QuestionDetail,
|
||||
QuestionOption,
|
||||
QuestionShortAnswer,
|
||||
|
|
@ -26,20 +26,19 @@ import {
|
|||
questionRowHasContent,
|
||||
type LearnEnglishDefinitionQuestionInput,
|
||||
} from "./learnEnglishDefinitionQuestion"
|
||||
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
|
||||
import { validatePracticeQuestionsWithDefinitions } from "./practiceCreationOrchestrator"
|
||||
import {
|
||||
dynamicPayloadToFieldValues,
|
||||
slotApiValueToFieldString,
|
||||
} from "./practiceDynamicQuestionPayload"
|
||||
import { normalizePracticeParents, parentsFromPractice } from "./practiceParents"
|
||||
import {
|
||||
isIeltsSharedStimulusMode,
|
||||
mapApiStimulusBlocksToForm,
|
||||
mapFormStimulusBlocksToApi,
|
||||
normalizeAuthoringProfile,
|
||||
validatePracticeStimulusBlocks,
|
||||
validateStimulusBlocks,
|
||||
type PracticeFormStimulusBlock,
|
||||
type PracticeFormStimulusBlock
|
||||
} from "./practiceStimulusBlocks"
|
||||
import {
|
||||
resolveAssociatedQuestionId,
|
||||
|
|
@ -186,11 +185,11 @@ function normalizeQuestionOptions(raw: unknown): QuestionOption[] | undefined {
|
|||
|
||||
function normalizeShortAnswerItems(
|
||||
raw: unknown,
|
||||
): QuestionShortAnswer[] | string[] | undefined {
|
||||
): QuestionShortAnswer[] | undefined {
|
||||
if (!Array.isArray(raw)) return undefined
|
||||
const items = raw
|
||||
.map((entry) => {
|
||||
if (typeof entry === "string") return entry
|
||||
if (typeof entry === "string") return { acceptable_answer: entry, match_type: "CASE_INSENSITIVE" }
|
||||
const record = asRecord(entry)
|
||||
if (!record) return null
|
||||
const acceptable = pickStr(
|
||||
|
|
@ -205,8 +204,8 @@ function normalizeShortAnswerItems(
|
|||
return { acceptable_answer: acceptable, match_type: matchType }
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is QuestionShortAnswer | string =>
|
||||
entry != null && (typeof entry === "string" || Boolean(entry.acceptable_answer)),
|
||||
(entry): entry is { acceptable_answer: string; match_type: string } =>
|
||||
entry != null && Boolean(entry.acceptable_answer),
|
||||
)
|
||||
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 type { QuestionDetail } from "../types/course.types"
|
||||
import type {
|
||||
|
|
|
|||
|
|
@ -10,9 +10,10 @@ export const SUBSCRIPTION_PLAN_CATEGORIES: {
|
|||
value: SubscriptionPlanCategory
|
||||
label: string
|
||||
}[] = [
|
||||
{ value: "LEARN_ENGLISH", label: "Learn English" },
|
||||
{ value: "IELTS", label: "IELTS" },
|
||||
{ value: "DUOLINGO", label: "Duolingo" },
|
||||
{ value: "EDUCATION", label: "Makeup Artistry" },
|
||||
{ value: "LEARN_ENGLISH", label: "Legacy: Learn English" },
|
||||
{ value: "IELTS", label: "Legacy: IELTS" },
|
||||
{ value: "DUOLINGO", label: "Legacy: Duolingo" },
|
||||
]
|
||||
|
||||
export const LIFETIME_DURATION_DEFAULT = {
|
||||
|
|
@ -123,7 +124,7 @@ export function formatPlanDuration(
|
|||
}
|
||||
|
||||
export function formatPlanPrice(
|
||||
plan: Pick<SubscriptionPlan, "price" | "currency" | "is_free">,
|
||||
plan: Pick<SubscriptionPlan, "price" | "currency"> & Partial<Pick<SubscriptionPlan, "is_free">>,
|
||||
): string {
|
||||
if (plan.is_free) return "Free"
|
||||
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 {
|
||||
Dialog,
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from "../components/ui/dialog"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||
import { matchesConfirmWord } from "./typeToConfirm.shared"
|
||||
import { cn } from "./utils"
|
||||
|
||||
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 = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
|
|
@ -86,10 +83,12 @@ export function TypeToConfirmDialog({
|
|||
const [confirmText, setConfirmText] = useState("")
|
||||
const confirmMatched = matchesConfirmWord(confirmText, confirmWord)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setConfirmText("")
|
||||
}, [open, confirmWord])
|
||||
const dialogState = JSON.stringify([open, confirmWord])
|
||||
const [previousDialogState, setPreviousDialogState] = useState(dialogState)
|
||||
if (previousDialogState !== dialogState) {
|
||||
setPreviousDialogState(dialogState)
|
||||
if (open) setConfirmText("")
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!confirmMatched || confirming) return
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/**
|
||||
* 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"
|
||||
|
|
@ -27,6 +27,11 @@ const AGE_GROUP_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: "JOB_SEEKERS", label: "Job Seekers / Fresh Graduates" },
|
||||
{ code: "WORKING_PROFESSIONALS", label: "Working Professionals (Corporate/Office)" },
|
||||
|
|
@ -65,6 +70,11 @@ const EDUCATION_LEVEL_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: "WORK_CAREER", label: "Work and career" },
|
||||
{ code: "ACADEMIC_STUDY", label: "Academic study" },
|
||||
|
|
@ -74,6 +84,11 @@ const LEARNING_GOAL_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: "WORDS_GRAMMAR", label: "Finding words or grammar quickly" },
|
||||
{ code: "CONFIDENCE", label: "Feeling nervous or lacking confidence" },
|
||||
|
|
@ -81,12 +96,21 @@ const LANGUAGE_CHALLENGE_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: "PRACTICE_TO_SPEAK_ENGLISH", label: "Practice Speaking English" },
|
||||
{ code: "SKILL_BASED_COURSES", label: "Skill-based Courses" },
|
||||
]
|
||||
|
||||
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: "HOBBIES_SPORTS_MUSIC", label: "Hobbies, Sports, Music" },
|
||||
{ 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_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_LEARNING_GOALS = LEARNING_GOAL_OPTIONS
|
||||
export const PROFILE_FILTER_LANGUAGE_GOALS = LANGUAGE_GOAL_OPTIONS
|
||||
export const PROFILE_FILTER_FAVOURITE_TOPICS = FAVOURITE_TOPIC_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.filter((option) => ["MAKEUP_FOUNDATIONS", "PROFESSIONAL_ARTISTRY", "CREATIVE_ARTISTRY"].includes(option.code))
|
||||
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_ETHIOPIA_REGIONS = ETHIOPIA_REGION_OPTIONS
|
||||
|
||||
|
|
@ -290,18 +314,18 @@ function isCatchAllProfileValue(normalized: string): boolean {
|
|||
}
|
||||
|
||||
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(
|
||||
raw: string | null | undefined,
|
||||
options: ProfileFieldOption[],
|
||||
defaultCode: string,
|
||||
_defaultCode: string,
|
||||
aliases?: Record<string, string>,
|
||||
): string {
|
||||
const trimmed = raw?.trim() ?? ""
|
||||
const normalized = normalizeProfileFieldKey(trimmed)
|
||||
if (isCatchAllProfileValue(normalized)) return defaultCode
|
||||
if (isCatchAllProfileValue(normalized)) return "UNASSIGNED"
|
||||
|
||||
if (aliases?.[normalized]) return aliases[normalized]
|
||||
|
||||
|
|
@ -317,7 +341,7 @@ function resolveProfileFieldCode(
|
|||
if (lower === opt.label.toLowerCase()) return opt.code
|
||||
}
|
||||
|
||||
return defaultCode
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function displayProfileFieldLabel(
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import {
|
||||
// Activity,
|
||||
BadgeCheck,
|
||||
Video,
|
||||
Bell,
|
||||
CreditCard,
|
||||
// Coins,
|
||||
DollarSign,
|
||||
HelpCircle,
|
||||
|
|
@ -9,70 +10,69 @@ import {
|
|||
Star,
|
||||
// TrendingUp,
|
||||
Users,
|
||||
UserX,
|
||||
Bell,
|
||||
CreditCard,
|
||||
UsersRound,
|
||||
UserX,
|
||||
Video,
|
||||
} from "lucide-react"
|
||||
import spinnerSrc from "../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
Bar,
|
||||
BarChart,
|
||||
Cell,
|
||||
CartesianGrid,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} 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 { DashboardProfileRail } from "../components/dashboard/DashboardProfileRail"
|
||||
import { StatCard } from "../components/dashboard/StatCard"
|
||||
import {
|
||||
ActivePlansBreakdownCard,
|
||||
RenewalRateCard,
|
||||
DonutBreakdownCard,
|
||||
analyticsSoftCardClass,
|
||||
labelCountsToPieSlices,
|
||||
SUBSCRIPTION_CHART_COLORS,
|
||||
} from "../components/analytics/SubscriptionRevenueVisuals"
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { getDashboard } from "../api/analytics.api"
|
||||
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
|
||||
import { getSubscriptionPlans } from "../api/subscription-plans.api"
|
||||
import { getTeamMemberById } from "../api/team.api"
|
||||
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 { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||
import { SensitiveRevealProvider, SensitiveValue } from "../components/ui/sensitive-value"
|
||||
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 {
|
||||
buildSubscriptionStatusPie,
|
||||
formatAnalyticsSeriesDate,
|
||||
getPrimaryQuestionTypeSummary,
|
||||
getSeriesPeriodLabel,
|
||||
getSubscriptionMetrics,
|
||||
getVideoLessonsSummary,
|
||||
buildSubscriptionStatusPie,
|
||||
} from "../lib/analytics"
|
||||
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
||||
import { formatAppDateTime } from "../lib/datetime"
|
||||
import { formatAverageStars } from "../lib/ratingsDisplay"
|
||||
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 { SubscriptionPlan } from "../types/subscription.types"
|
||||
|
||||
const PIE_COLORS = SUBSCRIPTION_CHART_COLORS
|
||||
const CHART_BRAND = SUBSCRIPTION_CHART_COLORS[0]
|
||||
const chartTooltipStyle = {
|
||||
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)",
|
||||
fontSize: 12,
|
||||
}
|
||||
|
||||
function DashboardSectionTitle({ children }: { children: ReactNode }) {
|
||||
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
|
||||
|
||||
const generatedAt = dashboard ? formatAppDateTime(dashboard.generated_at) : ""
|
||||
|
||||
const registrationPeakIndex = registrationData.reduce((best, row, idx) => {
|
||||
return row.count > (registrationData[best]?.count ?? 0) ? idx : best
|
||||
}, 0)
|
||||
const peakRegistrations = Math.max(0, ...registrationData.map(row => row.count))
|
||||
|
||||
return (
|
||||
<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="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-layout mx-auto w-full min-w-0 max-w-[1800px] pb-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="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">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-brand-500" />
|
||||
Dashboard
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-900 sm:text-3xl">
|
||||
Welcome back, {userFirstName || localStorage.getItem("user_first_name") || "there"}
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-600">
|
||||
Hello {userFirstName || localStorage.getItem("user_first_name") || "there"}
|
||||
</h1>
|
||||
<p className="mt-1.5 text-sm text-grayScale-500">
|
||||
Snapshot for {getDashboardFilterLabel(filters)}
|
||||
|
|
@ -389,56 +388,16 @@ export function DashboardPage() {
|
|||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="h-[280px] px-5 pb-5 pt-2">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={registrationData} margin={{ left: 4, right: 8, top: 12, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="dashboardRegFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={CHART_BRAND} stopOpacity={0.32} />
|
||||
<stop offset="100%" stopColor={CHART_BRAND} stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid vertical={false} stroke="#EEEEEE" strokeDasharray="4 4" />
|
||||
<XAxis
|
||||
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 width="100%" height="100%" minWidth={0}>
|
||||
<BarChart data={registrationData} margin={{ left: 0, right: 8, top: 16, bottom: 4 }} barCategoryGap="25%">
|
||||
<CartesianGrid vertical={false} stroke="var(--gs-200)" strokeDasharray="3 5" strokeOpacity={0.5} />
|
||||
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={10} minTickGap={20} tick={{ fill: "var(--gs-500)" }} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={10} width={36} allowDecimals={false} tick={{ fill: "var(--gs-500)" }} />
|
||||
<Tooltip cursor={{ fill: "var(--gs-100)" }} contentStyle={chartTooltipStyle} />
|
||||
<Bar dataKey="count" name="Registrations" radius={[5, 5, 0, 0]} maxBarSize={24} isAnimationActive={false}>
|
||||
{registrationData.map(row => <Cell key={row.date} fill={row.count === peakRegistrations && peakRegistrations > 0 ? "#27685F" : "#79AAA0"} />)}
|
||||
</Bar>
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
|
@ -454,7 +413,7 @@ export function DashboardPage() {
|
|||
|
||||
<section className="space-y-3">
|
||||
<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
|
||||
data={labelCountsToPieSlices(
|
||||
(dashboard.subscriptions.active_by_plan?.length
|
||||
|
|
@ -470,14 +429,9 @@ export function DashboardPage() {
|
|||
renewalRate={dashboard.subscriptions.renewal?.renewal_rate ?? 0}
|
||||
autoRenewCount={dashboard.subscriptions.snapshot?.auto_renew_enabled ?? 0}
|
||||
cancelledCount={dashboard.subscriptions.snapshot?.cancelled_now ?? 0}
|
||||
activeNow={
|
||||
dashboard.subscriptions.snapshot?.active_now ??
|
||||
subscriptionMetrics?.active ??
|
||||
0
|
||||
}
|
||||
/>
|
||||
{subscriptionStatusData.length > 0 ? (
|
||||
<DonutBreakdownCard
|
||||
<BreakdownBarCard
|
||||
title="Subscription Status"
|
||||
data={subscriptionStatusData}
|
||||
countSuffix="Subscriptions"
|
||||
|
|
@ -652,6 +606,8 @@ export function DashboardPage() {
|
|||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<DashboardProfileRail firstName={userFirstName} dashboard={dashboard} />
|
||||
</div>
|
||||
</SensitiveRevealProvider>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { Pencil, User } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { notifyApiError } from "../lib/apiErrors";
|
||||
import { getTeamMe, updateTeamMe } from "../api/team.api";
|
||||
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
|
|
@ -20,12 +20,14 @@ import {
|
|||
import { Input } from "../components/ui/input";
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||
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 type { TeamMeProfile } from "../types/team.types";
|
||||
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
|
||||
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 {
|
||||
return formatAppLongDate(dateStr, "unassigned")
|
||||
|
|
@ -44,11 +46,6 @@ function formatRoleLabel(role: string): string {
|
|||
.join(" ");
|
||||
}
|
||||
|
||||
function displayValue(value: string | null | undefined): string {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : "unassigned";
|
||||
}
|
||||
|
||||
function FieldGroup({
|
||||
label,
|
||||
value,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { notifyApiError } from "../lib/apiErrors"
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
CreditCard,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Globe,
|
||||
|
|
@ -8,11 +7,16 @@ import {
|
|||
Moon,
|
||||
Palette,
|
||||
Shield,
|
||||
Smartphone,
|
||||
Sun,
|
||||
User,
|
||||
CreditCard,
|
||||
Smartphone,
|
||||
} 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 {
|
||||
Card,
|
||||
CardContent,
|
||||
|
|
@ -20,21 +24,18 @@ import {
|
|||
CardTitle,
|
||||
} from "../components/ui/card";
|
||||
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 { changeTeamMemberPassword } from "../api/team.api";
|
||||
import { useTheme } from "../contexts/ThemeContext.shared";
|
||||
|
||||
import { notifyApiError } from "../lib/apiErrors";
|
||||
import { logoutToLogin } from "../lib/auth";
|
||||
import { getMyProfile } from "../api/users.api";
|
||||
import { cn } from "../lib/utils";
|
||||
import type { TeamMeProfile } from "../types/team.types";
|
||||
import { toast } from "sonner";
|
||||
import { RolesListPage } from "./role-management/RolesListPage";
|
||||
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
||||
import { ReferralsTab } from "./settings/ReferralsTab";
|
||||
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
||||
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 =
|
||||
| "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() {
|
||||
const { theme, setTheme, resolvedTheme, systemTheme } = useTheme();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,24 @@
|
|||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||
import { useEffect, useState, type ElementType, type ReactNode } from "react"
|
||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||
import {
|
||||
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 {
|
||||
Area,
|
||||
AreaChart,
|
||||
|
|
@ -14,70 +32,51 @@ import {
|
|||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
import alertSrc from "../../assets/Alert.svg"
|
||||
import {
|
||||
Users,
|
||||
BadgeCheck,
|
||||
DollarSign,
|
||||
BookOpen,
|
||||
HelpCircle,
|
||||
Bell,
|
||||
UsersRound,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
CreditCard,
|
||||
Video,
|
||||
FolderOpen,
|
||||
RefreshCw,
|
||||
ChevronDown,
|
||||
PlayCircle,
|
||||
RotateCcw,
|
||||
CheckCircle2,
|
||||
} from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
} from "recharts";
|
||||
import { getDashboard } from "../../api/analytics.api";
|
||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
||||
import alertSrc from "../../assets/Alert.svg";
|
||||
import { AnalyticsTimeRangeFilter } from "../../components/analytics/AnalyticsTimeRangeFilter";
|
||||
import { getDashboardFilterLabel } from "../../components/analytics/AnalyticsTimeRangeFilter.shared";
|
||||
|
||||
import { MonthlyRevenueBarChart, MonthlyRevenueTrendPanel, SensitiveYtdValue, analyticsSoftCardClass } from "../../components/analytics/SubscriptionRevenueVisuals";
|
||||
import { SUBSCRIPTION_CHART_COLORS } from "../../components/analytics/SubscriptionRevenueVisuals.shared";
|
||||
|
||||
import { Badge } from "../../components/ui/badge";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card";
|
||||
import {
|
||||
SensitiveChart,
|
||||
SensitiveRevealProvider,
|
||||
SensitiveValue,
|
||||
} 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"
|
||||
} from "../../components/ui/sensitive-value";
|
||||
import {
|
||||
aggregateRevenueByMonth,
|
||||
formatAnalyticsLabel,
|
||||
formatAnalyticsSeriesDate,
|
||||
formatPercentRate,
|
||||
formatRevenueAxisTick,
|
||||
getPrimaryQuestionTypeSummary,
|
||||
getSeriesPeriodLabel,
|
||||
formatAnalyticsLabel,
|
||||
getSubscriptionMetrics,
|
||||
getVideoLessonsSummary,
|
||||
formatPercentRate,
|
||||
formatAnalyticsSeriesDate,
|
||||
aggregateRevenueByMonth,
|
||||
formatRevenueAxisTick,
|
||||
} from "../../lib/analytics"
|
||||
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
|
||||
import { formatAppDateTime } from "../../lib/datetime"
|
||||
import { isUnassignedLabel } from "../../lib/displayValue"
|
||||
} from "../../lib/analytics";
|
||||
import { formatAppDateTime } from "../../lib/datetime";
|
||||
import { isUnassignedLabel } from "../../lib/displayValue.shared";
|
||||
|
||||
import {
|
||||
displayUserAgeGroup,
|
||||
displayUserCountry,
|
||||
displayUserEducationLevel,
|
||||
displayUserKnowledgeLevel,
|
||||
displayUserLanguageChallenge,
|
||||
displayUserLearningGoal,
|
||||
displayUserOccupation,
|
||||
displayUserRegion,
|
||||
displayUserEducationLevel,
|
||||
displayUserLearningGoal,
|
||||
displayUserLanguageChallenge,
|
||||
displayUserCountry,
|
||||
displayUserKnowledgeLevel,
|
||||
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
|
||||
|
||||
|
|
@ -158,14 +157,15 @@ function BreakdownList({
|
|||
title,
|
||||
data,
|
||||
total,
|
||||
scrollable: _scrollable,
|
||||
formatRowLabel,
|
||||
showPercent = true,
|
||||
}: {
|
||||
title: string
|
||||
data: LabelCount[]
|
||||
total?: number
|
||||
scrollable?: boolean
|
||||
formatRowLabel?: (label: string) => string
|
||||
showPercent?: boolean
|
||||
}) {
|
||||
const labelFn = formatRowLabel ?? formatAnalyticsLabel
|
||||
const merged = mergeAnalyticsRowsByDisplayLabel(data, labelFn).filter(
|
||||
|
|
@ -199,7 +199,7 @@ function BreakdownList({
|
|||
</div>
|
||||
<span className="font-semibold text-grayScale-700">
|
||||
{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>
|
||||
</div>
|
||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-grayScale-100">
|
||||
|
|
@ -639,7 +639,7 @@ export function AnalyticsPage() {
|
|||
formatRowLabel={displayUserLearningGoal}
|
||||
/>
|
||||
<BreakdownList
|
||||
title="Language challenge"
|
||||
title="Artistry challenge"
|
||||
data={users.by_language_challange ?? []}
|
||||
total={users.total_users}
|
||||
formatRowLabel={displayUserLanguageChallenge}
|
||||
|
|
@ -682,7 +682,7 @@ export function AnalyticsPage() {
|
|||
/>
|
||||
{(users.by_knowledge_level?.length ?? 0) > 0 ? (
|
||||
<BreakdownList
|
||||
title="Knowledge level"
|
||||
title="Makeup experience"
|
||||
data={users.by_knowledge_level ?? []}
|
||||
total={users.total_users}
|
||||
formatRowLabel={displayUserKnowledgeLevel}
|
||||
|
|
@ -703,7 +703,7 @@ export function AnalyticsPage() {
|
|||
scrollable
|
||||
/>
|
||||
<BreakdownList
|
||||
title="Language challenge"
|
||||
title="Artistry challenge"
|
||||
data={users.by_language_challange ?? []}
|
||||
total={users.total_users}
|
||||
formatRowLabel={displayUserLanguageChallenge}
|
||||
|
|
@ -778,10 +778,10 @@ export function AnalyticsPage() {
|
|||
ytdValue={<SensitiveYtdValue amount={payments.total_revenue} />}
|
||||
ytdLabel="Period total"
|
||||
>
|
||||
<MonthlyRevenueAreaChart
|
||||
<MonthlyRevenueBarChart
|
||||
data={monthlyRevenueTrendData}
|
||||
xKey={useMonthlyRevenueTrend ? "month" : "date"}
|
||||
gradientId="analyticsSubsRevenueFill"
|
||||
|
||||
height={260}
|
||||
yTickFormatter={formatRevenueAxisTick}
|
||||
/>
|
||||
|
|
@ -936,7 +936,8 @@ export function AnalyticsPage() {
|
|||
<div className="grid items-start gap-4 lg:grid-cols-2">
|
||||
{examPrep && (
|
||||
<BreakdownList
|
||||
title="Exam prep catalog"
|
||||
title="Makeup course catalog"
|
||||
showPercent={false}
|
||||
data={[
|
||||
{ label: "Catalog courses", count: examPrep.catalog_courses },
|
||||
{ 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 { 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 { Button } from "../../components/ui/button";
|
||||
|
|
@ -9,13 +10,13 @@ import { Label } from "../../components/ui/label";
|
|||
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 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 {
|
||||
interface Window {
|
||||
|
|
@ -126,9 +127,9 @@ export function LoginPage() {
|
|||
try {
|
||||
const result = await loginWithGoogle(response.credential);
|
||||
storeTokensAndRedirect(result);
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setError(
|
||||
err.response?.data?.message || "Google sign-in failed. Please try again."
|
||||
getApiErrorMessage(err, "Google sign-in failed. Please try again.")
|
||||
);
|
||||
} finally {
|
||||
setGoogleLoading(false);
|
||||
|
|
@ -209,8 +210,8 @@ export function LoginPage() {
|
|||
try {
|
||||
const res: LoginResult = await login(payload);
|
||||
storeTokensAndRedirect(res);
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || "Invalid email or password");
|
||||
} catch (err: unknown) {
|
||||
setError(getApiErrorMessage(err, "Invalid email or password"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
|
@ -233,36 +234,36 @@ export function LoginPage() {
|
|||
const googleClientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
|
||||
|
||||
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 */}
|
||||
<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 */}
|
||||
<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 -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>
|
||||
|
||||
<div className="relative z-10 max-w-lg px-12 text-left">
|
||||
{/* Brand logo */}
|
||||
<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>
|
||||
<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>
|
||||
<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">The art of beauty. The craft of teaching.</h2>
|
||||
<p className="mt-6 max-w-sm text-base leading-relaxed text-white/65">
|
||||
Manage your academy, track student progress, and streamline
|
||||
operations — all from one powerful dashboard.
|
||||
Nurture creative talent, curate makeup artistry lessons, and
|
||||
guide every student from first brushstroke to professional confidence.
|
||||
</p>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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="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="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-[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 */}
|
||||
<div className="mb-10 flex justify-center lg:hidden">
|
||||
<BrandLogo />
|
||||
|
|
@ -270,13 +271,13 @@ export function LoginPage() {
|
|||
|
||||
{/* Header */}
|
||||
<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
|
||||
</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
|
||||
</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
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -313,7 +314,7 @@ export function LoginPage() {
|
|||
type="button"
|
||||
onClick={handleGoogleClick}
|
||||
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 ? (
|
||||
<SpinnerIcon className="h-5 w-5" />
|
||||
|
|
@ -342,7 +343,7 @@ export function LoginPage() {
|
|||
<div>
|
||||
<Label
|
||||
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
|
||||
</Label>
|
||||
|
|
@ -369,13 +370,13 @@ export function LoginPage() {
|
|||
<div className="mb-1.5 flex items-center justify-between">
|
||||
<Label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-[#34443d]"
|
||||
className="block text-sm font-medium text-foreground"
|
||||
>
|
||||
Password
|
||||
</Label>
|
||||
<Link
|
||||
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?
|
||||
</Link>
|
||||
|
|
@ -410,7 +411,7 @@ export function LoginPage() {
|
|||
|
||||
<Button
|
||||
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}
|
||||
>
|
||||
{loading ? "Signing in…" : "Sign in"}
|
||||
|
|
@ -418,7 +419,7 @@ export function LoginPage() {
|
|||
</form>
|
||||
|
||||
{/* 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>
|
||||
</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 { 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 { Link, useLocation, useParams, useNavigate } from "react-router-dom";
|
||||
import { ArrowLeft, ArrowRight, ChevronDown, Grid3X3, Check, Plus, Trash2, GripVertical, Upload } from "lucide-react";
|
||||
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
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 {
|
||||
createQuestionSet,
|
||||
createQuestion,
|
||||
addQuestionToSet,
|
||||
createQuestion,
|
||||
createQuestionSet,
|
||||
} from "../../api/courses.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 { useActivePersonas } from "../../hooks/useActivePersonas";
|
||||
import { useVideoUpload } from "../../hooks/useVideoUpload";
|
||||
import { notifyApiError } from "../../lib/apiErrors";
|
||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video";
|
||||
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";
|
||||
|
||||
type Step = 1 | 2 | 3 | 4 | 5;
|
||||
|
|
|
|||
|
|
@ -1,43 +1,44 @@
|
|||
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||
import { navigateBack } from "../../lib/navigateBack";
|
||||
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 { Stepper } from "../../components/ui/stepper";
|
||||
import successIcon from "../../assets/success.svg";
|
||||
import type { PracticeParentKind } from "../../types/course.types";
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
||||
import { getQuestionTypeDefinitions } from "../../api/questionTypeDefinitions.api";
|
||||
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors";
|
||||
import { emptyDynamicFieldValuesForDefinition } from "../../lib/learnEnglishDefinitionQuestion";
|
||||
import {
|
||||
validateLearnEnglishQuestionsWithDefinitions,
|
||||
} from "../../lib/learnEnglishPracticePublish";
|
||||
import { navigateBack } from "../../lib/navigateBack";
|
||||
import { executePracticeCreation } from "../../lib/practiceCreationOrchestrator";
|
||||
import { syncStimulusBlocksAfterCreate } from "../../lib/practiceEditOrchestrator";
|
||||
import {
|
||||
isIeltsSharedStimulusMode,
|
||||
validatePracticeStimulusBlocks,
|
||||
} from "../../lib/practiceStimulusBlocks";
|
||||
import type { PracticeFormState } from "../../lib/practiceFullMapper";
|
||||
import {
|
||||
buildCreatePracticeParentsPayload,
|
||||
dedupeParents,
|
||||
formatPracticeParentsSummary,
|
||||
validatePracticeParents,
|
||||
} from "../../lib/practiceParents";
|
||||
import {
|
||||
isIeltsSharedStimulusMode,
|
||||
validatePracticeStimulusBlocks,
|
||||
} from "../../lib/practiceStimulusBlocks";
|
||||
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 { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
||||
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
||||
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||
import {
|
||||
personaFromId,
|
||||
personaIdNumber,
|
||||
} from "./components/practice-steps/constants";
|
||||
import { useActivePersonas } from "../../hooks/useActivePersonas";
|
||||
|
||||
const STEP_LABELS = ["Practice", "Persona", "Questions", "Review"] as const;
|
||||
|
||||
|
|
@ -137,6 +138,7 @@ export function AddPracticeFlow() {
|
|||
}, [
|
||||
lessonId,
|
||||
lessonTitleDisplay,
|
||||
isExamPrep,
|
||||
isModuleContext,
|
||||
isUnitContext,
|
||||
isCourseContext,
|
||||
|
|
@ -148,7 +150,7 @@ export function AddPracticeFlow() {
|
|||
const programLabel = isExamPrep
|
||||
? programType === "skill"
|
||||
? "Skill-Based Courses"
|
||||
: "Duolingo/IELTS"
|
||||
: "Makeup artistry"
|
||||
: level
|
||||
? `Program ${level}`
|
||||
: null;
|
||||
|
|
@ -252,7 +254,7 @@ export function AddPracticeFlow() {
|
|||
reload: reloadPersonas,
|
||||
} = useActivePersonas();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
const [formData, setFormData] = useState<PracticeFormState>({
|
||||
title: "",
|
||||
description: "",
|
||||
storyImageUrl: "",
|
||||
|
|
@ -629,7 +631,7 @@ export function AddPracticeFlow() {
|
|||
return (
|
||||
<ContextStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
onCancel={goBack}
|
||||
lessonTitle={lessonTitleDisplay}
|
||||
|
|
@ -653,7 +655,7 @@ export function AddPracticeFlow() {
|
|||
return (
|
||||
<QuestionsStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
prevStep={prevStep}
|
||||
typeDefinitions={typeDefinitions}
|
||||
|
|
@ -697,7 +699,7 @@ export function AddPracticeFlow() {
|
|||
return (
|
||||
<ScenarioStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
cancelHref={backPath}
|
||||
/>
|
||||
|
|
@ -719,7 +721,7 @@ export function AddPracticeFlow() {
|
|||
return (
|
||||
<QuestionsStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
prevStep={prevStep}
|
||||
typeDefinitions={typeDefinitions}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,20 @@
|
|||
import { notifyApiError } from "../../lib/apiErrors"
|
||||
import { ArrowLeft, Plus, X } from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useNavigate, useParams } from "react-router-dom"
|
||||
import { ArrowLeft, Plus, X } from "lucide-react"
|
||||
import { navigateBack } from "../../lib/navigateBack"
|
||||
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 {
|
||||
getQuestionTypeDefinitions,
|
||||
questionTypeDefinitionListLabel,
|
||||
} 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 Difficulty = "EASY" | "MEDIUM" | "HARD"
|
||||
|
|
@ -294,13 +294,10 @@ export function AddQuestionPage() {
|
|||
{ acceptable_answer: formData.correctAnswer.trim(), match_type: "CASE_INSENSITIVE" as const },
|
||||
]
|
||||
: undefined
|
||||
let dynamicPayload: { stimulus: unknown[]; response: unknown[] } | undefined
|
||||
let dynamicPayload: DynamicQuestionPayload | undefined
|
||||
if (formData.type === "DYNAMIC") {
|
||||
try {
|
||||
dynamicPayload = JSON.parse(formData.dynamicPayloadJson) as {
|
||||
stimulus: unknown[]
|
||||
response: unknown[]
|
||||
}
|
||||
dynamicPayload = JSON.parse(formData.dynamicPayloadJson) as DynamicQuestionPayload
|
||||
} catch {
|
||||
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 { useNavigate } from "react-router-dom"
|
||||
import { Search, Plus, RefreshCw, Edit2, ToggleLeft, ToggleRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { toast } from "sonner"
|
||||
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 { 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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog"
|
||||
import { FileUpload } from "../../components/ui/file-upload"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import {
|
||||
|
|
@ -15,26 +29,13 @@ import {
|
|||
TableHeader,
|
||||
TableRow,
|
||||
} 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 { toast } from "sonner"
|
||||
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 spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png"
|
||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { Course, CourseCategory } from "../../types/course.types"
|
||||
|
||||
type CourseWithCategory = Course & { category_name: string }
|
||||
|
||||
|
|
@ -54,7 +55,7 @@ export function AllCoursesPage() {
|
|||
const [createTitle, setCreateTitle] = useState("")
|
||||
const [createDescription, setCreateDescription] = useState("")
|
||||
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 [togglingId, setTogglingId] = useState<number | null>(null)
|
||||
const [editOpen, setEditOpen] = useState(false)
|
||||
|
|
@ -147,14 +148,9 @@ export function AllCoursesPage() {
|
|||
description: createDescription.trim(),
|
||||
})
|
||||
|
||||
const createdIdRaw =
|
||||
(createdRes.data?.data as any)?.id ??
|
||||
(createdRes.data?.data as any)?.course?.id ??
|
||||
(createdRes.data?.data as any)?.data?.id
|
||||
const createdId = readCreatedEntityId(createdRes.data, "course")
|
||||
|
||||
const createdId = Number(createdIdRaw)
|
||||
|
||||
if (createThumbnail && Number.isFinite(createdId)) {
|
||||
if (createThumbnail && createdId != null) {
|
||||
const uploadRes = await uploadImageFile(createThumbnail)
|
||||
const thumbnailUrl = uploadRes.data?.data?.url?.trim()
|
||||
if (thumbnailUrl) {
|
||||
|
|
@ -174,7 +170,7 @@ export function AllCoursesPage() {
|
|||
setCreateThumbnail(null)
|
||||
setCreateVideo(null)
|
||||
await fetchAllCourses()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
console.error("Failed to create course:", err)
|
||||
notifyApiError(err, "Failed to create sub-category")
|
||||
} finally {
|
||||
|
|
@ -221,7 +217,7 @@ export function AllCoursesPage() {
|
|||
setEditOpen(false)
|
||||
setCourseToEdit(null)
|
||||
await fetchAllCourses()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
console.error("Failed to update course:", err)
|
||||
notifyApiError(err, "Failed to update sub-category")
|
||||
} finally {
|
||||
|
|
@ -560,7 +556,7 @@ export function AllCoursesPage() {
|
|||
Sub-category title
|
||||
</label>
|
||||
<Input
|
||||
placeholder="e.g. Beginner English A1"
|
||||
placeholder="e.g. Makeup Artistry Foundations"
|
||||
value={createTitle}
|
||||
onChange={(e) => setCreateTitle(e.target.value)}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { ArrowLeft, Check, Clock } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
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 { 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 { AttachPracticeStep1 } from "./components/practice-steps/AttachPracticeStep1";
|
||||
|
||||
export function AttachPracticeFlow() {
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -25,9 +25,9 @@ export function AttachPracticeFlow() {
|
|||
program:
|
||||
programType === "skill"
|
||||
? "Skill-Based Courses"
|
||||
: "Duolingo/IELTS",
|
||||
module: "Module 4: Interactive Speaking",
|
||||
video: "Intro to Interactive Speaking",
|
||||
: "Makeup artistry",
|
||||
module: "Module 4: Consultation practice",
|
||||
video: "Introduction to bridal consultation",
|
||||
questionType: "speaking",
|
||||
version: "v1",
|
||||
});
|
||||
|
|
@ -71,7 +71,7 @@ export function AttachPracticeFlow() {
|
|||
</div>
|
||||
<div className="text-left space-y-1.5">
|
||||
<h4 className="text-[14px] font-medium text-grayScale-900">
|
||||
Intro to IELTS Speaking Part 1
|
||||
Introduction to bridal consultation
|
||||
</h4>
|
||||
<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">
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { ArrowLeft } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
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 { 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 { ProgramAttachStep1 } from "./components/practice-steps/ProgramAttachStep1";
|
||||
|
||||
export function AttachProgramPracticeFlow() {
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -17,7 +17,7 @@ export function AttachProgramPracticeFlow() {
|
|||
const [isPublished, setIsPublished] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
program: "Duolingo/IELTS",
|
||||
program: "Makeup artistry",
|
||||
test: "Mock Exam 1",
|
||||
questionType: "Speaking Practice",
|
||||
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 { 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 type { CourseCategory } from "../../types/course.types"
|
||||
import { cn } from "../../lib/utils"
|
||||
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 = [
|
||||
{
|
||||
|
|
@ -65,17 +64,49 @@ type ContentSection = (typeof contentSections)[number]
|
|||
export function ContentOverviewPage() {
|
||||
const { categoryId } = useParams<{ categoryId: string }>()
|
||||
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 [dragKey, setDragKey] = useState<string | null>(null)
|
||||
const [flowSteps, setFlowSteps] = useState<
|
||||
const flowSteps = useMemo<
|
||||
{
|
||||
id: string
|
||||
type: "lesson" | "practice" | "exam" | "feedback" | "course" | "speaking" | "new_course"
|
||||
title: 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(() => {
|
||||
const fetchCategory = async () => {
|
||||
|
|
@ -93,55 +124,6 @@ export function ContentOverviewPage() {
|
|||
}
|
||||
}, [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
|
||||
useEffect(() => {
|
||||
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 { 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 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 { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
|
|
@ -16,10 +16,11 @@ import {
|
|||
DialogHeader,
|
||||
DialogTitle,
|
||||
} 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 { toast } from "sonner"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
|
||||
export function CourseCategoryPage() {
|
||||
const [categories, setCategories] = useState<CourseCategory[]>([])
|
||||
|
|
@ -216,7 +217,7 @@ export function CourseCategoryPage() {
|
|||
Category name
|
||||
</label>
|
||||
<Input
|
||||
placeholder="e.g. Beginner English, Duolingo/IELTS"
|
||||
placeholder="e.g. Makeup Foundations, Bridal Artistry"
|
||||
value={newCategoryName}
|
||||
onChange={(e) => setNewCategoryName(e.target.value)}
|
||||
/>
|
||||
|
|
@ -337,19 +338,7 @@ export function CourseCategoryPage() {
|
|||
try {
|
||||
const name = newCategoryName.trim()
|
||||
const parentRes = await createCourseCategory({ name })
|
||||
let createdCategoryId: number | null = null
|
||||
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
|
||||
}
|
||||
const createdCategoryId = readCreatedEntityId(parentRes.data, "category")
|
||||
|
||||
if (createdCategoryId && pendingSubCategories.length > 0) {
|
||||
await Promise.all(
|
||||
|
|
|
|||
|
|
@ -1,18 +1,32 @@
|
|||
import { notifyApiError } from "../../lib/apiErrors"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Calendar,
|
||||
Layers,
|
||||
Pencil,
|
||||
Plus,
|
||||
Trash2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
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 { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { Card } from "../../components/ui/card";
|
||||
import {
|
||||
Dialog,
|
||||
|
|
@ -24,58 +38,44 @@ import {
|
|||
} from "../../components/ui/dialog";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import { Textarea } from "../../components/ui/textarea";
|
||||
import { cn } from "../../lib/utils";
|
||||
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 { notifyApiError } from "../../lib/apiErrors";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
type PublishStatusFilter,
|
||||
} from "../../lib/contentListFilters";
|
||||
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||
import { DisplayValue } from "../../lib/displayValue";
|
||||
import {
|
||||
fetchAllOffsetPages,
|
||||
offsetPageFromListEnvelope,
|
||||
} from "../../lib/fetchAllOffsetPages";
|
||||
import { AddModuleModal } from "./components/AddModuleModal";
|
||||
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 { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||
import {
|
||||
hasCourseDirectPracticeLink,
|
||||
isPracticeParentUnlinkNotLinkedError,
|
||||
listCourseContextUnlinkParents,
|
||||
practiceUnlinkBlockedMessage,
|
||||
unlinkPracticeFromParent,
|
||||
} from "../../lib/practiceParentUnlink"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
} from "../../lib/practiceParentUnlink";
|
||||
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;
|
||||
|
||||
|
|
@ -317,7 +317,7 @@ export function CourseDetailPage() {
|
|||
} else {
|
||||
console.error(modulesOutcome.reason);
|
||||
setModules([]);
|
||||
notifyApiError(err, "Could not load modules");
|
||||
notifyApiError(modulesOutcome.reason, "Could not load modules");
|
||||
}
|
||||
} catch (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 {
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
|
|
@ -25,23 +16,34 @@ import {
|
|||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { PageBackLink } from "../../components/navigation/PageBackLink"
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
GripVertical,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
} from "lucide-react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
getCourseCategories,
|
||||
getCoursesByCategory,
|
||||
getQuestionSetsByOwner,
|
||||
getSubModulesByCourse,
|
||||
getVideosBySubModule,
|
||||
getQuestionSetsByOwner,
|
||||
reorderCategories,
|
||||
reorderCourses,
|
||||
reorderPractices,
|
||||
reorderSubModules,
|
||||
reorderVideos,
|
||||
reorderPractices,
|
||||
} 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 {
|
||||
Course,
|
||||
CourseCategory,
|
||||
|
|
@ -51,9 +53,6 @@ import type {
|
|||
QuestionSet,
|
||||
ReorderItem,
|
||||
} 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 }
|
||||
|
||||
|
|
@ -67,7 +66,7 @@ function mapPracticeSetsToPracticeItems(sets: QuestionSet[]): PracticeListItem[]
|
|||
status: set.status,
|
||||
question_count: 0,
|
||||
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
|
||||
}
|
||||
|
||||
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[]) {
|
||||
return [...items].sort((a, b) => {
|
||||
const ao = typeof (a as any).display_order === "number" ? (a as any).display_order : 0
|
||||
const bo = typeof (b as any).display_order === "number" ? (b as any).display_order : 0
|
||||
const ao = readDisplayOrder(a) ?? 0
|
||||
const bo = readDisplayOrder(b) ?? 0
|
||||
if (ao === bo) return a.id - b.id
|
||||
return ao - bo
|
||||
})
|
||||
|
|
@ -211,7 +216,7 @@ export function CourseFlowBuilderPage() {
|
|||
)
|
||||
|
||||
const topLevelCategories = useMemo(
|
||||
() => sortByDisplayOrder(categories.filter((c) => normalizeParentId(c.parent_id as any) === null)),
|
||||
() => sortByDisplayOrder(categories.filter((c) => normalizeParentId(c.parent_id) === null)),
|
||||
[categories],
|
||||
)
|
||||
|
||||
|
|
@ -227,7 +232,7 @@ export function CourseFlowBuilderPage() {
|
|||
const res = await getCourseCategories()
|
||||
const all = sortByDisplayOrder(res.data.data.categories ?? [])
|
||||
setCategories(all)
|
||||
} catch {
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to load course categories.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
|
|
@ -264,7 +269,7 @@ export function CourseFlowBuilderPage() {
|
|||
)
|
||||
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: items }))
|
||||
setSelectedCourseId(items[0]?.id ?? null)
|
||||
} catch {
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to load course sub-categories.")
|
||||
} finally {
|
||||
setLoadingCourses(false)
|
||||
|
|
@ -283,7 +288,7 @@ export function CourseFlowBuilderPage() {
|
|||
try {
|
||||
const selectedCourse = activeCourses.find((course) => course.id === 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,
|
||||
title: sc.title,
|
||||
description: sc.description ?? "",
|
||||
|
|
@ -328,7 +333,7 @@ export function CourseFlowBuilderPage() {
|
|||
const videosRes = await getVideosBySubModule(sc.id)
|
||||
const rows = videosRes.data?.data?.videos ?? []
|
||||
const mapped = sortByDisplayOrder(
|
||||
rows.map((video: any, idx: number) => ({
|
||||
rows.map((video, idx) => ({
|
||||
id: Number(video.id),
|
||||
title: String(video.title ?? "Video"),
|
||||
display_order: Number(video.display_order ?? idx),
|
||||
|
|
@ -352,7 +357,7 @@ export function CourseFlowBuilderPage() {
|
|||
videoMap[subCourseId] = videos
|
||||
})
|
||||
setVideosBySubCourse(videoMap)
|
||||
} catch {
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to load course flow detail.")
|
||||
setLearningPath(null)
|
||||
} finally {
|
||||
|
|
@ -390,7 +395,7 @@ export function CourseFlowBuilderPage() {
|
|||
const videos =
|
||||
videosRes.status === "fulfilled"
|
||||
? sortByDisplayOrder(
|
||||
(videosRes.value.data?.data?.videos ?? []).map((video: any, idx: number) => ({
|
||||
(videosRes.value.data?.data?.videos ?? []).map((video, idx) => ({
|
||||
id: Number(video.id),
|
||||
title: String(video.title ?? "Video"),
|
||||
display_order: Number(video.display_order ?? idx),
|
||||
|
|
@ -403,7 +408,7 @@ export function CourseFlowBuilderPage() {
|
|||
...prev,
|
||||
[subCourseId]: videos,
|
||||
}))
|
||||
} catch {
|
||||
} catch (err) {
|
||||
notifyApiError(err, "Failed to load practice sets for course.")
|
||||
} finally {
|
||||
setLoadingPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: false }))
|
||||
|
|
@ -429,7 +434,7 @@ export function CourseFlowBuilderPage() {
|
|||
setSavingKey("categories")
|
||||
try {
|
||||
await reorderCategories(toReorderItems(reordered))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setCategories(previous)
|
||||
notifyApiError(err, "Failed to reorder categories.")
|
||||
} finally {
|
||||
|
|
@ -455,7 +460,7 @@ export function CourseFlowBuilderPage() {
|
|||
setSavingKey("courses")
|
||||
try {
|
||||
await reorderCourses(toReorderItems(reordered))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setCoursesByCategory((prev) => ({ ...prev, [selectedCategoryId]: previous }))
|
||||
notifyApiError(err, "Failed to reorder courses.")
|
||||
} finally {
|
||||
|
|
@ -481,7 +486,7 @@ export function CourseFlowBuilderPage() {
|
|||
setSavingKey("sub-modules")
|
||||
try {
|
||||
await reorderSubModules(toReorderItems(reordered))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setLearningPath((prev) => (prev ? { ...prev, sub_courses: previous } : prev))
|
||||
notifyApiError(err, "Failed to reorder sub-modules.")
|
||||
} finally {
|
||||
|
|
@ -517,7 +522,7 @@ export function CourseFlowBuilderPage() {
|
|||
setSavingKey(`videos-${subCourseId}`)
|
||||
try {
|
||||
await reorderVideos(toReorderItems(reordered))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setLearningPath((prev) =>
|
||||
prev
|
||||
? {
|
||||
|
|
@ -552,7 +557,7 @@ export function CourseFlowBuilderPage() {
|
|||
setSavingKey(`practices-${subCourseId}`)
|
||||
try {
|
||||
await reorderPractices(toReorderItems(reordered))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
setPracticesBySubCourse((prev) => ({ ...prev, [subCourseId]: previous }))
|
||||
notifyApiError(err, "Failed to reorder practices.")
|
||||
} 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 {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
LayoutGrid,
|
||||
PlayCircle,
|
||||
ClipboardCheck,
|
||||
Pencil,
|
||||
Trash2,
|
||||
ChevronRight,
|
||||
ArrowRight,
|
||||
X,
|
||||
ClipboardCheck,
|
||||
FileText,
|
||||
LayoutGrid,
|
||||
Pencil,
|
||||
PlayCircle,
|
||||
Plus,
|
||||
Trash2
|
||||
} from "lucide-react";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Card } from "../../components/ui/card";
|
||||
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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||
import {
|
||||
createExamPrepCatalogUnit,
|
||||
deleteExamPrepCatalogUnit,
|
||||
getExamPrepCatalogCourses,
|
||||
getExamPrepCatalogUnits,
|
||||
setExamPrepCatalogCoursePublishStatus,
|
||||
setExamPrepCatalogUnitAccessTier,
|
||||
setExamPrepCatalogUnitPublishStatus,
|
||||
updateExamPrepCatalogUnit,
|
||||
deleteExamPrepCatalogUnit,
|
||||
getExamPrepCatalogUnits,
|
||||
} from "../../api/courses.api";
|
||||
import { uploadImageFile } from "../../api/files.api";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import uploadIcon from "../../assets/icons/upload.png";
|
||||
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||
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 { 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 {
|
||||
ContentAccessTier,
|
||||
ExamPrepCatalogCourseItem,
|
||||
ExamPrepCatalogUnitItem,
|
||||
PracticePublishStatus,
|
||||
} from "../../types/course.types";
|
||||
import { DisplayValue } from "../../lib/displayValue"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
import {
|
||||
fetchAllOffsetPages,
|
||||
offsetPageFromListEnvelope,
|
||||
} from "../../lib/fetchAllOffsetPages";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
type PublishStatusFilter,
|
||||
} from "../../lib/contentListFilters";
|
||||
import { CatalogCoursePracticesPanel } from "./components/CatalogCoursePracticesPanel";
|
||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
|
||||
export function CourseManagementPage() {
|
||||
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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
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 { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||
import { VideoCard } from "./components/VideoCard";
|
||||
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
||||
import {
|
||||
createExamPrepModuleLesson,
|
||||
updateExamPrepModuleLesson,
|
||||
deleteExamPrepModuleLesson,
|
||||
getExamPrepModuleLessons,
|
||||
getExamPrepUnitModules,
|
||||
setExamPrepModuleLessonAccessTier,
|
||||
setExamPrepModuleLessonPublishStatus,
|
||||
setExamPrepUnitModulePublishStatus,
|
||||
updateExamPrepModuleLesson,
|
||||
} from "../../api/courses.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 { 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 { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
||||
import type {
|
||||
|
|
@ -49,15 +53,9 @@ import type {
|
|||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
import { DisplayValue } from "../../lib/displayValue"
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
type PublishStatusFilter,
|
||||
} from "../../lib/contentListFilters";
|
||||
import {
|
||||
fetchAllOffsetPages,
|
||||
offsetPageFromListEnvelope,
|
||||
} from "../../lib/fetchAllOffsetPages";
|
||||
import { ExamPrepAssessmentsPanel } from "./components/ExamPrepAssessmentsPanel";
|
||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||
import { VideoCard } from "./components/VideoCard";
|
||||
|
||||
const LESSON_THUMB_GRADIENTS = [
|
||||
"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 {
|
||||
Plus,
|
||||
ArrowLeft,
|
||||
ToggleLeft,
|
||||
ToggleRight,
|
||||
X,
|
||||
Trash2,
|
||||
Edit,
|
||||
AlertCircle,
|
||||
ArrowLeft,
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Search,
|
||||
BookOpen,
|
||||
Edit,
|
||||
Eye,
|
||||
Plus,
|
||||
Search,
|
||||
ToggleLeft,
|
||||
ToggleRight,
|
||||
Trash2,
|
||||
X,
|
||||
} 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 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 { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import {
|
||||
Table,
|
||||
|
|
@ -31,18 +38,11 @@ import {
|
|||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../components/ui/table"
|
||||
import {
|
||||
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 { getApiErrorMessage } from "../../lib/apiErrors"
|
||||
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() {
|
||||
const { categoryId } = useParams<{ categoryId: string }>()
|
||||
|
|
@ -151,7 +151,7 @@ export function CoursesPage() {
|
|||
})
|
||||
handleCloseModal()
|
||||
await fetchSubCategories()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
console.error("Failed to create course:", err)
|
||||
setSaveError(getApiErrorMessage(err, "Failed to create sub-category"))
|
||||
} finally {
|
||||
|
|
@ -231,7 +231,7 @@ export function CoursesPage() {
|
|||
|
||||
handleCloseEditModal()
|
||||
await fetchSubCategories()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
console.error("Failed to update course:", err)
|
||||
setUpdateError(getApiErrorMessage(err, "Failed to update sub-category"))
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -1,52 +1,53 @@
|
|||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||
import { getApiErrorMessage, notifyApiError } from "../../lib/apiErrors"
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
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 { Button } from "../../components/ui/button";
|
||||
import { Stepper } from "../../components/ui/stepper";
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types";
|
||||
import {
|
||||
getExamPrepPracticeFull,
|
||||
getLearnEnglishPracticeFull,
|
||||
} from "../../api/courses.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 {
|
||||
validateLearnEnglishQuestionsWithDefinitions,
|
||||
} from "../../lib/learnEnglishPracticePublish";
|
||||
import { navigateBack } from "../../lib/navigateBack";
|
||||
import {
|
||||
buildPracticeEditSnapshot,
|
||||
hasPracticeEditChanges,
|
||||
} from "../../lib/practiceEditDirty";
|
||||
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 {
|
||||
mapPracticeFullToFormState,
|
||||
unwrapPracticeFullData,
|
||||
type PreservedQuestionSetFields,
|
||||
} from "../../lib/practiceFullMapper";
|
||||
import {
|
||||
buildPracticeEditSnapshot,
|
||||
hasPracticeEditChanges,
|
||||
} from "../../lib/practiceEditDirty";
|
||||
dedupeParents,
|
||||
formatPracticeParentsSummary,
|
||||
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 { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||
import { PersonaStep } from "./components/practice-steps/PersonaStep";
|
||||
import { QuestionsStep } from "./components/practice-steps/QuestionsStep";
|
||||
import { ReviewStep } from "./components/practice-steps/ReviewStep";
|
||||
import { ScenarioStep } from "./components/practice-steps/ScenarioStep";
|
||||
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;
|
||||
|
||||
|
|
@ -150,6 +151,7 @@ export function EditPracticeFlow() {
|
|||
}, [
|
||||
lessonId,
|
||||
lessonTitleDisplay,
|
||||
isExamPrep,
|
||||
isModuleContext,
|
||||
isUnitContext,
|
||||
isCourseContext,
|
||||
|
|
@ -161,7 +163,7 @@ export function EditPracticeFlow() {
|
|||
const programLabel = isExamPrep
|
||||
? programType === "skill"
|
||||
? "Skill-Based Courses"
|
||||
: "Duolingo/IELTS"
|
||||
: "Makeup artistry"
|
||||
: level
|
||||
? `Program ${level}`
|
||||
: null;
|
||||
|
|
@ -263,7 +265,7 @@ export function EditPracticeFlow() {
|
|||
reload: reloadPersonas,
|
||||
} = useActivePersonas({ ensurePersonaId: loadedPersonaId });
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
const [formData, setFormData] = useState<PracticeFormState>({
|
||||
title: "",
|
||||
description: "",
|
||||
storyImageUrl: "",
|
||||
|
|
@ -621,7 +623,7 @@ export function EditPracticeFlow() {
|
|||
return (
|
||||
<ContextStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
onCancel={() => goBack()}
|
||||
lessonTitle={lessonTitleDisplay}
|
||||
|
|
@ -661,7 +663,7 @@ export function EditPracticeFlow() {
|
|||
return (
|
||||
<QuestionsStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
prevStep={prevStep}
|
||||
typeDefinitions={typeDefinitions}
|
||||
|
|
@ -703,7 +705,7 @@ export function EditPracticeFlow() {
|
|||
return (
|
||||
<ScenarioStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
cancelHref={backPath}
|
||||
/>
|
||||
|
|
@ -725,7 +727,7 @@ export function EditPracticeFlow() {
|
|||
return (
|
||||
<QuestionsStep
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
setFormData={(changes) => setFormData((previous) => ({ ...previous, ...changes }))}
|
||||
nextStep={nextStep}
|
||||
prevStep={prevStep}
|
||||
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 { Link } from "react-router-dom"
|
||||
import { BookOpen, ChevronDown, ChevronRight, FolderTree, Languages, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
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 {
|
||||
createModule,
|
||||
deleteModule,
|
||||
|
|
@ -21,7 +11,17 @@ import {
|
|||
updateModule,
|
||||
} from "../../api/courses.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 { notifyApiError } from "../../lib/apiErrors"
|
||||
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
||||
|
||||
type IdFilterValue = number | "ALL"
|
||||
|
|
@ -270,10 +270,6 @@ export function HumanLanguageHierarchyPage() {
|
|||
() => (selectedSubCategoryId === "ALL" ? [] : toCourseOptions(hierarchyRows, selectedSubCategoryId)),
|
||||
[hierarchyRows, selectedSubCategoryId],
|
||||
)
|
||||
const selectedCourse = useMemo(
|
||||
() => (selectedCourseId === "ALL" ? null : courseOptions.find((item) => item.id === selectedCourseId) ?? null),
|
||||
[selectedCourseId, courseOptions],
|
||||
)
|
||||
|
||||
const targetCourseIds = useMemo(() => {
|
||||
if (selectedSubCategoryId === "ALL") return []
|
||||
|
|
@ -300,12 +296,23 @@ export function HumanLanguageHierarchyPage() {
|
|||
setHierarchyError(null)
|
||||
try {
|
||||
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) {
|
||||
console.error(err)
|
||||
setHierarchyRows([])
|
||||
setHierarchyError("Could not load Human Language hierarchy")
|
||||
notifyApiError(err, "Failed to load Human Language hierarchy")
|
||||
setHierarchyError("Could not load academy hierarchy")
|
||||
notifyApiError(err, "Failed to load academy hierarchy")
|
||||
} finally {
|
||||
setHierarchyLoading(false)
|
||||
}
|
||||
|
|
@ -675,7 +682,7 @@ export function HumanLanguageHierarchyPage() {
|
|||
<Languages className="h-5 w-5" aria-hidden />
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -379,7 +379,7 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
const courseStructurePath = `/content/category/${categoryId}/courses/${courseId}/sub-modules`
|
||||
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) => {
|
||||
navigate(`${basePath}/practices/${questionSetId}/questions`)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
CheckCircle2,
|
||||
ClipboardList,
|
||||
|
|
@ -11,7 +10,9 @@ import {
|
|||
Trash2,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { updateQuestion } from "../../api/courses.api"
|
||||
import {
|
||||
createAndAttachPlacementQuestion,
|
||||
detachPlacementQuestion,
|
||||
|
|
@ -23,10 +24,6 @@ import {
|
|||
type PlacementQuestionDetail,
|
||||
type PlacementQuestionRow,
|
||||
} from "../../api/initial-assessment.api"
|
||||
import { updateQuestion } from "../../api/courses.api"
|
||||
import { notifyApiError } from "../../lib/apiErrors"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
||||
import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab"
|
||||
import { TablePagination } from "../../components/admin/TablePagination"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
|
|
@ -45,9 +42,12 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
|||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||
import { Textarea } from "../../components/ui/textarea"
|
||||
import { ToggleSwitch } from "../../components/ui/toggle-switch"
|
||||
import { notifyApiError } from "../../lib/apiErrors"
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { QuestionSetDetail } from "../../types/course.types"
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab"
|
||||
|
||||
type TabId = "set" | "questions" | "thresholds"
|
||||
type DraftQuestionType = "MCQ" | "TRUE_FALSE"
|
||||
|
|
@ -204,7 +204,7 @@ export function InitialAssessmentPage() {
|
|||
const [pendingDelete, setPendingDelete] = useState<PlacementQuestionRow | null>(null)
|
||||
const [statusUpdatingId, setStatusUpdatingId] = useState<number | null>(null)
|
||||
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 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>
|
||||
<h1 className="text-2xl font-bold tracking-tight text-grayScale-700">
|
||||
Learn English
|
||||
Academy Content
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
Manage learning content by program
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
|
|
@ -12,20 +11,7 @@ import {
|
|||
setExamPrepPracticePublishStatus,
|
||||
setLearnEnglishPracticePublishStatus,
|
||||
} 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 { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
|
|
@ -33,6 +19,24 @@ import {
|
|||
DialogHeader,
|
||||
DialogTitle,
|
||||
} 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 {
|
||||
ExamPrepLessonPractice,
|
||||
GetExamPrepLessonPracticesResponse,
|
||||
|
|
@ -41,13 +45,8 @@ import type {
|
|||
} from "../../types/course.types";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
type PublishStatusFilter,
|
||||
} from "../../lib/contentListFilters";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages";
|
||||
import { unwrapPracticesPage } from "../../lib/parentContextPractice";
|
||||
import { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { PracticeSelectableGrid } from "./components/PracticeSelectableGrid";
|
||||
|
||||
function unwrapExamPrepPracticesEnvelope(
|
||||
res: { data?: GetExamPrepLessonPracticesResponse & { Data?: GetExamPrepLessonPracticesResponse["data"] } },
|
||||
|
|
@ -495,8 +494,8 @@ export function LessonPracticesPage() {
|
|||
parentsFromPractice(practiceToUnlink).filter(
|
||||
(p) =>
|
||||
!(
|
||||
p.parent_kind === lessonParent.parent_kind &&
|
||||
p.parent_id === lessonParent.parent_id
|
||||
p.parent_kind === "LESSON" &&
|
||||
p.parent_id === lid
|
||||
),
|
||||
).length === 0
|
||||
? " 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 { ArrowLeft, Video, Calendar, Trash2, X } from "lucide-react";
|
||||
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
|
|
@ -14,31 +13,7 @@ import {
|
|||
setTopLevelModuleLessonAccessTier,
|
||||
updateTopLevelModuleLesson,
|
||||
} 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 { PracticeActionButton } from "./components/PracticeActionButton";
|
||||
import { PracticeActionChoiceDialog } from "./components/PracticeActionChoiceDialog";
|
||||
import { buildPracticeContentPaths, type PracticeContentPathOptions } from "../../lib/practiceContentPaths";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
|
|
@ -49,18 +24,43 @@ import {
|
|||
} from "../../components/ui/dialog";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import { Textarea } from "../../components/ui/textarea";
|
||||
import { resolveThumbnailForPreview } from "../../lib/videoPreview";
|
||||
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 { notifyApiError } from "../../lib/apiErrors";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
type PublishStatusFilter,
|
||||
} 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 = [
|
||||
"from-[#D4D4D8] to-[#71717A]",
|
||||
|
|
@ -263,7 +263,7 @@ export function ModuleDetailPage() {
|
|||
if (showPageLoading) {
|
||||
setLessonsLoadError(null);
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (showPageLoading) {
|
||||
setLessons([]);
|
||||
setLessonsLoadError("Failed to load lessons. Please try again.");
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export function NewContentPage() {
|
|||
Learning Content
|
||||
</h1>
|
||||
<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.
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -39,11 +39,11 @@ export function NewContentPage() {
|
|||
</div>
|
||||
<CardContent className="flex flex-col justify-center p-8">
|
||||
<h2 className="text-xl font-bold text-grayScale-800">
|
||||
Exam prep catalog
|
||||
Makeup course catalog
|
||||
</h2>
|
||||
<p className="mt-2 max-w-2xl text-sm leading-relaxed text-grayScale-500">
|
||||
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
|
||||
where they belong.
|
||||
</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 { Plus, Pencil, Trash2, X } from "lucide-react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { PageBackLink } from "../../components/navigation/PageBackLink";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
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 {
|
||||
createProgramCourse,
|
||||
deleteTopLevelCourse,
|
||||
|
|
@ -29,29 +11,46 @@ import {
|
|||
setProgramCoursePublishStatus,
|
||||
updateTopLevelCourse,
|
||||
} from "../../api/courses.api";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import { uploadImageFile } from "../../api/files.api";
|
||||
import spinnerSrc from "../../assets/05d37a91-04f9-41d8-99a2-b11bf20a6af2.png";
|
||||
import alertSrc from "../../assets/Alert.svg";
|
||||
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 {
|
||||
filterBySearchAndPublishStatus,
|
||||
hasActiveContentFilters,
|
||||
type PublishStatusFilter,
|
||||
type PublishStatusFilter
|
||||
} from "../../lib/contentListFilters";
|
||||
import { uploadImageFile } from "../../api/files.api";
|
||||
import { DisplayValue } from "../../lib/displayValue";
|
||||
import {
|
||||
fetchAllOffsetPages,
|
||||
offsetPageFromListEnvelope,
|
||||
} from "../../lib/fetchAllOffsetPages";
|
||||
import type {
|
||||
ContentAccessTier,
|
||||
LearningProgramListItem,
|
||||
PracticePublishStatus,
|
||||
ProgramCourseListItem,
|
||||
} 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 { DisplayValue } from "../../lib/displayValue"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
import {
|
||||
fetchAllOffsetPages,
|
||||
offsetPageFromListEnvelope,
|
||||
} from "../../lib/fetchAllOffsetPages";
|
||||
|
||||
export function ProgramCoursesPage() {
|
||||
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 {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
ListChecks,
|
||||
ChevronRight,
|
||||
Pencil,
|
||||
Trash2,
|
||||
X,
|
||||
Plus,
|
||||
Trash2
|
||||
} from "lucide-react";
|
||||
import { Button } from "../../components/ui/button";
|
||||
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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Link, useNavigate, useParams } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import { ResolvedImage } from "../../components/media/ResolvedImage";
|
||||
import {
|
||||
createExamPrepCatalogCourse,
|
||||
deleteExamPrepCatalogCourse,
|
||||
|
|
@ -33,29 +18,43 @@ import {
|
|||
setExamPrepCatalogCoursePublishStatus,
|
||||
updateExamPrepCatalogCourse,
|
||||
} from "../../api/courses.api";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import { uploadImageFile } from "../../api/files.api";
|
||||
import uploadIcon from "../../assets/icons/upload.png";
|
||||
import { SearchHighlight } from "../../components/SearchHighlight";
|
||||
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 {
|
||||
ContentAccessTier,
|
||||
ExamPrepCatalogCategory,
|
||||
ExamPrepCatalogCourseItem,
|
||||
PracticePublishStatus,
|
||||
} from "../../types/course.types";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
hasActiveContentFilters,
|
||||
type PublishStatusFilter,
|
||||
} 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";
|
||||
import { ContentAccessTierChip } from "./components/ContentAccessTierChip";
|
||||
import { ContentListSearchFilterBar } from "./components/ContentListSearchFilterBar";
|
||||
import { ContentPageDescription } from "./components/ContentPageDescription";
|
||||
import { ContentPublishStatusChip } from "./components/ContentPublishStatusChip";
|
||||
|
||||
type CourseListRow = {
|
||||
id: number;
|
||||
|
|
@ -109,9 +108,9 @@ export function ProgramDetailPage() {
|
|||
const [deletingCourse, setDeletingCourse] = useState(false);
|
||||
|
||||
const categoryLabels: Record<ExamPrepCatalogCategory, string> = {
|
||||
EDUCATION: "Education",
|
||||
IELTS: "IELTS",
|
||||
DUOLINGO: "Duolingo English Test",
|
||||
EDUCATION: "Makeup Artistry",
|
||||
IELTS: "Legacy: IELTS",
|
||||
DUOLINGO: "Legacy: Duolingo English Test",
|
||||
};
|
||||
const currentProgram = category
|
||||
? {
|
||||
|
|
@ -563,7 +562,7 @@ export function ProgramDetailPage() {
|
|||
<Input
|
||||
value={createName}
|
||||
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"
|
||||
disabled={creating}
|
||||
/>
|
||||
|
|
@ -724,7 +723,7 @@ export function ProgramDetailPage() {
|
|||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
filteredCourses.map((course: any) => (
|
||||
filteredCourses.map((course) => (
|
||||
<Card
|
||||
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"
|
||||
|
|
@ -790,7 +789,7 @@ export function ProgramDetailPage() {
|
|||
</div>
|
||||
{isExamPrepCatalog && course.category ? (
|
||||
<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>
|
||||
) : null}
|
||||
<h3 className="text-[18px] font-medium text-grayScale-900">
|
||||
|
|
@ -891,9 +890,9 @@ export function ProgramDetailPage() {
|
|||
disabled={savingEdit || uploadingEditThumbnail}
|
||||
>
|
||||
<option value="">Select a category…</option>
|
||||
<option value="EDUCATION">Education</option>
|
||||
<option value="IELTS">IELTS</option>
|
||||
<option value="DUOLINGO">Duolingo</option>
|
||||
<option value="EDUCATION">Makeup Artistry</option>
|
||||
<option value="IELTS">Legacy: IELTS</option>
|
||||
<option value="DUOLINGO">Legacy: Duolingo</option>
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -5,20 +5,20 @@ import { PageBackLink } from "../../components/navigation/PageBackLink";
|
|||
const categories = [
|
||||
{
|
||||
slug: "education",
|
||||
title: "Education",
|
||||
description: "Structured learning courses with lessons, practice, and assessments.",
|
||||
title: "Makeup Artistry",
|
||||
description: "Teach makeup foundations, bridal looks, and editorial artistry through demonstrations and assessments.",
|
||||
icon: BookOpen,
|
||||
},
|
||||
{
|
||||
slug: "ielts",
|
||||
title: "IELTS",
|
||||
description: "Prepare learners for IELTS sections, skills, and exam practice.",
|
||||
title: "Legacy: IELTS",
|
||||
description: "Historical language courses retained for existing learners.",
|
||||
icon: Target,
|
||||
},
|
||||
{
|
||||
slug: "duolingo",
|
||||
title: "Duolingo English Test",
|
||||
description: "Build courses and exam preparation for the Duolingo English Test.",
|
||||
title: "Legacy: Duolingo English Test",
|
||||
description: "Historical language courses retained for existing learners.",
|
||||
icon: Languages,
|
||||
},
|
||||
];
|
||||
|
|
@ -36,7 +36,7 @@ export function ProgramTypeSelectionPage() {
|
|||
</p>
|
||||
</div>
|
||||
<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">
|
||||
<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">
|
||||
|
|
@ -51,6 +51,12 @@ export function ProgramTypeSelectionPage() {
|
|||
</Link>
|
||||
))}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
|
|
@ -12,10 +9,16 @@ import {
|
|||
Trash2,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link, useNavigate, useSearchParams } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import {
|
||||
deleteQuestionTypeDefinition,
|
||||
getQuestionTypeDefinitions,
|
||||
} from "../../api/questionTypeDefinitions.api"
|
||||
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 {
|
||||
Dialog,
|
||||
|
|
@ -25,18 +28,15 @@ import {
|
|||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
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 { cn } from "../../lib/utils"
|
||||
import type { QuestionTypeDefinition } from "../../types/questionTypeDefinition.types"
|
||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||
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 ScopeFilter = "all" | "system" | "custom"
|
||||
|
|
@ -64,7 +64,7 @@ export function QuestionTypeLibraryPage() {
|
|||
const [query, setQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("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 [definitionPendingDelete, setDefinitionPendingDelete] = useState<QuestionTypeDefinition | null>(null)
|
||||
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 { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
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 { type ChangeEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
addQuestionToSet,
|
||||
createQuestion,
|
||||
createQuestionSet,
|
||||
deleteQuestion,
|
||||
getCourseCategories,
|
||||
getCoursesByCategory,
|
||||
getQuestionById,
|
||||
getSubModulesByCourse,
|
||||
createQuestion,
|
||||
createQuestionSet,
|
||||
// getQuestions,
|
||||
getPracticeQuestionsByPractice,
|
||||
getQuestionById,
|
||||
getQuestionSets,
|
||||
getSubModulesByCourse,
|
||||
updateQuestion,
|
||||
} from "../../api/courses.api"
|
||||
import { resolveFileUrl, uploadAudioFile, uploadImageFile } 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 { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
|
|
@ -33,13 +27,19 @@ import {
|
|||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "../../components/ui/dropdown-menu"
|
||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||
import { toast } from "sonner"
|
||||
import { Input } from "../../components/ui/input"
|
||||
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 { notifyApiError } from "../../lib/apiErrors"
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { UnassignedLabel } from "../../lib/displayValue"
|
||||
import { SearchHighlight } from "../../components/SearchHighlight"
|
||||
import { vimeoResultToStoredUrl } from "../../lib/video-upload/upload-video"
|
||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||
|
||||
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
||||
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 [audioTotalCount, setAudioTotalCount] = useState(0)
|
||||
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 [selectedPracticeId, setSelectedPracticeId] = useState<string>("")
|
||||
const [practiceFilterOpen, setPracticeFilterOpen] = useState(false)
|
||||
|
|
@ -1277,7 +1277,7 @@ export function SpeakingPage() {
|
|||
const groupedAudioQuestions = useMemo(() => {
|
||||
const groups = new Map<string, { practiceId: number | null; practiceTitle: string; questions: AudioListQuestion[] }>()
|
||||
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"
|
||||
if (!groups.has(key)) {
|
||||
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 { 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"
|
||||
|
|
@ -128,7 +128,7 @@ export function SubModuleContentPage() {
|
|||
fetchData()
|
||||
}, [subModuleId, courseId])
|
||||
|
||||
const fetchPractices = async () => {
|
||||
const fetchPractices = useCallback(async () => {
|
||||
if (!subModuleId) return
|
||||
setPracticesLoading(true)
|
||||
try {
|
||||
|
|
@ -141,9 +141,9 @@ export function SubModuleContentPage() {
|
|||
} finally {
|
||||
setPracticesLoading(false)
|
||||
}
|
||||
}
|
||||
}, [subModuleId])
|
||||
|
||||
const fetchVideos = async () => {
|
||||
const fetchVideos = useCallback(async () => {
|
||||
if (!subModuleId) return
|
||||
setVideosLoading(true)
|
||||
try {
|
||||
|
|
@ -155,9 +155,9 @@ export function SubModuleContentPage() {
|
|||
} finally {
|
||||
setVideosLoading(false)
|
||||
}
|
||||
}
|
||||
}, [subModuleId])
|
||||
|
||||
const fetchRatings = async (offset = 0) => {
|
||||
const fetchRatings = useCallback(async (offset = 0) => {
|
||||
if (!subModuleId) return
|
||||
setRatingsLoading(true)
|
||||
try {
|
||||
|
|
@ -173,7 +173,7 @@ export function SubModuleContentPage() {
|
|||
} finally {
|
||||
setRatingsLoading(false)
|
||||
}
|
||||
}
|
||||
}, [subModuleId, ratingsPageSize])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "practice") {
|
||||
|
|
@ -183,13 +183,8 @@ export function SubModuleContentPage() {
|
|||
} else if (activeTab === "ratings") {
|
||||
fetchRatings(ratingsPage * ratingsPageSize)
|
||||
}
|
||||
}, [activeTab, subModuleId])
|
||||
}, [activeTab, fetchPractices, fetchVideos, fetchRatings, ratingsPage, ratingsPageSize])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeTab === "ratings") {
|
||||
fetchRatings(ratingsPage * ratingsPageSize)
|
||||
}
|
||||
}, [ratingsPage])
|
||||
|
||||
const handleAddPractice = () => {
|
||||
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 {
|
||||
Dialog,
|
||||
|
|
@ -8,26 +7,8 @@ import {
|
|||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
|
||||
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.`
|
||||
}
|
||||
import type { ContentAccessTier } from "../../../types/course.types"
|
||||
import { accessTierConfirmDescription, accessTierConfirmTitle } from "./AccessTierConfirmDialog.shared"
|
||||
|
||||
type AccessTierConfirmDialogProps = {
|
||||
open: boolean
|
||||
|
|
|
|||
|
|
@ -1,42 +1,42 @@
|
|||
import { SpinnerIcon } from "@/components/ui/spinner-icon";
|
||||
import { notifyApiError } from "../../../lib/apiErrors"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { BookOpen, RefreshCw } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { BookOpen, RefreshCw } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
deleteExamPrepPractice,
|
||||
getExamPrepCatalogCoursePractices,
|
||||
setExamPrepPracticePublishStatus,
|
||||
} from "../../../api/courses.api"
|
||||
import { unwrapPracticesList } from "../../../lib/parentContextPractice"
|
||||
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"
|
||||
} from "../../../api/courses.api";
|
||||
import { Button } from "../../../components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar"
|
||||
import { PracticeSelectableGrid } from "./PracticeSelectableGrid"
|
||||
} from "../../../components/ui/dialog";
|
||||
import { notifyApiError } from "../../../lib/apiErrors";
|
||||
import {
|
||||
filterBySearchAndPublishStatus,
|
||||
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 {
|
||||
ParentContextPractice,
|
||||
PracticePublishStatus,
|
||||
} from "../../../types/course.types"
|
||||
} from "../../../types/course.types";
|
||||
import { ContentListSearchFilterBar } from "./ContentListSearchFilterBar";
|
||||
import { PracticeSelectableGrid } from "./PracticeSelectableGrid";
|
||||
|
||||
function extractPracticesPage(
|
||||
res: Awaited<ReturnType<typeof getExamPrepCatalogCoursePractices>>,
|
||||
|
|
@ -313,8 +313,8 @@ export function CatalogCoursePracticesPanel({
|
|||
parentsFromPractice(practiceToUnlink).filter(
|
||||
(p) =>
|
||||
!(
|
||||
p.parent_kind === catalogParent.parent_kind &&
|
||||
p.parent_id === catalogParent.parent_id
|
||||
p.parent_kind === "CATALOG_COURSE" &&
|
||||
p.parent_id === catalogCourseId
|
||||
),
|
||||
).length === 0
|
||||
? " 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