feat(admin): connect admin pages to live APIs and expand content tooling
Wire team, user, persona, FAQ, and ratings flows to backend endpoints; rebuild profile and user detail views with learning activity and subscriptions; fetch Vimeo lesson duration on module cards; add shared filters, permissions helpers, and notification UX improvements. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
035d73889e
commit
2966bdb180
174
package-lock.json
generated
174
package-lock.json
generated
|
|
@ -29,6 +29,7 @@
|
|||
"resend": "^6.12.3",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -3403,6 +3404,12 @@
|
|||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
|
|
@ -3553,6 +3560,15 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/combine-errors": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/combine-errors/-/combine-errors-3.0.3.tgz",
|
||||
"integrity": "sha512-C8ikRNRMygCwaTx+Ek3Yr+OuZzgZjduCOfSQBjbM8V3MfgcjSTeto/GXP6PAwKvJz/v15b7GHZvx5rOlczFw/Q==",
|
||||
"dependencies": {
|
||||
"custom-error-instance": "2.1.1",
|
||||
"lodash.uniqby": "4.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
|
|
@ -3637,6 +3653,12 @@
|
|||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/custom-error-instance": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/custom-error-instance/-/custom-error-instance-2.1.1.tgz",
|
||||
"integrity": "sha512-p6JFxJc3M4OTD2li2qaHkDCw9SfMw82Ldr6OC9Je1aXiGfhx2W8p3GaoeaGrPJTUN9NirTM/KTxHWMUdR1rsUg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||
|
|
@ -4467,6 +4489,12 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
|
|
@ -4651,6 +4679,18 @@
|
|||
"node": ">=0.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-stream": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
|
||||
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
|
|
@ -4668,6 +4708,12 @@
|
|||
"jiti": "bin/jiti.js"
|
||||
}
|
||||
},
|
||||
"node_modules/js-base64": {
|
||||
"version": "3.7.8",
|
||||
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.8.tgz",
|
||||
"integrity": "sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
|
|
@ -4795,6 +4841,52 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash._baseiteratee": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash._baseiteratee/-/lodash._baseiteratee-4.7.0.tgz",
|
||||
"integrity": "sha512-nqB9M+wITz0BX/Q2xg6fQ8mLkyfF7MU7eE+MNBNjTHFKeKaZAPEzEg+E8LWxKWf1DQVflNEn9N49yAuqKh2mWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash._stringtopath": "~4.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash._basetostring": {
|
||||
"version": "4.12.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-4.12.0.tgz",
|
||||
"integrity": "sha512-SwcRIbyxnN6CFEEK4K1y+zuApvWdpQdBHM/swxP962s8HIxPO3alBH5t3m/dl+f4CMUug6sJb7Pww8d13/9WSw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash._baseuniq": {
|
||||
"version": "4.6.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash._baseuniq/-/lodash._baseuniq-4.6.0.tgz",
|
||||
"integrity": "sha512-Ja1YevpHZctlI5beLA7oc5KNDhGcPixFhcqSiORHNsp/1QTv7amAXzw+gu4YOvErqVlMVyIJGgtzeepCnnur0A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash._createset": "~4.0.0",
|
||||
"lodash._root": "~3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash._createset": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash._createset/-/lodash._createset-4.0.3.tgz",
|
||||
"integrity": "sha512-GTkC6YMprrJZCYU3zcqZj+jkXkrXzq3IPBcF/fIPpNEAB4hZEtXU8zp/RwKOvZl43NUmwDbyRk3+ZTbeRdEBXA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash._root": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash._root/-/lodash._root-3.0.1.tgz",
|
||||
"integrity": "sha512-O0pWuFSK6x4EXhM1dhZ8gchNtG7JMqBtrHdoUFUWXD7dJnNSUze1GuyQr5sOs0aCvgGeI3o/OJW8f4ca7FDxmQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash._stringtopath": {
|
||||
"version": "4.8.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash._stringtopath/-/lodash._stringtopath-4.8.0.tgz",
|
||||
"integrity": "sha512-SXL66C731p0xPDC5LZg4wI5H+dJo/EO4KTqOMwLYCH3+FmmfAKJEZCm6ohGpI+T1xwsDsJCfL4OnhorllvlTPQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash._basetostring": "~4.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||
|
|
@ -4802,6 +4894,22 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.throttle": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz",
|
||||
"integrity": "sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.uniqby": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.5.0.tgz",
|
||||
"integrity": "sha512-IRt7cfTtHy6f1aRVA5n7kT8rgN3N1nH6MOWLcHfpWG2SH19E3JksLK38MktLxZDhlAjCP9jpIXkOnRXlu6oByQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lodash._baseiteratee": "~4.7.0",
|
||||
"lodash._baseuniq": "~4.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
||||
|
|
@ -5287,6 +5395,17 @@
|
|||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/proper-lockfile": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
|
||||
"integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.4",
|
||||
"retry": "^0.12.0",
|
||||
"signal-exit": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
|
|
@ -5303,6 +5422,12 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/querystringify": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
|
||||
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
|
|
@ -5577,6 +5702,12 @@
|
|||
"redux": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/requires-port": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
|
||||
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/reselect": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
|
||||
|
|
@ -5635,6 +5766,15 @@
|
|||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/retry": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
|
||||
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/reusify": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
||||
|
|
@ -5757,6 +5897,12 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/signal-exit": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
|
||||
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/sonner": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",
|
||||
|
|
@ -5991,6 +6137,24 @@
|
|||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tus-js-client": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/tus-js-client/-/tus-js-client-4.3.1.tgz",
|
||||
"integrity": "sha512-ZLeYmjrkaU1fUsKbIi8JML52uAocjEZtBx4DKjRrqzrZa0O4MYwT6db+oqePlspV+FxXJAyFBc/L5gwUi2OFsg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-from": "^1.1.2",
|
||||
"combine-errors": "^3.0.3",
|
||||
"is-stream": "^2.0.0",
|
||||
"js-base64": "^3.7.2",
|
||||
"lodash.throttle": "^4.1.1",
|
||||
"proper-lockfile": "^4.1.2",
|
||||
"url-parse": "^1.5.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
|
|
@ -6091,6 +6255,16 @@
|
|||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/url-parse": {
|
||||
"version": "1.5.10",
|
||||
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
|
||||
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"querystringify": "^2.1.1",
|
||||
"requires-port": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/use-callback-ref": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@
|
|||
"resend": "^6.12.3",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"zustand": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -63,9 +63,9 @@ import type {
|
|||
GetSubCourseEntryAssessmentResponse,
|
||||
ReorderItem,
|
||||
ReorderOrderedIdsRequest,
|
||||
GetRatingsResponse,
|
||||
GetRatingsParams,
|
||||
GetVimeoSampleResponse,
|
||||
GetVimeoVideoResponse,
|
||||
VimeoSampleVideo,
|
||||
CreateCourseVideoRequest,
|
||||
GetLearningProgramsResponse,
|
||||
UpdateLearningProgramRequest,
|
||||
|
|
@ -1394,12 +1394,52 @@ export const reorderVideos = reorderNotYetSupported
|
|||
|
||||
export const reorderPractices = reorderNotYetSupported
|
||||
|
||||
// Ratings
|
||||
export const getRatings = (params: GetRatingsParams) =>
|
||||
http.get<GetRatingsResponse>("/ratings", { params })
|
||||
// Ratings — see ratings.api.ts
|
||||
export { getRatings } from "./ratings.api"
|
||||
|
||||
// Vimeo Sample Video
|
||||
export const getVimeoSample = (videoId: string, width = 640, height = 360) =>
|
||||
http.get<GetVimeoSampleResponse>("/vimeo/sample", {
|
||||
params: { video_id: videoId, width, height },
|
||||
})
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function readString(raw: Record<string, unknown>, ...keys: string[]): string {
|
||||
for (const key of keys) {
|
||||
const value = raw[key]
|
||||
if (value == null) continue
|
||||
const text = String(value).trim()
|
||||
if (text) return text
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
function normalizeVimeoVideoDetails(raw: unknown): VimeoSampleVideo {
|
||||
if (!isRecord(raw)) throw new Error("Invalid Vimeo video response")
|
||||
|
||||
return {
|
||||
vimeo_id: readString(raw, "vimeo_id", "VimeoID"),
|
||||
uri: readString(raw, "uri", "URI"),
|
||||
name: readString(raw, "name", "Name"),
|
||||
description: readString(raw, "description", "Description"),
|
||||
duration: Number(raw.duration ?? raw.Duration) || 0,
|
||||
width: Number(raw.width ?? raw.Width) || 0,
|
||||
height: Number(raw.height ?? raw.Height) || 0,
|
||||
link: readString(raw, "link", "Link"),
|
||||
embed_url: readString(raw, "embed_url", "EmbedURL", "EmbedUrl"),
|
||||
embed_html: readString(raw, "embed_html", "EmbedHTML", "EmbedHtml"),
|
||||
thumbnail_url: readString(raw, "thumbnail_url", "ThumbnailURL", "ThumbnailUrl"),
|
||||
status: readString(raw, "status", "Status"),
|
||||
transcode_status: readString(raw, "transcode_status", "TranscodeStatus"),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getVimeoVideo(videoId: string): Promise<VimeoSampleVideo> {
|
||||
const res = await http.get<GetVimeoVideoResponse>(
|
||||
`/vimeo/videos/${encodeURIComponent(videoId.trim())}`,
|
||||
)
|
||||
return normalizeVimeoVideoDetails(res.data.data)
|
||||
}
|
||||
|
|
|
|||
163
src/api/faq.api.ts
Normal file
163
src/api/faq.api.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
import http from "./http"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||
import type {
|
||||
CreateFAQRequest,
|
||||
CreateFAQResponse,
|
||||
DeleteFAQResponse,
|
||||
FAQ,
|
||||
FAQFilters,
|
||||
FAQListData,
|
||||
GetFAQResponse,
|
||||
GetFAQsResponse,
|
||||
UpdateFAQRequest,
|
||||
UpdateFAQResponse,
|
||||
} from "../types/faq.types"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeFAQ(raw: unknown): FAQ | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
if (!Number.isFinite(id)) return null
|
||||
|
||||
const status = String(raw.status ?? "ACTIVE").toUpperCase()
|
||||
const category = raw.category
|
||||
const normalizedCategory =
|
||||
category == null || String(category).trim() === "" ? null : String(category)
|
||||
|
||||
return {
|
||||
id,
|
||||
question: String(raw.question ?? ""),
|
||||
answer: String(raw.answer ?? ""),
|
||||
category: normalizedCategory,
|
||||
display_order: Number(raw.display_order ?? 0),
|
||||
status: status === "INACTIVE" ? "INACTIVE" : "ACTIVE",
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
updated_at:
|
||||
raw.updated_at == null || String(raw.updated_at).trim() === ""
|
||||
? null
|
||||
: String(raw.updated_at),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseFAQsList(body: unknown): FAQListData {
|
||||
const empty: FAQListData = { faqs: [], total_count: 0 }
|
||||
|
||||
if (isRecord(body)) {
|
||||
const data = body.data
|
||||
if (isRecord(data) && Array.isArray(data.faqs)) {
|
||||
const faqs = data.faqs
|
||||
.map(normalizeFAQ)
|
||||
.filter((row): row is FAQ => row !== null)
|
||||
const total_count = Number(data.total_count ?? faqs.length)
|
||||
return {
|
||||
faqs,
|
||||
total_count: Number.isFinite(total_count) ? total_count : faqs.length,
|
||||
}
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
const faqs = data.map(normalizeFAQ).filter((row): row is FAQ => row !== null)
|
||||
return { faqs, total_count: faqs.length }
|
||||
}
|
||||
if (Array.isArray(body.faqs)) {
|
||||
const faqs = body.faqs
|
||||
.map(normalizeFAQ)
|
||||
.filter((row): row is FAQ => row !== null)
|
||||
const total_count = Number(body.total_count ?? faqs.length)
|
||||
return {
|
||||
faqs,
|
||||
total_count: Number.isFinite(total_count) ? total_count : faqs.length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(body)) {
|
||||
const faqs = body.map(normalizeFAQ).filter((row): row is FAQ => row !== null)
|
||||
return { faqs, total_count: faqs.length }
|
||||
}
|
||||
|
||||
return empty
|
||||
}
|
||||
|
||||
export function parseFAQMutation(body: unknown): FAQ | null {
|
||||
if (isRecord(body) && body.data != null) {
|
||||
return normalizeFAQ(body.data)
|
||||
}
|
||||
return normalizeFAQ(body)
|
||||
}
|
||||
|
||||
function buildFAQQuery(filters: FAQFilters = {}): Record<string, string | number> {
|
||||
const params: Record<string, string | number> = {}
|
||||
if (filters.status) params.status = filters.status
|
||||
if (filters.category?.trim()) params.category = filters.category.trim()
|
||||
params.limit = filters.limit ?? DEFAULT_TABLE_PAGE_SIZE
|
||||
params.offset = filters.offset ?? 0
|
||||
return params
|
||||
}
|
||||
|
||||
/** GET /admin/faqs — list FAQs (all statuses). */
|
||||
export const getFAQs = (filters: FAQFilters = {}) =>
|
||||
http
|
||||
.get<GetFAQsResponse>("/admin/faqs", { params: buildFAQQuery(filters) })
|
||||
.then((res) => {
|
||||
const parsed = parseFAQsList(res.data)
|
||||
return {
|
||||
...res,
|
||||
data: parsed,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}
|
||||
})
|
||||
|
||||
/** GET /admin/faqs/:id — get one FAQ for editing. */
|
||||
export const getFAQById = (id: number) =>
|
||||
http.get<GetFAQResponse>(`/admin/faqs/${id}`).then((res) => ({
|
||||
...res,
|
||||
data: parseFAQMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
/** POST /admin/faqs — create FAQ. */
|
||||
export const createFAQ = (payload: CreateFAQRequest) =>
|
||||
http.post<CreateFAQResponse>("/admin/faqs", payload).then((res) => ({
|
||||
...res,
|
||||
data: parseFAQMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
/** PUT /admin/faqs/:id — update FAQ. */
|
||||
export const updateFAQ = (id: number, payload: UpdateFAQRequest) =>
|
||||
http.put<UpdateFAQResponse>(`/admin/faqs/${id}`, payload).then((res) => ({
|
||||
...res,
|
||||
data: parseFAQMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
/** DELETE /admin/faqs/:id — hard delete FAQ. */
|
||||
export const deleteFAQ = (id: number) =>
|
||||
http.delete<DeleteFAQResponse>(`/admin/faqs/${id}`).then((res) => ({
|
||||
...res,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
/** GET /faqs/:id — public detail (preview only, ACTIVE FAQs). */
|
||||
export const getPublicFAQById = (id: number) =>
|
||||
http.get<GetFAQResponse>(`/faqs/${id}`).then((res) => ({
|
||||
...res,
|
||||
data: parseFAQMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
/** GET /faqs — public list (preview only, ACTIVE FAQs). */
|
||||
export const getPublicFAQs = (filters: Pick<FAQFilters, "category" | "limit" | "offset"> = {}) =>
|
||||
http
|
||||
.get<GetFAQsResponse>("/faqs", { params: buildFAQQuery(filters) })
|
||||
.then((res) => {
|
||||
const parsed = parseFAQsList(res.data)
|
||||
return {
|
||||
...res,
|
||||
data: parsed,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}
|
||||
})
|
||||
|
|
@ -118,6 +118,13 @@ export const markAllRead = () =>
|
|||
export const markAllUnread = () =>
|
||||
http.post("/notifications/mark-all-unread")
|
||||
|
||||
/** DELETE /notifications/:id — remove an in-app notification. */
|
||||
export const deleteNotification = (id: string) =>
|
||||
http.delete<unknown>(`/notifications/${id}`).then((res) => ({
|
||||
...res,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
|
||||
export type BulkSendApiResult =
|
||||
| { kind: "immediate"; data: BulkSendResult; message: string }
|
||||
| { kind: "scheduled"; data: ScheduledNotification; message: string }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,162 @@
|
|||
import http from "./http"
|
||||
import type { GetPersonasParams, GetPersonasResponse } from "../types/persona.types"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||
import type {
|
||||
CreatePersonaInput,
|
||||
DeletePersonaResponse,
|
||||
GetPersonaResponse,
|
||||
GetPersonasResponse,
|
||||
ListPersonasParams,
|
||||
LmsPersona,
|
||||
MutatePersonaResponse,
|
||||
PersonaListData,
|
||||
UpdatePersonaInput,
|
||||
} from "../types/persona.types"
|
||||
|
||||
/** GET /personas — list personas (filter active client-side when needed). */
|
||||
export const getPersonas = (params?: GetPersonasParams) =>
|
||||
http.get<GetPersonasResponse>("/personas", { params })
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizePersona(raw: unknown): LmsPersona | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
if (!Number.isFinite(id)) return null
|
||||
|
||||
const name = String(raw.name ?? "").trim()
|
||||
if (!name) return null
|
||||
|
||||
const descriptionRaw = raw.description
|
||||
const description =
|
||||
descriptionRaw == null || String(descriptionRaw).trim() === ""
|
||||
? null
|
||||
: String(descriptionRaw)
|
||||
|
||||
const profilePictureRaw = raw.profile_picture
|
||||
const profile_picture =
|
||||
profilePictureRaw == null || String(profilePictureRaw).trim() === ""
|
||||
? null
|
||||
: String(profilePictureRaw)
|
||||
|
||||
const genderRaw = raw.gender
|
||||
const gender =
|
||||
genderRaw == null || String(genderRaw).trim() === "" ? null : String(genderRaw)
|
||||
|
||||
const updatedAtRaw = raw.updated_at
|
||||
const updated_at =
|
||||
updatedAtRaw == null || String(updatedAtRaw).trim() === ""
|
||||
? null
|
||||
: String(updatedAtRaw)
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
profile_picture,
|
||||
gender,
|
||||
is_active: raw.is_active !== false,
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
export function parsePersonasList(body: unknown): PersonaListData {
|
||||
const empty: PersonaListData = {
|
||||
personas: [],
|
||||
total_count: 0,
|
||||
limit: DEFAULT_TABLE_PAGE_SIZE,
|
||||
offset: 0,
|
||||
}
|
||||
|
||||
if (isRecord(body)) {
|
||||
const data = body.data ?? body.Data
|
||||
if (isRecord(data) && Array.isArray(data.personas)) {
|
||||
const personas = data.personas
|
||||
.map(normalizePersona)
|
||||
.filter((row): row is LmsPersona => row !== null)
|
||||
const total_count = Number(data.total_count ?? personas.length)
|
||||
const limit = Number(data.limit ?? DEFAULT_TABLE_PAGE_SIZE)
|
||||
const offset = Number(data.offset ?? 0)
|
||||
return {
|
||||
personas,
|
||||
total_count: Number.isFinite(total_count) ? total_count : personas.length,
|
||||
limit: Number.isFinite(limit) ? limit : DEFAULT_TABLE_PAGE_SIZE,
|
||||
offset: Number.isFinite(offset) ? offset : 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return empty
|
||||
}
|
||||
|
||||
export function parsePersonaMutation(body: unknown): LmsPersona | null {
|
||||
if (isRecord(body) && body.data != null) {
|
||||
return normalizePersona(body.data)
|
||||
}
|
||||
return normalizePersona(body)
|
||||
}
|
||||
|
||||
function buildPersonasQuery(params: ListPersonasParams = {}): Record<string, string | number | boolean> {
|
||||
return {
|
||||
active_only: params.active_only !== false,
|
||||
limit: params.limit ?? DEFAULT_TABLE_PAGE_SIZE,
|
||||
offset: params.offset ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /personas — list persona catalog (paginated). */
|
||||
export function listPersonas(params: ListPersonasParams = {}) {
|
||||
return http
|
||||
.get<GetPersonasResponse>("/personas", { params: buildPersonasQuery(params) })
|
||||
.then((res) => {
|
||||
const parsed = parsePersonasList(res.data)
|
||||
return {
|
||||
...res,
|
||||
data: parsed,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** GET /personas — legacy axios response for practice picker callers. */
|
||||
export const getPersonas = (params?: ListPersonasParams) =>
|
||||
http.get<GetPersonasResponse>("/personas", { params: buildPersonasQuery(params ?? {}) })
|
||||
|
||||
/** GET /personas/:id */
|
||||
export function getPersonaById(id: number) {
|
||||
return http.get<GetPersonaResponse>(`/personas/${id}`).then((res) => ({
|
||||
...res,
|
||||
data: parsePersonaMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
/** POST /personas */
|
||||
export function createPersona(payload: CreatePersonaInput) {
|
||||
return http.post<MutatePersonaResponse>("/personas", payload).then((res) => ({
|
||||
...res,
|
||||
data: parsePersonaMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
/** PUT /personas/:id */
|
||||
export function updatePersona(id: number, payload: UpdatePersonaInput) {
|
||||
return http.put<MutatePersonaResponse>(`/personas/${id}`, payload).then((res) => ({
|
||||
...res,
|
||||
data: parsePersonaMutation(res.data),
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
/** DELETE /personas/:id */
|
||||
export function deletePersona(id: number) {
|
||||
return http.delete<DeletePersonaResponse>(`/personas/${id}`).then((res) => ({
|
||||
...res,
|
||||
message: isRecord(res.data) ? String(res.data.message ?? "") : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Active personas for practice editor dropdown. */
|
||||
export async function listActivePersonasForPicker(limit = 200): Promise<LmsPersona[]> {
|
||||
const res = await listPersonas({ active_only: true, limit, offset: 0 })
|
||||
return res.data.personas
|
||||
}
|
||||
|
|
|
|||
144
src/api/ratings.api.ts
Normal file
144
src/api/ratings.api.ts
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import http from "./http"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination"
|
||||
import type {
|
||||
AppReviewsPageData,
|
||||
GetRatingSummaryResponse,
|
||||
GetRatingsResponse,
|
||||
ListRatingsParams,
|
||||
Rating,
|
||||
RatingSummary,
|
||||
RatingSummaryParams,
|
||||
RatingTargetType,
|
||||
} from "../types/ratings.types"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeTargetId(targetType: RatingTargetType, targetId?: number): number {
|
||||
if (targetType === "app") return 0
|
||||
const id = Number(targetId ?? 0)
|
||||
return Number.isFinite(id) ? id : 0
|
||||
}
|
||||
|
||||
function normalizeRating(raw: unknown): Rating | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
const user_id = Number(raw.user_id)
|
||||
if (!Number.isFinite(id) || !Number.isFinite(user_id)) return null
|
||||
|
||||
const target_type = String(raw.target_type ?? "app") as RatingTargetType
|
||||
const stars = Number(raw.stars)
|
||||
if (!Number.isFinite(stars) || stars < 1 || stars > 5) return null
|
||||
|
||||
const reviewRaw = raw.review
|
||||
const review =
|
||||
reviewRaw == null || String(reviewRaw).trim() === "" ? null : String(reviewRaw)
|
||||
|
||||
return {
|
||||
id,
|
||||
user_id,
|
||||
target_type,
|
||||
target_id: Number(raw.target_id ?? 0),
|
||||
stars,
|
||||
review,
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
updated_at: String(raw.updated_at ?? ""),
|
||||
}
|
||||
}
|
||||
|
||||
function parseRatingsList(body: unknown): Rating[] {
|
||||
if (isRecord(body) && Array.isArray(body.data)) {
|
||||
return body.data.map(normalizeRating).filter((row): row is Rating => row !== null)
|
||||
}
|
||||
if (Array.isArray(body)) {
|
||||
return body.map(normalizeRating).filter((row): row is Rating => row !== null)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function parseRatingSummary(body: unknown): RatingSummary {
|
||||
const fallback: RatingSummary = { total_count: 0, average_stars: 0 }
|
||||
if (!isRecord(body)) return fallback
|
||||
|
||||
const data = body.data
|
||||
if (!isRecord(data)) return fallback
|
||||
|
||||
const total_count = Number(data.total_count ?? 0)
|
||||
const average_stars = Number(data.average_stars ?? 0)
|
||||
|
||||
return {
|
||||
total_count: Number.isFinite(total_count) ? total_count : 0,
|
||||
average_stars: Number.isFinite(average_stars) ? average_stars : 0,
|
||||
}
|
||||
}
|
||||
|
||||
function buildRatingsQuery(params: ListRatingsParams): Record<string, string | number> {
|
||||
const targetId = normalizeTargetId(params.target_type, params.target_id)
|
||||
return {
|
||||
target_type: params.target_type,
|
||||
target_id: targetId,
|
||||
limit: params.limit ?? DEFAULT_TABLE_PAGE_SIZE,
|
||||
offset: params.offset ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function getRatingSummary(params: RatingSummaryParams) {
|
||||
const targetId = normalizeTargetId(params.target_type, params.target_id)
|
||||
return http
|
||||
.get<GetRatingSummaryResponse>("/ratings/summary", {
|
||||
params: { target_type: params.target_type, target_id: targetId },
|
||||
})
|
||||
.then((res) => parseRatingSummary(res.data))
|
||||
}
|
||||
|
||||
export function listRatingsByTarget(params: ListRatingsParams) {
|
||||
return http
|
||||
.get<GetRatingsResponse>("/ratings", { params: buildRatingsQuery(params) })
|
||||
.then((res) => parseRatingsList(res.data))
|
||||
}
|
||||
|
||||
/** Load summary + paginated reviews in parallel (recommended admin pattern). */
|
||||
export async function loadRatingsPage(
|
||||
targetType: RatingTargetType,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
targetId?: number,
|
||||
): Promise<AppReviewsPageData> {
|
||||
const offset = (page - 1) * pageSize
|
||||
const normalizedTargetId = normalizeTargetId(targetType, targetId)
|
||||
|
||||
const [summary, reviews] = await Promise.all([
|
||||
getRatingSummary({ target_type: targetType, target_id: normalizedTargetId }),
|
||||
listRatingsByTarget({
|
||||
target_type: targetType,
|
||||
target_id: normalizedTargetId,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
}),
|
||||
])
|
||||
|
||||
return { summary, reviews }
|
||||
}
|
||||
|
||||
/** @deprecated Use listRatingsByTarget — kept for legacy callers. */
|
||||
export function getRatings(params: {
|
||||
target_type: string
|
||||
target_id: number
|
||||
limit?: number
|
||||
offset?: number
|
||||
}) {
|
||||
return listRatingsByTarget({
|
||||
target_type: params.target_type as RatingTargetType,
|
||||
target_id: params.target_id,
|
||||
limit: params.limit,
|
||||
offset: params.offset,
|
||||
}).then((reviews) => ({
|
||||
data: {
|
||||
message: "Ratings retrieved successfully",
|
||||
data: reviews,
|
||||
success: true,
|
||||
status_code: 200,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
|
@ -30,6 +30,10 @@ export const setRolePermissions = (roleId: number, data: SetRolePermissionsReque
|
|||
export const getAllPermissions = () =>
|
||||
http.get<GetPermissionsResponse>("/rbac/permissions")
|
||||
|
||||
/** POST /rbac/permissions/sync — upsert permission definitions and default role links. */
|
||||
export const syncRbacPermissions = () =>
|
||||
http.post<{ message?: string }>("/rbac/permissions/sync")
|
||||
|
||||
export const deleteRole = (roleId: number) =>
|
||||
http.delete<DeleteRoleResponse>(`/rbac/roles/${roleId}`)
|
||||
|
||||
|
|
|
|||
|
|
@ -9,12 +9,79 @@ import type {
|
|||
import type {
|
||||
ChangeTeamMemberPasswordRequest,
|
||||
ChangeTeamMemberPasswordResponse,
|
||||
GetTeamMeResponse,
|
||||
GetTeamMembersResponse,
|
||||
GetTeamMemberResponse,
|
||||
CreateTeamMemberRequest,
|
||||
UpdateTeamMemberRequest,
|
||||
UpdateTeamMeRequest,
|
||||
TeamMember,
|
||||
TeamMemberDetail,
|
||||
} from "../types/team.types"
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | null {
|
||||
if (value == null) return null
|
||||
const text = String(value).trim()
|
||||
return text ? text : null
|
||||
}
|
||||
|
||||
export function normalizeTeamMemberDetail(raw: unknown): TeamMemberDetail | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
if (!Number.isFinite(id)) return null
|
||||
|
||||
return {
|
||||
id,
|
||||
first_name: String(raw.first_name ?? ""),
|
||||
last_name: String(raw.last_name ?? ""),
|
||||
email: String(raw.email ?? ""),
|
||||
phone_number: String(raw.phone_number ?? ""),
|
||||
team_role: String(raw.team_role ?? ""),
|
||||
department: String(raw.department ?? ""),
|
||||
job_title: String(raw.job_title ?? ""),
|
||||
bio: optionalString(raw.bio),
|
||||
status: String(raw.status ?? ""),
|
||||
email_verified: raw.email_verified === true,
|
||||
last_login: optionalString(raw.last_login),
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
updated_at: optionalString(raw.updated_at),
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeTeamMember(raw: unknown): TeamMember | null {
|
||||
if (!isRecord(raw)) return null
|
||||
const id = Number(raw.id)
|
||||
if (!Number.isFinite(id)) return null
|
||||
|
||||
const permissionsRaw = raw.permissions
|
||||
const permissions = Array.isArray(permissionsRaw)
|
||||
? permissionsRaw.map((entry) => String(entry))
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id,
|
||||
first_name: String(raw.first_name ?? ""),
|
||||
last_name: String(raw.last_name ?? ""),
|
||||
email: String(raw.email ?? ""),
|
||||
phone_number: String(raw.phone_number ?? ""),
|
||||
team_role: String(raw.team_role ?? ""),
|
||||
department: String(raw.department ?? ""),
|
||||
job_title: String(raw.job_title ?? ""),
|
||||
employment_type: optionalString(raw.employment_type) ?? undefined,
|
||||
hire_date: optionalString(raw.hire_date) ?? undefined,
|
||||
bio: optionalString(raw.bio) ?? undefined,
|
||||
status: String(raw.status ?? ""),
|
||||
email_verified: raw.email_verified === true,
|
||||
permissions,
|
||||
last_login: optionalString(raw.last_login),
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
}
|
||||
}
|
||||
|
||||
export const getTeamMembers = (page?: number, pageSize?: number) =>
|
||||
http.get<GetTeamMembersResponse>("/team/members", {
|
||||
params: {
|
||||
|
|
@ -24,7 +91,27 @@ export const getTeamMembers = (page?: number, pageSize?: number) =>
|
|||
})
|
||||
|
||||
export const getTeamMemberById = (id: number) =>
|
||||
http.get<GetTeamMemberResponse>(`/team/members/${id}`)
|
||||
http.get<GetTeamMemberResponse>(`/team/members/${id}`).then((res) => {
|
||||
const body = res.data
|
||||
const member = normalizeTeamMemberDetail(body?.data)
|
||||
if (!member) {
|
||||
throw new Error("Invalid team member response")
|
||||
}
|
||||
return {
|
||||
...res,
|
||||
data: {
|
||||
...body,
|
||||
data: member,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
/** GET /team/me — signed-in team member profile */
|
||||
export const getTeamMe = () => http.get<GetTeamMeResponse>("/team/me")
|
||||
|
||||
/** PUT /team/me — update signed-in team member profile */
|
||||
export const updateTeamMe = (data: UpdateTeamMeRequest) =>
|
||||
http.put<GetTeamMeResponse>("/team/me", data)
|
||||
|
||||
export const createTeamMember = (data: CreateTeamMemberRequest) =>
|
||||
http.post("/team/register", data)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,399 @@
|
|||
import http from "./http";
|
||||
import type { GetTeamMeResponse } from "../types/team.types";
|
||||
import {
|
||||
type UserProfileResponse,
|
||||
type GetUsersResponse,
|
||||
type UpdateProfileRequest,
|
||||
type UserProfileData,
|
||||
type UserProfileResponse,
|
||||
type UserSummaryResponse,
|
||||
type GetDeletionRequestsParams,
|
||||
type GetDeletionRequestsResponse,
|
||||
type UserRecentActivityResponse,
|
||||
type UserRecentActivityItem,
|
||||
type UserRecentActivityData,
|
||||
} from "../types/user.types";
|
||||
import type {
|
||||
LearningActivityAccess,
|
||||
LearningActivityCompletedIds,
|
||||
LearningActivityCourse,
|
||||
LearningActivityLesson,
|
||||
LearningActivityModule,
|
||||
LearningActivityProgram,
|
||||
LearningActivityUnit,
|
||||
UserLearningActivityData,
|
||||
UserLearningActivityResponse,
|
||||
UserSubscriptionPayment,
|
||||
UserSubscriptionRecord,
|
||||
UserSubscriptionsData,
|
||||
UserSubscriptionsResponse,
|
||||
} from "../types/userAdmin.types";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
const text = String(value).trim();
|
||||
return text ? text : null;
|
||||
}
|
||||
|
||||
export function normalizeUserProfile(raw: unknown): UserProfileData | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
return {
|
||||
id,
|
||||
first_name: String(raw.first_name ?? ""),
|
||||
last_name: String(raw.last_name ?? ""),
|
||||
gender: String(raw.gender ?? ""),
|
||||
birth_day: optionalString(raw.birth_day),
|
||||
email: String(raw.email ?? ""),
|
||||
role: String(raw.role ?? ""),
|
||||
age_group: String(raw.age_group ?? ""),
|
||||
education_level: String(raw.education_level ?? ""),
|
||||
country: String(raw.country ?? ""),
|
||||
region: String(raw.region ?? ""),
|
||||
nick_name: String(raw.nick_name ?? ""),
|
||||
occupation: String(raw.occupation ?? ""),
|
||||
learning_goal: String(raw.learning_goal ?? ""),
|
||||
language_goal: String(raw.language_goal ?? ""),
|
||||
language_challange: String(raw.language_challange ?? ""),
|
||||
favoutite_topic: String(raw.favoutite_topic ?? ""),
|
||||
email_verified: raw.email_verified === true,
|
||||
phone_verified: raw.phone_verified === true,
|
||||
status: String(raw.status ?? ""),
|
||||
last_login: optionalString(raw.last_login),
|
||||
profile_completed: raw.profile_completed === true,
|
||||
profile_completion_percentage: Number(raw.profile_completion_percentage) || 0,
|
||||
profile_picture_url: String(raw.profile_picture_url ?? ""),
|
||||
preferred_language: String(raw.preferred_language ?? ""),
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
subscription_status: String(raw.subscription_status ?? ""),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUserRecentActivityItem(raw: unknown): UserRecentActivityItem | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = String(raw.id ?? "").trim();
|
||||
if (!id) return null;
|
||||
|
||||
return {
|
||||
id,
|
||||
kind: String(raw.kind ?? ""),
|
||||
occurred_at: String(raw.occurred_at ?? ""),
|
||||
headline: String(raw.headline ?? ""),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUserRecentActivity(raw: unknown): UserRecentActivityData | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const userId = Number(raw.user_id);
|
||||
if (!Number.isFinite(userId)) return null;
|
||||
|
||||
const itemsRaw = raw.items;
|
||||
const items = Array.isArray(itemsRaw)
|
||||
? itemsRaw
|
||||
.map((entry) => normalizeUserRecentActivityItem(entry))
|
||||
.filter((entry): entry is UserRecentActivityItem => entry !== null)
|
||||
: [];
|
||||
|
||||
return { user_id: userId, items };
|
||||
}
|
||||
|
||||
function normalizeLearningActivityAccess(raw: unknown): LearningActivityAccess {
|
||||
if (!isRecord(raw)) {
|
||||
return {
|
||||
is_accessible: false,
|
||||
is_completed: false,
|
||||
completed_count: 0,
|
||||
total_count: 0,
|
||||
progress_percent: 0,
|
||||
progress_percent_precise: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const reason = optionalString(raw.reason);
|
||||
return {
|
||||
is_accessible: raw.is_accessible === true,
|
||||
is_completed: raw.is_completed === true,
|
||||
reason: reason ?? undefined,
|
||||
completed_count: Number(raw.completed_count) || 0,
|
||||
total_count: Number(raw.total_count) || 0,
|
||||
progress_percent: Number(raw.progress_percent) || 0,
|
||||
progress_percent_precise: Number(raw.progress_percent_precise) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLearningActivityLesson(raw: unknown): LearningActivityLesson | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
const moduleId = Number(raw.module_id);
|
||||
if (!Number.isFinite(id) || !Number.isFinite(moduleId)) return null;
|
||||
|
||||
return {
|
||||
id,
|
||||
module_id: moduleId,
|
||||
title: String(raw.title ?? ""),
|
||||
access: normalizeLearningActivityAccess(raw.access),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLearningActivityModule(raw: unknown): LearningActivityModule | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
const lessonsRaw = raw.lessons;
|
||||
const lessons = Array.isArray(lessonsRaw)
|
||||
? lessonsRaw
|
||||
.map((entry) => normalizeLearningActivityLesson(entry))
|
||||
.filter((entry): entry is LearningActivityLesson => entry !== null)
|
||||
: [];
|
||||
|
||||
const programId = Number(raw.program_id);
|
||||
const courseId = Number(raw.course_id);
|
||||
const unitId = Number(raw.unit_id);
|
||||
|
||||
return {
|
||||
id,
|
||||
program_id: Number.isFinite(programId) ? programId : undefined,
|
||||
course_id: Number.isFinite(courseId) ? courseId : undefined,
|
||||
unit_id: Number.isFinite(unitId) ? unitId : undefined,
|
||||
name: String(raw.name ?? ""),
|
||||
access: normalizeLearningActivityAccess(raw.access),
|
||||
lessons,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLearningActivityUnit(raw: unknown): LearningActivityUnit | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
const catalogCourseId = Number(raw.catalog_course_id);
|
||||
if (!Number.isFinite(id) || !Number.isFinite(catalogCourseId)) return null;
|
||||
|
||||
const modulesRaw = raw.modules;
|
||||
const modules = Array.isArray(modulesRaw)
|
||||
? modulesRaw
|
||||
.map((entry) => normalizeLearningActivityModule(entry))
|
||||
.filter((entry): entry is LearningActivityModule => entry !== null)
|
||||
: [];
|
||||
|
||||
return {
|
||||
id,
|
||||
catalog_course_id: catalogCourseId,
|
||||
name: String(raw.name ?? ""),
|
||||
access: normalizeLearningActivityAccess(raw.access),
|
||||
modules,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLearningActivityCourse(raw: unknown): LearningActivityCourse | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
const modulesRaw = raw.modules;
|
||||
const modules = Array.isArray(modulesRaw)
|
||||
? modulesRaw
|
||||
.map((entry) => normalizeLearningActivityModule(entry))
|
||||
.filter((entry): entry is LearningActivityModule => entry !== null)
|
||||
: undefined;
|
||||
|
||||
const unitsRaw = raw.units;
|
||||
const units = Array.isArray(unitsRaw)
|
||||
? unitsRaw
|
||||
.map((entry) => normalizeLearningActivityUnit(entry))
|
||||
.filter((entry): entry is LearningActivityUnit => entry !== null)
|
||||
: undefined;
|
||||
|
||||
const programId = Number(raw.program_id);
|
||||
const catalogCourseId = Number(raw.catalog_course_id);
|
||||
|
||||
return {
|
||||
id,
|
||||
program_id: Number.isFinite(programId) ? programId : undefined,
|
||||
catalog_course_id: Number.isFinite(catalogCourseId) ? catalogCourseId : undefined,
|
||||
name: String(raw.name ?? ""),
|
||||
access: normalizeLearningActivityAccess(raw.access),
|
||||
modules,
|
||||
units,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLearningActivityProgram(raw: unknown): LearningActivityProgram | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
const coursesRaw = raw.courses;
|
||||
const courses = Array.isArray(coursesRaw)
|
||||
? coursesRaw
|
||||
.map((entry) => normalizeLearningActivityCourse(entry))
|
||||
.filter((entry): entry is LearningActivityCourse => entry !== null)
|
||||
: [];
|
||||
|
||||
return {
|
||||
id,
|
||||
name: String(raw.name ?? ""),
|
||||
access: normalizeLearningActivityAccess(raw.access),
|
||||
courses,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCompletedIds(raw: unknown): LearningActivityCompletedIds {
|
||||
if (!isRecord(raw)) {
|
||||
return { lesson_ids: [], module_ids: [], course_ids: [], program_ids: [] };
|
||||
}
|
||||
|
||||
const toIds = (value: unknown) =>
|
||||
Array.isArray(value)
|
||||
? value.map((entry) => Number(entry)).filter((entry) => Number.isFinite(entry))
|
||||
: [];
|
||||
|
||||
return {
|
||||
lesson_ids: toIds(raw.lesson_ids),
|
||||
module_ids: toIds(raw.module_ids),
|
||||
course_ids: toIds(raw.course_ids),
|
||||
program_ids: toIds(raw.program_ids),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUserLearningActivity(raw: unknown): UserLearningActivityData | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const userId = Number(raw.user_id);
|
||||
if (!Number.isFinite(userId)) return null;
|
||||
|
||||
const lmsRaw = isRecord(raw.lms) ? raw.lms : {};
|
||||
const lmsProgressRaw = isRecord(lmsRaw.progress) ? lmsRaw.progress : {};
|
||||
const programsRaw = lmsProgressRaw.programs;
|
||||
const programs = Array.isArray(programsRaw)
|
||||
? programsRaw
|
||||
.map((entry) => normalizeLearningActivityProgram(entry))
|
||||
.filter((entry): entry is LearningActivityProgram => entry !== null)
|
||||
: [];
|
||||
|
||||
const examPrepRaw = isRecord(raw.exam_prep) ? raw.exam_prep : {};
|
||||
const examProgressRaw = isRecord(examPrepRaw.progress) ? examPrepRaw.progress : {};
|
||||
const catalogCoursesRaw = examProgressRaw.catalog_courses;
|
||||
const catalogCourses = Array.isArray(catalogCoursesRaw)
|
||||
? catalogCoursesRaw
|
||||
.map((entry) => normalizeLearningActivityCourse(entry))
|
||||
.filter((entry): entry is LearningActivityCourse => entry !== null)
|
||||
: [];
|
||||
|
||||
const lmsCompletionsRaw = isRecord(lmsRaw.completions) ? lmsRaw.completions : {};
|
||||
const examCompletionsRaw = isRecord(examPrepRaw.completions) ? examPrepRaw.completions : {};
|
||||
|
||||
return {
|
||||
user_id: userId,
|
||||
lms: {
|
||||
completed_ids: normalizeCompletedIds(lmsRaw.completed_ids),
|
||||
progress: { programs },
|
||||
completions: {
|
||||
user_id: Number(lmsCompletionsRaw.user_id) || userId,
|
||||
programs: Array.isArray(lmsCompletionsRaw.programs) ? lmsCompletionsRaw.programs : [],
|
||||
},
|
||||
},
|
||||
exam_prep: {
|
||||
progress: { catalog_courses: catalogCourses },
|
||||
completions: {
|
||||
user_id: Number(examCompletionsRaw.user_id) || userId,
|
||||
catalog_courses: Array.isArray(examCompletionsRaw.catalog_courses)
|
||||
? examCompletionsRaw.catalog_courses
|
||||
: [],
|
||||
},
|
||||
},
|
||||
recent_activity: normalizeUserRecentActivity(raw.recent_activity) ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUserSubscriptionRecord(raw: unknown): UserSubscriptionRecord | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
const userId = Number(raw.user_id);
|
||||
const planId = Number(raw.plan_id);
|
||||
if (!Number.isFinite(id) || !Number.isFinite(userId) || !Number.isFinite(planId)) return null;
|
||||
|
||||
return {
|
||||
id,
|
||||
user_id: userId,
|
||||
plan_id: planId,
|
||||
plan_name: String(raw.plan_name ?? ""),
|
||||
plan_category: String(raw.plan_category ?? ""),
|
||||
starts_at: String(raw.starts_at ?? ""),
|
||||
expires_at: String(raw.expires_at ?? ""),
|
||||
status: String(raw.status ?? ""),
|
||||
payment_reference: String(raw.payment_reference ?? ""),
|
||||
payment_method: String(raw.payment_method ?? ""),
|
||||
auto_renew: raw.auto_renew === true,
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
duration_value: Number(raw.duration_value) || 0,
|
||||
duration_unit: String(raw.duration_unit ?? ""),
|
||||
price: Number(raw.price) || 0,
|
||||
currency: String(raw.currency ?? ""),
|
||||
is_currently_active: raw.is_currently_active === true,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeUserSubscriptionPayment(raw: unknown): UserSubscriptionPayment | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const id = Number(raw.id);
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
const planId = Number(raw.plan_id);
|
||||
const subscriptionId = Number(raw.subscription_id);
|
||||
|
||||
return {
|
||||
id,
|
||||
plan_id: Number.isFinite(planId) ? planId : undefined,
|
||||
plan_name: optionalString(raw.plan_name) ?? undefined,
|
||||
subscription_id: Number.isFinite(subscriptionId) ? subscriptionId : undefined,
|
||||
amount: Number(raw.amount) || 0,
|
||||
currency: String(raw.currency ?? ""),
|
||||
payment_method: optionalString(raw.payment_method) ?? undefined,
|
||||
status: String(raw.status ?? ""),
|
||||
paid_at: optionalString(raw.paid_at),
|
||||
expires_at: optionalString(raw.expires_at),
|
||||
created_at: String(raw.created_at ?? ""),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUserSubscriptions(raw: unknown): UserSubscriptionsData | null {
|
||||
if (!isRecord(raw)) return null;
|
||||
const userId = Number(raw.user_id);
|
||||
if (!Number.isFinite(userId)) return null;
|
||||
|
||||
const activeByCategoryRaw = isRecord(raw.active_by_category) ? raw.active_by_category : {};
|
||||
const active_by_category: Record<string, boolean> = {};
|
||||
for (const [key, value] of Object.entries(activeByCategoryRaw)) {
|
||||
active_by_category[key] = value === true;
|
||||
}
|
||||
|
||||
const mapSubscriptions = (value: unknown) =>
|
||||
Array.isArray(value)
|
||||
? value
|
||||
.map((entry) => normalizeUserSubscriptionRecord(entry))
|
||||
.filter((entry): entry is UserSubscriptionRecord => entry !== null)
|
||||
: [];
|
||||
|
||||
const payments = Array.isArray(raw.payments)
|
||||
? raw.payments
|
||||
.map((entry) => normalizeUserSubscriptionPayment(entry))
|
||||
.filter((entry): entry is UserSubscriptionPayment => entry !== null)
|
||||
: [];
|
||||
|
||||
return {
|
||||
user_id: userId,
|
||||
display_status: String(raw.display_status ?? ""),
|
||||
has_active_subscription: raw.has_active_subscription === true,
|
||||
active_by_category,
|
||||
active_subscriptions: mapSubscriptions(raw.active_subscriptions),
|
||||
subscriptions: mapSubscriptions(raw.subscriptions),
|
||||
payments,
|
||||
};
|
||||
}
|
||||
|
||||
/** Query params for GET /users (RFC3339 for created_*; subscription_status: ACTIVE | PENDING | Unsubscribed). */
|
||||
export interface GetUsersParams {
|
||||
|
|
@ -59,13 +445,71 @@ export const updateUserStatus = (payload: UpdateUserStatusRequest) =>
|
|||
http.patch("/user/status", payload);
|
||||
|
||||
export const getUserById = (id: number) =>
|
||||
http.get<UserProfileResponse>(`/user/single/${id}`);
|
||||
http.get<UserProfileResponse>(`/user/single/${id}`).then((res) => {
|
||||
const body = res.data;
|
||||
const user = normalizeUserProfile(body?.data);
|
||||
if (!user) {
|
||||
throw new Error("Invalid user profile response");
|
||||
}
|
||||
return {
|
||||
...res,
|
||||
data: {
|
||||
...body,
|
||||
data: user,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const getUserRecentActivity = (userId: number) =>
|
||||
http.get<UserRecentActivityResponse>(`/admin/users/${userId}/recent-activity`);
|
||||
http.get<UserRecentActivityResponse>(`/admin/users/${userId}/recent-activity`).then((res) => {
|
||||
const body = res.data;
|
||||
const activity = normalizeUserRecentActivity(body?.data);
|
||||
if (!activity) {
|
||||
throw new Error("Invalid recent activity response");
|
||||
}
|
||||
return {
|
||||
...res,
|
||||
data: {
|
||||
...body,
|
||||
data: activity,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const getUserLearningActivity = (userId: number) =>
|
||||
http.get<UserLearningActivityResponse>(`/admin/users/${userId}/learning-activity`).then((res) => {
|
||||
const body = res.data;
|
||||
const activity = normalizeUserLearningActivity(body?.data);
|
||||
if (!activity) {
|
||||
throw new Error("Invalid learning activity response");
|
||||
}
|
||||
return {
|
||||
...res,
|
||||
data: {
|
||||
...body,
|
||||
data: activity,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const getUserSubscriptions = (userId: number) =>
|
||||
http.get<UserSubscriptionsResponse>(`/admin/users/${userId}/subscriptions`).then((res) => {
|
||||
const body = res.data;
|
||||
const subscriptions = normalizeUserSubscriptions(body?.data);
|
||||
if (!subscriptions) {
|
||||
throw new Error("Invalid user subscriptions response");
|
||||
}
|
||||
return {
|
||||
...res,
|
||||
data: {
|
||||
...body,
|
||||
data: subscriptions,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const getMyProfile = () =>
|
||||
http.get<UserProfileResponse>("/team/me");
|
||||
http.get<GetTeamMeResponse>("/team/me");
|
||||
|
||||
// Best-guess API for creating a new user (admin-side).
|
||||
// Adjust payload shape or endpoint if backend differs.
|
||||
|
|
|
|||
|
|
@ -68,6 +68,10 @@ import { AboutPage } from "../pages/AboutPage";
|
|||
import { TermsPage } from "../pages/TermsPage";
|
||||
import { PrivacyPage } from "../pages/PrivacyPage";
|
||||
import { AccountDeletionPage } from "../pages/AccountDeletionPage";
|
||||
import { FaqsPage } from "../pages/faqs/FaqsPage";
|
||||
import { EditFaqPage } from "../pages/faqs/EditFaqPage";
|
||||
import { AppReviewsPage } from "../pages/ratings/AppReviewsPage";
|
||||
import { PersonasPage } from "../pages/personas/PersonasPage";
|
||||
|
||||
export function AppRoutes() {
|
||||
return (
|
||||
|
|
@ -287,6 +291,14 @@ export function AppRoutes() {
|
|||
<Route path="/payments" element={<PaymentsPage />} />
|
||||
<Route path="/user-log" element={<UserLogPage />} />
|
||||
<Route path="/issues" element={<IssuesPage />} />
|
||||
<Route path="/help/faqs" element={<FaqsPage />} />
|
||||
<Route path="/help/faqs/:id/edit" element={<EditFaqPage />} />
|
||||
<Route path="/app-reviews" element={<AppReviewsPage />} />
|
||||
<Route path="/admin/app-reviews" element={<AppReviewsPage />} />
|
||||
<Route path="/operations/app-reviews" element={<AppReviewsPage />} />
|
||||
<Route path="/ratings" element={<AppReviewsPage />} />
|
||||
<Route path="/personas" element={<PersonasPage />} />
|
||||
<Route path="/admin/personas" element={<PersonasPage />} />
|
||||
<Route path="/analytics" element={<AnalyticsPage />} />
|
||||
|
||||
<Route path="/team" element={<TeamManagementPage />} />
|
||||
|
|
|
|||
102
src/components/filters/AdminFiltersPanel.tsx
Normal file
102
src/components/filters/AdminFiltersPanel.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import { ChevronDown, SlidersHorizontal, X } from "lucide-react"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { Button } from "../ui/button"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
export type AdminFiltersPanelProps = {
|
||||
search?: ReactNode
|
||||
children?: ReactNode
|
||||
/** Renders in place of the show/hide toggle; keeps filters always visible. */
|
||||
actions?: ReactNode
|
||||
activeFilterCount?: number
|
||||
onClearFilters?: () => void
|
||||
clearLabel?: string
|
||||
defaultOpen?: boolean
|
||||
className?: string
|
||||
footer?: ReactNode
|
||||
summary?: ReactNode
|
||||
}
|
||||
|
||||
export function AdminFiltersPanel({
|
||||
search,
|
||||
children,
|
||||
actions,
|
||||
activeFilterCount = 0,
|
||||
onClearFilters,
|
||||
clearLabel = "Clear filters",
|
||||
defaultOpen = false,
|
||||
className,
|
||||
footer,
|
||||
summary,
|
||||
}: AdminFiltersPanelProps) {
|
||||
const [open, setOpen] = useState(defaultOpen || activeFilterCount > 0)
|
||||
const inlineActions = Boolean(actions)
|
||||
|
||||
useEffect(() => {
|
||||
if (!inlineActions && activeFilterCount > 0) {
|
||||
setOpen(true)
|
||||
}
|
||||
}, [activeFilterCount, inlineActions])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-xl border border-grayScale-100 bg-white shadow-none",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3 p-4">
|
||||
{search ? <div className="min-w-[200px] flex-1">{search}</div> : null}
|
||||
{inlineActions ? (
|
||||
<div className="h-9 shrink-0">{actions}</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 shrink-0 gap-2"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<SlidersHorizontal className="h-4 w-4" />
|
||||
{open ? "Hide filters" : "Show filters"}
|
||||
{activeFilterCount > 0 ? (
|
||||
<Badge variant="default" className="px-1.5 py-0 text-[10px]">
|
||||
{activeFilterCount}
|
||||
</Badge>
|
||||
) : null}
|
||||
<ChevronDown
|
||||
className={cn("h-4 w-4 transition-transform", open && "rotate-180")}
|
||||
/>
|
||||
</Button>
|
||||
)}
|
||||
{activeFilterCount > 0 && onClearFilters ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 shrink-0 gap-1 text-grayScale-500"
|
||||
onClick={onClearFilters}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
{clearLabel}
|
||||
</Button>
|
||||
) : null}
|
||||
{summary ? <div className="ml-auto text-xs text-grayScale-500">{summary}</div> : null}
|
||||
</div>
|
||||
{inlineActions ? (
|
||||
footer ? (
|
||||
<div className="border-t border-grayScale-100 px-4 pb-3 pt-2 text-xs text-grayScale-400">
|
||||
{footer}
|
||||
</div>
|
||||
) : null
|
||||
) : open ? (
|
||||
<div className="space-y-3 border-t border-grayScale-100 px-4 pb-4 pt-3">
|
||||
{children}
|
||||
{footer ? <div className="text-xs text-grayScale-400">{footer}</div> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
96
src/components/notifications/NotificationDeleteDialog.tsx
Normal file
96
src/components/notifications/NotificationDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useState } from "react"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { deleteNotification } from "../../api/notifications.api"
|
||||
import { Button } from "../ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog"
|
||||
import { getNotificationTitle, type Notification } from "../../types/notification.types"
|
||||
|
||||
type NotificationDeleteDialogProps = {
|
||||
notification: Notification | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onDeleted?: (id: string) => void
|
||||
}
|
||||
|
||||
export function NotificationDeleteDialog({
|
||||
notification,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDeleted,
|
||||
}: NotificationDeleteDialogProps) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !deleting) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!notification) return
|
||||
|
||||
setDeleting(true)
|
||||
try {
|
||||
const response = await deleteNotification(notification.id)
|
||||
toast.success(response.message || "Notification deleted")
|
||||
onOpenChange(false)
|
||||
onDeleted?.(notification.id)
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg =
|
||||
(e as { response?: { data?: { message?: string; error?: string } } })?.response
|
||||
?.data?.error ??
|
||||
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||
"Failed to delete notification"
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||
Delete notification?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-left text-grayScale-600">
|
||||
This permanently removes the notification from your inbox.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{notification ? (
|
||||
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||
<p className="line-clamp-2 text-sm font-semibold text-grayScale-900">
|
||||
{getNotificationTitle(notification) || "Notification"}
|
||||
</p>
|
||||
<p className="text-xs text-grayScale-500">#{notification.id}</p>
|
||||
</div>
|
||||
) : null}
|
||||
<DialogFooter className="gap-2 sm:gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={deleting}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleting || !notification}
|
||||
onClick={() => void handleConfirm()}
|
||||
>
|
||||
{deleting ? "Deleting…" : "Delete"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import {
|
|||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog"
|
||||
|
|
@ -26,6 +27,7 @@ type NotificationDetailDialogProps = {
|
|||
loading?: boolean
|
||||
error?: boolean
|
||||
onRetry?: () => void
|
||||
onDelete?: () => void
|
||||
}
|
||||
|
||||
export function NotificationDetailDialog({
|
||||
|
|
@ -35,6 +37,7 @@ export function NotificationDetailDialog({
|
|||
loading = false,
|
||||
error = false,
|
||||
onRetry,
|
||||
onDelete,
|
||||
}: NotificationDetailDialogProps) {
|
||||
const config = notification
|
||||
? NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
||||
|
|
@ -161,6 +164,14 @@ export function NotificationDetailDialog({
|
|||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{onDelete ? (
|
||||
<DialogFooter className="gap-2 sm:gap-2">
|
||||
<Button variant="destructive" onClick={onDelete}>
|
||||
Delete notification
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
|
|
|
|||
132
src/components/profile/ProfileAvatarUpload.tsx
Normal file
132
src/components/profile/ProfileAvatarUpload.tsx
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import { useCallback, useRef, useState, type ChangeEvent } from "react"
|
||||
import { Camera } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { uploadImageFile } from "../../api/files.api"
|
||||
import { updateTeamMe } from "../../api/team.api"
|
||||
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { TeamMeProfile } from "../../types/team.types"
|
||||
|
||||
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp"])
|
||||
|
||||
function isAllowedImageFile(file: File): boolean {
|
||||
if (ALLOWED_IMAGE_TYPES.has(file.type)) return true
|
||||
const name = file.name.toLowerCase()
|
||||
return /\.(jpe?g|png|webp)$/.test(name)
|
||||
}
|
||||
|
||||
type ProfileAvatarUploadProps = {
|
||||
avatarUrl?: string | null
|
||||
initials: string
|
||||
onProfileUpdate: (profile: TeamMeProfile) => void
|
||||
}
|
||||
|
||||
export function ProfileAvatarUpload({
|
||||
avatarUrl,
|
||||
initials,
|
||||
onProfileUpdate,
|
||||
}: ProfileAvatarUploadProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
|
||||
const processFile = useCallback(
|
||||
async (file: File) => {
|
||||
if (uploading) return
|
||||
if (!isAllowedImageFile(file)) {
|
||||
toast.error("Please use a JPG, PNG, or WEBP image.")
|
||||
return
|
||||
}
|
||||
if (file.size > MAX_IMAGE_BYTES) {
|
||||
toast.error("Image is too large", { description: "Maximum size is 5 MB." })
|
||||
return
|
||||
}
|
||||
|
||||
setUploading(true)
|
||||
try {
|
||||
const uploadRes = await uploadImageFile(file)
|
||||
const uploadedUrl = uploadRes.data?.data?.url?.trim()
|
||||
if (!uploadedUrl) throw new Error("Upload did not return a file URL")
|
||||
|
||||
const updateRes = await updateTeamMe({ profile_picture_url: uploadedUrl })
|
||||
onProfileUpdate(updateRes.data.data)
|
||||
toast.success(updateRes.data.message || "Profile picture updated")
|
||||
} catch (err: unknown) {
|
||||
console.error(err)
|
||||
const uploadMsg =
|
||||
(err as { response?: { data?: { message?: string } } })?.response?.data
|
||||
?.message
|
||||
toast.error(uploadMsg ?? "Failed to update profile picture")
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
},
|
||||
[onProfileUpdate, uploading],
|
||||
)
|
||||
|
||||
const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ""
|
||||
if (file) void processFile(file)
|
||||
}
|
||||
|
||||
const trimmedUrl = avatarUrl?.trim()
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
|
||||
className="sr-only"
|
||||
onChange={handleFileInputChange}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Upload profile picture"
|
||||
disabled={uploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
"group relative h-24 w-24 shrink-0 overflow-hidden rounded-full border-4 border-white shadow-sm",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2",
|
||||
uploading && "cursor-wait",
|
||||
)}
|
||||
>
|
||||
{trimmedUrl ? (
|
||||
<img
|
||||
src={trimmedUrl}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex h-full w-full items-center justify-center bg-brand-100 text-2xl font-bold text-brand-700">
|
||||
{initials || "?"}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inset-0 flex items-center justify-center rounded-full bg-black/45",
|
||||
"opacity-0 transition-opacity duration-200 ease-out",
|
||||
"group-hover:opacity-100 group-focus-visible:opacity-100",
|
||||
uploading && "opacity-100",
|
||||
)}
|
||||
>
|
||||
{uploading ? (
|
||||
<SpinnerIcon className="h-6 w-6 text-white" />
|
||||
) : (
|
||||
<Camera
|
||||
className={cn(
|
||||
"h-6 w-6 text-white",
|
||||
"scale-75 opacity-0 transition-all duration-200 ease-out",
|
||||
"group-hover:scale-100 group-hover:opacity-100",
|
||||
"group-focus-visible:scale-100 group-focus-visible:opacity-100",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
@ -5,13 +5,16 @@ import {
|
|||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleAlert,
|
||||
CircleHelp,
|
||||
ClipboardList,
|
||||
CreditCard,
|
||||
LayoutDashboard,
|
||||
LogOut,
|
||||
UserCircle2,
|
||||
Users,
|
||||
UsersRound,
|
||||
Settings,
|
||||
Star,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { type ComponentType, useEffect, useState } from "react";
|
||||
|
|
@ -19,6 +22,10 @@ import { NavLink } from "react-router-dom";
|
|||
import { cn } from "../../lib/utils";
|
||||
import { BrandLogo } from "../brand/BrandLogo";
|
||||
import { getUnreadCount } from "../../api/notifications.api";
|
||||
import { useTeamPermissions } from "../../hooks/useTeamPermissions";
|
||||
import { hasFaqPermission } from "../../lib/faqPermissions";
|
||||
import { hasRatingsPermission } from "../../lib/ratingsPermissions";
|
||||
import { hasPersonaPermission } from "../../lib/personasPermissions";
|
||||
import { SidebarNavGroup } from "./SidebarNavGroup";
|
||||
|
||||
type NavLinkItem = {
|
||||
|
|
@ -26,6 +33,7 @@ type NavLinkItem = {
|
|||
label: string;
|
||||
to: string;
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
permission?: string;
|
||||
};
|
||||
|
||||
type NavGroupItem = {
|
||||
|
|
@ -77,6 +85,13 @@ const navEntries: NavEntry[] = [
|
|||
{ label: "Question types", to: "/new-content/question-types" },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "link",
|
||||
label: "Personas",
|
||||
to: "/personas",
|
||||
icon: UsersRound,
|
||||
permission: "personas.list",
|
||||
},
|
||||
|
||||
{ kind: "section", label: "Communications" },
|
||||
{
|
||||
|
|
@ -96,6 +111,20 @@ const navEntries: NavEntry[] = [
|
|||
{ kind: "link", label: "Payments", to: "/payments", icon: CreditCard },
|
||||
{ kind: "link", label: "User activity log", to: "/user-log", icon: ClipboardList },
|
||||
{ kind: "link", label: "Issue reports", to: "/issues", icon: CircleAlert },
|
||||
{
|
||||
kind: "link",
|
||||
label: "FAQs",
|
||||
to: "/help/faqs",
|
||||
icon: CircleHelp,
|
||||
permission: "faqs.list",
|
||||
},
|
||||
{
|
||||
kind: "link",
|
||||
label: "App reviews",
|
||||
to: "/app-reviews",
|
||||
icon: Star,
|
||||
permission: "ratings.list_by_target",
|
||||
},
|
||||
|
||||
{ kind: "section", label: "Account" },
|
||||
{ kind: "link", label: "Profile", to: "/profile", icon: UserCircle2 },
|
||||
|
|
@ -115,6 +144,7 @@ export function Sidebar({
|
|||
onToggleCollapse,
|
||||
onClose,
|
||||
}: SidebarProps) {
|
||||
const { permissions, hasPermission, loading: permissionsLoading } = useTeamPermissions();
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -226,6 +256,40 @@ export function Sidebar({
|
|||
);
|
||||
}
|
||||
|
||||
if (entry.kind === "link") {
|
||||
if (
|
||||
entry.permission === "faqs.list" &&
|
||||
!permissionsLoading &&
|
||||
!hasFaqPermission("faqs.list", permissions)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
entry.permission === "ratings.list_by_target" &&
|
||||
!permissionsLoading &&
|
||||
!hasRatingsPermission("ratings.list_by_target", permissions)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
entry.permission === "personas.list" &&
|
||||
!permissionsLoading &&
|
||||
!hasPersonaPermission("personas.list", permissions)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
entry.permission &&
|
||||
entry.permission !== "faqs.list" &&
|
||||
entry.permission !== "ratings.list_by_target" &&
|
||||
entry.permission !== "personas.list" &&
|
||||
!permissionsLoading &&
|
||||
!hasPermission(entry.permission)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.kind === "group") {
|
||||
const isNotifications = entry.basePath === "/notifications";
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { Bell, BellOff, CheckCheck, Mail, MailOpen } from "lucide-react"
|
||||
import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Badge } from "../ui/badge"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
|
@ -8,6 +8,7 @@ import { SpinnerIcon } from "../ui/spinner-icon"
|
|||
import { getNotificationById } from "../../api/notifications.api"
|
||||
import { useNotifications } from "../../hooks/useNotifications"
|
||||
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
|
||||
import { NotificationDeleteDialog } from "../notifications/NotificationDeleteDialog"
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||
formatNotificationTimestamp,
|
||||
|
|
@ -20,11 +21,13 @@ function NotificationItem({
|
|||
onOpen,
|
||||
onMarkRead,
|
||||
onMarkUnread,
|
||||
onDelete,
|
||||
}: {
|
||||
notification: Notification
|
||||
onOpen: (notification: Notification) => void
|
||||
onMarkRead: (id: string) => void
|
||||
onMarkUnread: (id: string) => void
|
||||
onDelete: (notification: Notification) => void
|
||||
}) {
|
||||
const cfg = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
|
||||
const Icon = cfg.icon
|
||||
|
|
@ -86,6 +89,17 @@ function NotificationItem({
|
|||
<MailOpen className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="hidden shrink-0 self-center rounded-md p-1.5 text-destructive hover:bg-destructive/10 group-hover:block"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(notification)
|
||||
}}
|
||||
aria-label="Delete notification"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
@ -97,6 +111,7 @@ export function NotificationDropdown() {
|
|||
const [detailError, setDetailError] = useState(false)
|
||||
const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null)
|
||||
const [selectedNotificationId, setSelectedNotificationId] = useState<string | null>(null)
|
||||
const [notificationPendingDelete, setNotificationPendingDelete] = useState<Notification | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
|
|
@ -106,6 +121,7 @@ export function NotificationDropdown() {
|
|||
markOneRead,
|
||||
markOneUnread,
|
||||
markAllAsRead,
|
||||
refresh,
|
||||
} = useNotifications()
|
||||
|
||||
const loadNotificationDetail = useCallback(async (id: string, markReadIfNeeded: boolean) => {
|
||||
|
|
@ -142,6 +158,16 @@ export function NotificationDropdown() {
|
|||
[loadNotificationDetail],
|
||||
)
|
||||
|
||||
const handleNotificationDeleted = useCallback((id: string) => {
|
||||
if (selectedNotificationId === id) {
|
||||
setDetailOpen(false)
|
||||
setSelectedNotification(null)
|
||||
setSelectedNotificationId(null)
|
||||
}
|
||||
setNotificationPendingDelete(null)
|
||||
refresh()
|
||||
}, [selectedNotificationId, refresh])
|
||||
|
||||
useEffect(() => {
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
|
|
@ -213,6 +239,10 @@ export function NotificationDropdown() {
|
|||
onOpen={handleOpenNotification}
|
||||
onMarkRead={markOneRead}
|
||||
onMarkUnread={markOneUnread}
|
||||
onDelete={(notification) => {
|
||||
setOpen(false)
|
||||
setNotificationPendingDelete(notification)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -246,6 +276,20 @@ export function NotificationDropdown() {
|
|||
? () => void loadNotificationDetail(selectedNotificationId, false)
|
||||
: undefined
|
||||
}
|
||||
onDelete={
|
||||
selectedNotification
|
||||
? () => setNotificationPendingDelete(selectedNotification)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<NotificationDeleteDialog
|
||||
notification={notificationPendingDelete}
|
||||
open={notificationPendingDelete !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setNotificationPendingDelete(null)
|
||||
}}
|
||||
onDeleted={handleNotificationDeleted}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
|
|
|
|||
54
src/components/ui/toggle-switch.tsx
Normal file
54
src/components/ui/toggle-switch.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { cn } from "../../lib/utils"
|
||||
|
||||
export type ToggleSwitchProps = {
|
||||
checked: boolean
|
||||
onCheckedChange?: () => void
|
||||
disabled?: boolean
|
||||
"aria-label"?: string
|
||||
className?: string
|
||||
variant?: "brand" | "plain"
|
||||
}
|
||||
|
||||
export function ToggleSwitch({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
disabled = false,
|
||||
"aria-label": ariaLabel,
|
||||
className,
|
||||
variant = "brand",
|
||||
}: ToggleSwitchProps) {
|
||||
const isBrand = variant === "brand"
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onClick={onCheckedChange}
|
||||
className={cn(
|
||||
"relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-all duration-200",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
||||
isBrand && "border p-0.5",
|
||||
isBrand
|
||||
? checked
|
||||
? "border-brand-500 bg-brand-500 shadow-[0_4px_12px_rgba(168,85,247,0.3)]"
|
||||
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80"
|
||||
: checked
|
||||
? "bg-brand-500"
|
||||
: "bg-grayScale-200",
|
||||
disabled && "cursor-not-allowed opacity-60",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform duration-200 ease-out",
|
||||
isBrand ? "shadow-md ring-0" : "shadow-sm",
|
||||
checked ? "translate-x-4" : isBrand ? "translate-x-0" : "translate-x-0.5",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,18 +1,13 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { getPersonas } from "../api/personas.api"
|
||||
import {
|
||||
mapPersonaToCard,
|
||||
unwrapPersonasList,
|
||||
type PersonaCardModel,
|
||||
} from "../lib/personaDisplay"
|
||||
import { listActivePersonasForPicker } from "../api/personas.api"
|
||||
import { mapPersonaToCard, type PersonaCardModel } from "../lib/personaDisplay"
|
||||
|
||||
type UseActivePersonasOptions = {
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
||||
const { limit = 50, offset = 0 } = options
|
||||
const { limit = 200 } = options
|
||||
const [personas, setPersonas] = useState<PersonaCardModel[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
|
@ -21,8 +16,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
|||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await getPersonas({ limit, offset })
|
||||
const list = unwrapPersonasList(res).filter((p) => p.is_active)
|
||||
const list = await listActivePersonasForPicker(limit)
|
||||
setPersonas(list.map(mapPersonaToCard))
|
||||
} catch (e: unknown) {
|
||||
const msg =
|
||||
|
|
@ -33,7 +27,7 @@ export function useActivePersonas(options: UseActivePersonasOptions = {}) {
|
|||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [limit, offset])
|
||||
}, [limit])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
|
|
|
|||
39
src/hooks/useFaqPermissions.ts
Normal file
39
src/hooks/useFaqPermissions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { useMemo } from "react"
|
||||
import { hasFaqPermission } from "../lib/faqPermissions"
|
||||
import { useTeamPermissions } from "./useTeamPermissions"
|
||||
|
||||
export function useFaqPermissions() {
|
||||
const { permissions, loading, reload } = useTeamPermissions()
|
||||
|
||||
const canList = useMemo(
|
||||
() => hasFaqPermission("faqs.list", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canGet = useMemo(
|
||||
() => hasFaqPermission("faqs.get", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canCreate = useMemo(
|
||||
() => hasFaqPermission("faqs.create", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canUpdate = useMemo(
|
||||
() => hasFaqPermission("faqs.update", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canDelete = useMemo(
|
||||
() => hasFaqPermission("faqs.delete", permissions),
|
||||
[permissions],
|
||||
)
|
||||
|
||||
return {
|
||||
permissions,
|
||||
loading,
|
||||
reload,
|
||||
canList,
|
||||
canGet,
|
||||
canCreate,
|
||||
canUpdate,
|
||||
canDelete,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { useEffect, useState, useCallback, useRef } from "react"
|
||||
import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead } from "../api/notifications.api"
|
||||
import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, deleteNotification } from "../api/notifications.api"
|
||||
import type { Notification } from "../types/notification.types"
|
||||
|
||||
const MAX_DROPDOWN = 5
|
||||
|
|
@ -167,6 +167,21 @@ export function useNotifications() {
|
|||
}
|
||||
}, [fetchData])
|
||||
|
||||
const deleteOne = useCallback(async (id: string) => {
|
||||
const removed = notifications.find((n) => n.id === id)
|
||||
setNotifications((prev) => prev.filter((n) => n.id !== id))
|
||||
if (removed && !removed.is_read) {
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1))
|
||||
}
|
||||
dispatchUpdate()
|
||||
try {
|
||||
await deleteNotification(id)
|
||||
} catch {
|
||||
await fetchData()
|
||||
throw new Error("delete failed")
|
||||
}
|
||||
}, [notifications, fetchData])
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
|
@ -178,6 +193,7 @@ export function useNotifications() {
|
|||
markOneRead,
|
||||
markOneUnread,
|
||||
markAllAsRead,
|
||||
deleteOne,
|
||||
refresh,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
39
src/hooks/usePersonaPermissions.ts
Normal file
39
src/hooks/usePersonaPermissions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { useMemo } from "react"
|
||||
import { hasPersonaPermission } from "../lib/personasPermissions"
|
||||
import { useTeamPermissions } from "./useTeamPermissions"
|
||||
|
||||
export function usePersonaPermissions() {
|
||||
const { permissions, loading, reload } = useTeamPermissions()
|
||||
|
||||
const canList = useMemo(
|
||||
() => hasPersonaPermission("personas.list", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canGet = useMemo(
|
||||
() => hasPersonaPermission("personas.get", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canCreate = useMemo(
|
||||
() => hasPersonaPermission("personas.create", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canUpdate = useMemo(
|
||||
() => hasPersonaPermission("personas.update", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canDelete = useMemo(
|
||||
() => hasPersonaPermission("personas.delete", permissions),
|
||||
[permissions],
|
||||
)
|
||||
|
||||
return {
|
||||
permissions,
|
||||
loading,
|
||||
reload,
|
||||
canList,
|
||||
canGet,
|
||||
canCreate,
|
||||
canUpdate,
|
||||
canDelete,
|
||||
}
|
||||
}
|
||||
24
src/hooks/useRatingsPermissions.ts
Normal file
24
src/hooks/useRatingsPermissions.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { useMemo } from "react"
|
||||
import { hasRatingsPermission } from "../lib/ratingsPermissions"
|
||||
import { useTeamPermissions } from "./useTeamPermissions"
|
||||
|
||||
export function useRatingsPermissions() {
|
||||
const { permissions, loading, reload } = useTeamPermissions()
|
||||
|
||||
const canList = useMemo(
|
||||
() => hasRatingsPermission("ratings.list_by_target", permissions),
|
||||
[permissions],
|
||||
)
|
||||
const canSummary = useMemo(
|
||||
() => hasRatingsPermission("ratings.summary", permissions),
|
||||
[permissions],
|
||||
)
|
||||
|
||||
return {
|
||||
permissions,
|
||||
loading,
|
||||
reload,
|
||||
canList,
|
||||
canSummary,
|
||||
}
|
||||
}
|
||||
32
src/hooks/useTeamPermissions.ts
Normal file
32
src/hooks/useTeamPermissions.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { getMyProfile } from "../api/users.api"
|
||||
import type { TeamMeProfile } from "../types/team.types"
|
||||
|
||||
export function useTeamPermissions() {
|
||||
const [permissions, setPermissions] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await getMyProfile()
|
||||
const profile = res.data?.data as TeamMeProfile & { permissions?: string[] }
|
||||
setPermissions(Array.isArray(profile?.permissions) ? profile.permissions : [])
|
||||
} catch {
|
||||
setPermissions([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const hasPermission = useCallback(
|
||||
(key: string) => permissions.includes(key),
|
||||
[permissions],
|
||||
)
|
||||
|
||||
return { permissions, loading, hasPermission, reload: load }
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { getTeamMemberById } from "../api/team.api"
|
||||
import { getUserById } from "../api/users.api"
|
||||
import { TEAM_ROLE_OPTIONS, formatTeamRoleLabel } from "./teamRoles"
|
||||
import type { TeamMember } from "../types/team.types"
|
||||
import type { TeamMember, TeamMemberDetail } from "../types/team.types"
|
||||
import type { UserProfileData } from "../types/user.types"
|
||||
|
||||
const TEAM_ROLE_VALUES = new Set(
|
||||
|
|
@ -51,7 +51,12 @@ export function resolveActorKind(actorRole: string | null | undefined): ActorPro
|
|||
return null
|
||||
}
|
||||
|
||||
function teamMemberToProfile(member: TeamMember): ActorProfile {
|
||||
function teamMemberToProfile(
|
||||
member: Pick<
|
||||
TeamMember | TeamMemberDetail,
|
||||
"id" | "first_name" | "last_name" | "email" | "team_role" | "status" | "email_verified" | "created_at"
|
||||
>,
|
||||
): ActorProfile {
|
||||
return {
|
||||
kind: "team",
|
||||
id: member.id,
|
||||
|
|
|
|||
22
src/lib/adminFilterUtils.ts
Normal file
22
src/lib/adminFilterUtils.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
type FilterEntry = {
|
||||
value: unknown
|
||||
defaultValue?: unknown
|
||||
}
|
||||
|
||||
function isActiveFilterValue(value: unknown, defaultValue: unknown): boolean {
|
||||
if (value === defaultValue) return false
|
||||
if (value == null) return false
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return false
|
||||
if (trimmed === "all" || trimmed === "All") return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Count how many filters differ from their default / empty state. */
|
||||
export function countActiveFilters(entries: FilterEntry[]): number {
|
||||
return entries.filter(({ value, defaultValue = "" }) =>
|
||||
isActiveFilterValue(value, defaultValue),
|
||||
).length
|
||||
}
|
||||
39
src/lib/faqDisplay.ts
Normal file
39
src/lib/faqDisplay.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import type { FAQ, FAQStatus } from "../types/faq.types"
|
||||
|
||||
export function faqStatusBadgeVariant(status: string): "success" | "secondary" {
|
||||
const normalized = status.toUpperCase()
|
||||
if (normalized === "ACTIVE") return "success"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export function faqStatusLabel(status: FAQStatus | string): string {
|
||||
const normalized = status.toUpperCase()
|
||||
if (normalized === "ACTIVE") return "Published"
|
||||
if (normalized === "INACTIVE") return "Draft"
|
||||
return status
|
||||
}
|
||||
|
||||
export function formatFaqDate(raw: string | null | undefined): string {
|
||||
if (raw == null || String(raw).trim() === "") {
|
||||
return "—"
|
||||
}
|
||||
const text = String(raw)
|
||||
const parsed = new Date(text)
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return text.split(" +")[0]?.trim() || text
|
||||
}
|
||||
return parsed.toLocaleString(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
})
|
||||
}
|
||||
|
||||
export function deriveFaqCategories(faqs: FAQ[]): string[] {
|
||||
return [...new Set(faqs.map((f) => f.category).filter(Boolean) as string[])].sort()
|
||||
}
|
||||
|
||||
export function suggestNextDisplayOrder(faqs: FAQ[]): number {
|
||||
if (faqs.length === 0) return 1
|
||||
const max = Math.max(...faqs.map((f) => f.display_order ?? 0))
|
||||
return max + 1
|
||||
}
|
||||
12
src/lib/faqErrors.ts
Normal file
12
src/lib/faqErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export function getFaqApiErrorMessage(error: unknown, fallback: string): string {
|
||||
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||
?.response?.data
|
||||
return data?.error ?? data?.message ?? fallback
|
||||
}
|
||||
|
||||
export function isFaqForbiddenError(error: unknown): boolean {
|
||||
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||
}
|
||||
|
||||
export const FAQ_FORBIDDEN_MESSAGE =
|
||||
"You don't have permission to access this resource"
|
||||
26
src/lib/faqPermissions.ts
Normal file
26
src/lib/faqPermissions.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
/** Team roles whose JWT maps to ADMIN/SUPER_ADMIN and bypass FAQ permission checks. */
|
||||
const FAQ_BYPASS_TEAM_ROLES = new Set([
|
||||
"SUPER_ADMIN",
|
||||
"ADMIN",
|
||||
"CONTENT_MANAGER",
|
||||
"FINANCE",
|
||||
"HR",
|
||||
"ANALYST",
|
||||
])
|
||||
|
||||
export function getSessionTeamRole(): string {
|
||||
return localStorage.getItem("role")?.trim() ?? ""
|
||||
}
|
||||
|
||||
export function hasFaqRoleBypass(): boolean {
|
||||
const role = getSessionTeamRole().toUpperCase()
|
||||
return FAQ_BYPASS_TEAM_ROLES.has(role)
|
||||
}
|
||||
|
||||
export function hasFaqPermission(
|
||||
permission: string,
|
||||
permissions: string[],
|
||||
): boolean {
|
||||
if (hasFaqRoleBypass()) return true
|
||||
return permissions.includes(permission)
|
||||
}
|
||||
|
|
@ -41,6 +41,26 @@ export function mapPersonaToCard(persona: PersonaListItem): PersonaCardModel {
|
|||
}
|
||||
}
|
||||
|
||||
export function formatPersonaDate(dateStr: string | null | undefined): string {
|
||||
if (!dateStr?.trim()) return "—"
|
||||
const d = new Date(dateStr)
|
||||
if (Number.isNaN(d.getTime())) return dateStr
|
||||
return d.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
export function personaStatusLabel(isActive: boolean): string {
|
||||
return isActive ? "Active" : "Inactive"
|
||||
}
|
||||
|
||||
export function personaGenderLabel(gender: string | null | undefined): string {
|
||||
const value = gender?.trim()
|
||||
return value ? value : "—"
|
||||
}
|
||||
|
||||
export function unwrapPersonasList(
|
||||
res: { data?: GetPersonasResponse & { Data?: GetPersonasResponse["data"] } },
|
||||
): PersonaListItem[] {
|
||||
|
|
|
|||
12
src/lib/personasErrors.ts
Normal file
12
src/lib/personasErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export function getPersonaApiErrorMessage(error: unknown, fallback: string): string {
|
||||
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||
?.response?.data
|
||||
return data?.error ?? data?.message ?? fallback
|
||||
}
|
||||
|
||||
export function isPersonaForbiddenError(error: unknown): boolean {
|
||||
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||
}
|
||||
|
||||
export const PERSONAS_FORBIDDEN_MESSAGE =
|
||||
"You don't have permission to access the persona catalog"
|
||||
18
src/lib/personasPermissions.ts
Normal file
18
src/lib/personasPermissions.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
const PERSONAS_BYPASS_TEAM_ROLES = new Set(["SUPER_ADMIN", "ADMIN"])
|
||||
|
||||
export function getSessionTeamRole(): string {
|
||||
return localStorage.getItem("role")?.trim() ?? ""
|
||||
}
|
||||
|
||||
export function hasPersonasRoleBypass(): boolean {
|
||||
const role = getSessionTeamRole().toUpperCase()
|
||||
return PERSONAS_BYPASS_TEAM_ROLES.has(role)
|
||||
}
|
||||
|
||||
export function hasPersonaPermission(
|
||||
permission: string,
|
||||
permissions: string[],
|
||||
): boolean {
|
||||
if (hasPersonasRoleBypass()) return true
|
||||
return permissions.includes(permission)
|
||||
}
|
||||
54
src/lib/ratingUserCache.ts
Normal file
54
src/lib/ratingUserCache.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { getUserById } from "../api/users.api"
|
||||
import { userDisplayName } from "./ratingsDisplay"
|
||||
|
||||
export type ReviewerProfile = {
|
||||
id: number
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
const cache = new Map<number, ReviewerProfile | "error">()
|
||||
|
||||
export async function fetchReviewerProfile(userId: number): Promise<ReviewerProfile | null> {
|
||||
const cached = cache.get(userId)
|
||||
if (cached === "error") return null
|
||||
if (cached) return cached
|
||||
|
||||
try {
|
||||
const res = await getUserById(userId)
|
||||
const user = res.data.data
|
||||
const profile: ReviewerProfile = {
|
||||
id: user.id,
|
||||
name: userDisplayName(user.first_name, user.last_name, user.id),
|
||||
email: user.email || "",
|
||||
}
|
||||
cache.set(userId, profile)
|
||||
return profile
|
||||
} catch {
|
||||
cache.set(userId, "error")
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchReviewerProfiles(
|
||||
userIds: number[],
|
||||
concurrency = 5,
|
||||
): Promise<Map<number, ReviewerProfile>> {
|
||||
const unique = Array.from(new Set(userIds.filter((id) => Number.isFinite(id))))
|
||||
const result = new Map<number, ReviewerProfile>()
|
||||
|
||||
for (let i = 0; i < unique.length; i += concurrency) {
|
||||
const batch = unique.slice(i, i + concurrency)
|
||||
const profiles = await Promise.all(batch.map((id) => fetchReviewerProfile(id)))
|
||||
batch.forEach((id, index) => {
|
||||
const profile = profiles[index]
|
||||
if (profile) result.set(id, profile)
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export function clearReviewerProfileCache(): void {
|
||||
cache.clear()
|
||||
}
|
||||
57
src/lib/ratingsDisplay.ts
Normal file
57
src/lib/ratingsDisplay.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import type { RatingTargetType } from "../types/ratings.types"
|
||||
|
||||
export function formatAverageStars(value: number): string {
|
||||
if (!Number.isFinite(value) || value <= 0) return "0.0"
|
||||
return value.toFixed(1)
|
||||
}
|
||||
|
||||
export function formatRatingDate(dateStr: string): string {
|
||||
const d = new Date(dateStr)
|
||||
if (Number.isNaN(d.getTime())) return dateStr || "—"
|
||||
return d.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
export function formatRatingDateTime(dateStr: string): string {
|
||||
const d = new Date(dateStr)
|
||||
if (Number.isNaN(d.getTime())) return dateStr || "—"
|
||||
return d.toLocaleString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
export function targetTypeLabel(type: RatingTargetType): string {
|
||||
switch (type) {
|
||||
case "app":
|
||||
return "App"
|
||||
case "course":
|
||||
return "Course"
|
||||
case "sub_course":
|
||||
return "Sub-course"
|
||||
default:
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
export function reviewTextOrPlaceholder(review: string | null | undefined): string {
|
||||
const text = review?.trim()
|
||||
return text ? text : "No written review"
|
||||
}
|
||||
|
||||
export function userDisplayName(
|
||||
firstName?: string | null,
|
||||
lastName?: string | null,
|
||||
userId?: number,
|
||||
): string {
|
||||
const name = [firstName, lastName].filter(Boolean).join(" ").trim()
|
||||
if (name) return name
|
||||
if (userId != null) return `User #${userId}`
|
||||
return "Unknown user"
|
||||
}
|
||||
12
src/lib/ratingsErrors.ts
Normal file
12
src/lib/ratingsErrors.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export function getRatingsApiErrorMessage(error: unknown, fallback: string): string {
|
||||
const data = (error as { response?: { data?: { message?: string; error?: string } } })
|
||||
?.response?.data
|
||||
return data?.error ?? data?.message ?? fallback
|
||||
}
|
||||
|
||||
export function isRatingsForbiddenError(error: unknown): boolean {
|
||||
return (error as { response?: { status?: number } })?.response?.status === 403
|
||||
}
|
||||
|
||||
export const RATINGS_FORBIDDEN_MESSAGE =
|
||||
"You don't have permission to access ratings and app reviews"
|
||||
19
src/lib/ratingsPermissions.ts
Normal file
19
src/lib/ratingsPermissions.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
/** Roles that bypass RBAC permission checks per ratings integration guide. */
|
||||
const RATINGS_BYPASS_TEAM_ROLES = new Set(["SUPER_ADMIN", "ADMIN"])
|
||||
|
||||
export function getSessionTeamRole(): string {
|
||||
return localStorage.getItem("role")?.trim() ?? ""
|
||||
}
|
||||
|
||||
export function hasRatingsRoleBypass(): boolean {
|
||||
const role = getSessionTeamRole().toUpperCase()
|
||||
return RATINGS_BYPASS_TEAM_ROLES.has(role)
|
||||
}
|
||||
|
||||
export function hasRatingsPermission(
|
||||
permission: string,
|
||||
permissions: string[],
|
||||
): boolean {
|
||||
if (hasRatingsRoleBypass()) return true
|
||||
return permissions.includes(permission)
|
||||
}
|
||||
|
|
@ -10,9 +10,9 @@ export function toVimeoEmbedUrl(rawUrl: string): string | 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));
|
||||
const videoId = extractVimeoVideoId(rawUrl);
|
||||
if (!videoId) return null;
|
||||
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||
// Vimeo private/unlisted links often come as /<videoId>/<hash> instead of ?h=<hash>.
|
||||
const hashFromPath = (() => {
|
||||
const videoIdx = segments.findIndex((segment) => segment === videoId);
|
||||
|
|
@ -30,6 +30,23 @@ export function toVimeoEmbedUrl(rawUrl: string): string | null {
|
|||
}
|
||||
}
|
||||
|
||||
/** Numeric Vimeo video id from vimeo.com or player.vimeo.com URLs. */
|
||||
export function extractVimeoVideoId(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")) {
|
||||
const match = parsed.pathname.match(/\/video\/(\d+)/);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||
return segments.find((segment) => /^\d+$/.test(segment)) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function toYoutubeEmbedUrl(rawUrl: string): string | null {
|
||||
try {
|
||||
const u = new URL(rawUrl.trim());
|
||||
|
|
|
|||
38
src/lib/vimeoVideoCache.ts
Normal file
38
src/lib/vimeoVideoCache.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { getVimeoVideo } from "../api/courses.api"
|
||||
|
||||
const durationCache = new Map<string, number | null>()
|
||||
const inflight = new Map<string, Promise<number | null>>()
|
||||
|
||||
export function fetchVimeoDurationSeconds(vimeoId: string): Promise<number | null> {
|
||||
const id = vimeoId.trim()
|
||||
if (!id) return Promise.resolve(null)
|
||||
|
||||
if (durationCache.has(id)) {
|
||||
return Promise.resolve(durationCache.get(id) ?? null)
|
||||
}
|
||||
|
||||
const pending = inflight.get(id)
|
||||
if (pending) return pending
|
||||
|
||||
const request = getVimeoVideo(id)
|
||||
.then((video) => {
|
||||
const seconds =
|
||||
typeof video.duration === "number" &&
|
||||
Number.isFinite(video.duration) &&
|
||||
video.duration > 0
|
||||
? video.duration
|
||||
: null
|
||||
durationCache.set(id, seconds)
|
||||
return seconds
|
||||
})
|
||||
.catch(() => {
|
||||
durationCache.set(id, null)
|
||||
return null
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(id)
|
||||
})
|
||||
|
||||
inflight.set(id, request)
|
||||
return request
|
||||
}
|
||||
|
|
@ -37,8 +37,9 @@ 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 { getRatings } from "../api/courses.api"
|
||||
import { getRatingSummary, listRatingsByTarget } from "../api/ratings.api"
|
||||
import { useEffect, useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { AnalyticsTimeRangeFilter } from "../components/analytics/AnalyticsTimeRangeFilter"
|
||||
import {
|
||||
getPrimaryQuestionTypeSummary,
|
||||
|
|
@ -47,9 +48,10 @@ import {
|
|||
getVideoLessonsSummary,
|
||||
} from "../lib/analytics"
|
||||
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
|
||||
import { formatAverageStars } from "../lib/ratingsDisplay"
|
||||
import { formatPlanDuration } from "../lib/subscriptionPlans"
|
||||
import type { SubscriptionPlan } from "../types/subscription.types"
|
||||
import type { Rating } from "../types/course.types"
|
||||
import type { Rating, RatingSummary } from "../types/ratings.types"
|
||||
|
||||
const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444"]
|
||||
|
||||
|
|
@ -66,6 +68,10 @@ export function DashboardPage() {
|
|||
const [loading, setLoading] = useState(true)
|
||||
const [activeStatTab, setActiveStatTab] = useState<"primary" | "secondary">("primary")
|
||||
const [appRatings, setAppRatings] = useState<Rating[]>([])
|
||||
const [appRatingsSummary, setAppRatingsSummary] = useState<RatingSummary>({
|
||||
total_count: 0,
|
||||
average_stars: 0,
|
||||
})
|
||||
const [appRatingsLoading, setAppRatingsLoading] = useState(true)
|
||||
const [filters, setFilters] = useState<DashboardFilters>(DEFAULT_FILTERS)
|
||||
const [subscriptionPlans, setSubscriptionPlans] = useState<SubscriptionPlan[]>([])
|
||||
|
|
@ -93,8 +99,12 @@ export function DashboardPage() {
|
|||
useEffect(() => {
|
||||
const fetchAppRatings = async () => {
|
||||
try {
|
||||
const res = await getRatings({ target_type: "app", target_id: 1, limit: 5 })
|
||||
setAppRatings(res.data.data)
|
||||
const [summary, reviews] = await Promise.all([
|
||||
getRatingSummary({ target_type: "app", target_id: 0 }),
|
||||
listRatingsByTarget({ target_type: "app", target_id: 0, limit: 5, offset: 0 }),
|
||||
])
|
||||
setAppRatingsSummary(summary)
|
||||
setAppRatings(reviews)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
} finally {
|
||||
|
|
@ -496,9 +506,17 @@ export function DashboardPage() {
|
|||
{/* App Ratings */}
|
||||
<Card className="shadow-none">
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageSquare className="h-5 w-5 text-brand-500" />
|
||||
<CardTitle>Recent App Reviews</CardTitle>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<MessageSquare className="h-5 w-5 text-brand-500" />
|
||||
<CardTitle>Recent App Reviews</CardTitle>
|
||||
</div>
|
||||
<Link
|
||||
to="/app-reviews"
|
||||
className="text-xs font-medium text-brand-600 hover:underline"
|
||||
>
|
||||
View all
|
||||
</Link>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 pt-2">
|
||||
|
|
@ -506,7 +524,7 @@ export function DashboardPage() {
|
|||
<div className="flex items-center justify-center py-10">
|
||||
<img src={spinnerSrc} alt="" className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : appRatings.length === 0 ? (
|
||||
) : appRatingsSummary.total_count === 0 ? (
|
||||
<div className="flex items-center justify-center py-10 text-sm text-grayScale-400">
|
||||
No app reviews yet
|
||||
</div>
|
||||
|
|
@ -519,10 +537,7 @@ export function DashboardPage() {
|
|||
key={i}
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
i <
|
||||
Math.round(
|
||||
appRatings.reduce((sum, r) => sum + r.stars, 0) / appRatings.length,
|
||||
)
|
||||
i < Math.round(appRatingsSummary.average_stars)
|
||||
? "fill-amber-400 text-amber-400"
|
||||
: "fill-grayScale-200 text-grayScale-200",
|
||||
)}
|
||||
|
|
@ -530,10 +545,11 @@ export function DashboardPage() {
|
|||
))}
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-grayScale-600">
|
||||
{(appRatings.reduce((sum, r) => sum + r.stars, 0) / appRatings.length).toFixed(1)}
|
||||
{formatAverageStars(appRatingsSummary.average_stars)}
|
||||
</span>
|
||||
<span className="text-xs text-grayScale-400">
|
||||
({appRatings.length} {appRatings.length === 1 ? "review" : "reviews"})
|
||||
({appRatingsSummary.total_count}{" "}
|
||||
{appRatingsSummary.total_count === 1 ? "review" : "reviews"})
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,433 +1,491 @@
|
|||
import { useEffect, useState, type ChangeEvent } from "react";
|
||||
import { BadgeCheck, Briefcase, CalendarDays, Mail, Phone, Shield, User } from "lucide-react";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card, CardContent } from "../components/ui/card";
|
||||
import { useEffect, useState } from "react"
|
||||
import {
|
||||
BadgeCheck,
|
||||
CalendarDays,
|
||||
Clock3,
|
||||
Mail,
|
||||
Phone,
|
||||
Shield,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getTeamMe, updateTeamMe } from "../api/team.api"
|
||||
import { Badge } from "../components/ui/badge"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../components/ui/dialog";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Textarea } from "../components/ui/textarea";
|
||||
import { FileUpload } from "../components/ui/file-upload";
|
||||
import { getMyProfile } from "../api/users.api";
|
||||
import { updateTeamMember } from "../api/team.api";
|
||||
import { uploadImageFile } from "../api/files.api";
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||
import type { UpdateTeamMemberRequest } from "../types/team.types";
|
||||
import { toast } from "sonner";
|
||||
} from "../components/ui/dialog"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon"
|
||||
import { Textarea } from "../components/ui/textarea"
|
||||
import { cn } from "../lib/utils"
|
||||
import type { TeamMeProfile } from "../types/team.types"
|
||||
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload"
|
||||
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField"
|
||||
|
||||
function formatDate(dateStr: string | null | undefined): string {
|
||||
if (!dateStr) return "—";
|
||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||
if (!dateStr) return "—"
|
||||
const date = new Date(dateStr)
|
||||
if (Number.isNaN(date.getTime())) return dateStr
|
||||
return date.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr: string | null | undefined): string {
|
||||
if (!dateStr) return "—";
|
||||
return new Date(dateStr).toLocaleString("en-US", {
|
||||
if (!dateStr) return "—"
|
||||
const date = new Date(dateStr)
|
||||
if (Number.isNaN(date.getTime())) return dateStr
|
||||
return date.toLocaleString(undefined, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
interface TeamMeProfile {
|
||||
id: number
|
||||
first_name: string
|
||||
last_name: string
|
||||
email: string
|
||||
phone_number: string
|
||||
team_role: string
|
||||
department: string
|
||||
job_title: string
|
||||
employment_type: string
|
||||
hire_date: string
|
||||
bio: string
|
||||
status: string
|
||||
email_verified: boolean
|
||||
permissions: string[]
|
||||
last_login: string | null
|
||||
created_at: string
|
||||
emergency_contact?: string
|
||||
work_phone?: string
|
||||
profile_picture_url?: string
|
||||
function formatRoleLabel(role: string): string {
|
||||
const value = role.trim()
|
||||
if (!value) return "—"
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim()
|
||||
if (!value) return "—"
|
||||
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
|
||||
}
|
||||
|
||||
function displayValue(value: string | null | undefined): string {
|
||||
const trimmed = value?.trim()
|
||||
return trimmed ? trimmed : "—"
|
||||
}
|
||||
|
||||
function ReadOnlyField({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">{label}</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{value}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="w-full space-y-8 py-10">
|
||||
<div className="animate-pulse space-y-8">
|
||||
<div className="overflow-hidden rounded-2xl border border-grayScale-100">
|
||||
<div className="h-40 bg-gradient-to-r from-grayScale-100 via-grayScale-200/60 to-grayScale-100" />
|
||||
<div className="flex flex-col items-center px-8 pb-8">
|
||||
<div className="-mt-14 h-28 w-28 rounded-full bg-grayScale-100 ring-4 ring-white" />
|
||||
<div className="mt-4 h-6 w-48 rounded-lg bg-grayScale-100" />
|
||||
<div className="mt-3 h-5 w-24 rounded-full bg-grayScale-100" />
|
||||
<div className="mt-5 flex gap-3">
|
||||
<div className="h-7 w-20 rounded-full bg-grayScale-100" />
|
||||
<div className="h-7 w-28 rounded-full bg-grayScale-100" />
|
||||
<div className="h-7 w-28 rounded-full bg-grayScale-100" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-6 md:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div key={i} className="rounded-2xl border border-grayScale-100 p-6">
|
||||
<div className="mb-5 h-5 w-40 rounded bg-grayScale-100" />
|
||||
<div className="space-y-4">
|
||||
{[1, 2, 3, 4].map((j) => (
|
||||
<div key={j} className="flex items-center justify-between">
|
||||
<div className="h-4 w-20 rounded bg-grayScale-100" />
|
||||
<div className="h-4 w-28 rounded bg-grayScale-100" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mx-auto w-full max-w-5xl space-y-6 py-8">
|
||||
<div className="h-8 w-48 animate-pulse rounded-lg bg-grayScale-100" />
|
||||
<div className="h-40 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{[1, 2].map((item) => (
|
||||
<div key={item} className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
type EditFormState = {
|
||||
first_name: string
|
||||
last_name: string
|
||||
phone_number: string
|
||||
department: string
|
||||
job_title: string
|
||||
profile_picture_url: string
|
||||
bio: string
|
||||
work_phone: string
|
||||
}
|
||||
|
||||
function profileToEditForm(profile: TeamMeProfile): EditFormState {
|
||||
return {
|
||||
first_name: profile.first_name,
|
||||
last_name: profile.last_name,
|
||||
phone_number: profile.phone_number,
|
||||
department: profile.department ?? "",
|
||||
job_title: profile.job_title ?? "",
|
||||
profile_picture_url: profile.profile_picture_url ?? "",
|
||||
bio: profile.bio ?? "",
|
||||
work_phone: profile.work_phone ?? "",
|
||||
}
|
||||
}
|
||||
|
||||
export function ProfilePage() {
|
||||
const [profile, setProfile] = useState<TeamMeProfile | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [profilePictureFile, setProfilePictureFile] = useState<File | null>(null);
|
||||
const [editForm, setEditForm] = useState<UpdateTeamMemberRequest>({
|
||||
const [profile, setProfile] = useState<TeamMeProfile | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||
const [editForm, setEditForm] = useState<EditFormState>({
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
phone_number: "",
|
||||
department: "",
|
||||
job_title: "",
|
||||
profile_picture_url: "",
|
||||
bio: "",
|
||||
});
|
||||
work_phone: "",
|
||||
})
|
||||
|
||||
const busy = saving || uploadingPicture
|
||||
|
||||
const loadProfile = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await getTeamMe()
|
||||
setProfile(res.data.data)
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch profile", err)
|
||||
setProfile(null)
|
||||
setError("Failed to load profile. Please try again later.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProfile = async () => {
|
||||
try {
|
||||
const res = await getMyProfile();
|
||||
setProfile((res.data?.data ?? null) as unknown as TeamMeProfile | null);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch profile", err);
|
||||
setError("Failed to load profile. Please try again later.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchProfile();
|
||||
}, []);
|
||||
void loadProfile()
|
||||
}, [])
|
||||
|
||||
const startEditing = () => {
|
||||
if (!profile) return;
|
||||
const nextForm: UpdateTeamMemberRequest = {
|
||||
first_name: profile.first_name ?? "",
|
||||
last_name: profile.last_name ?? "",
|
||||
phone_number: profile.phone_number ?? "",
|
||||
profile_picture_url: profile.profile_picture_url ?? "",
|
||||
bio: profile.bio ?? "",
|
||||
};
|
||||
setEditForm(nextForm);
|
||||
setProfilePictureFile(null);
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const cancelEditing = () => {
|
||||
setProfilePictureFile(null);
|
||||
setEditing(false);
|
||||
};
|
||||
|
||||
const updateField = (field: keyof UpdateTeamMemberRequest, value: string) => {
|
||||
setEditForm((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
if (!profile) return
|
||||
setEditForm(profileToEditForm(profile))
|
||||
setUploadingPicture(false)
|
||||
setEditing(true)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!profile) return;
|
||||
if (!profile) return
|
||||
|
||||
let nextProfilePictureUrl = editForm.profile_picture_url ?? "";
|
||||
if (profilePictureFile) {
|
||||
try {
|
||||
const uploadRes = await uploadImageFile(profilePictureFile);
|
||||
const uploadedUrl = uploadRes.data?.data?.url?.trim();
|
||||
if (!uploadedUrl) throw new Error("Missing uploaded image url");
|
||||
nextProfilePictureUrl = uploadedUrl;
|
||||
} catch (err) {
|
||||
console.error("Failed to upload profile picture:", err);
|
||||
toast.error("Failed to upload profile picture");
|
||||
return;
|
||||
}
|
||||
const firstName = editForm.first_name.trim()
|
||||
const lastName = editForm.last_name.trim()
|
||||
|
||||
if (!firstName || !lastName) {
|
||||
toast.error("First name and last name are required")
|
||||
return
|
||||
}
|
||||
|
||||
const payload: UpdateTeamMemberRequest = {
|
||||
bio: editForm.bio ?? "",
|
||||
first_name: editForm.first_name ?? "",
|
||||
last_name: editForm.last_name ?? "",
|
||||
phone_number: editForm.phone_number ?? "",
|
||||
profile_picture_url: nextProfilePictureUrl,
|
||||
};
|
||||
|
||||
setSaving(true);
|
||||
setSaving(true)
|
||||
try {
|
||||
await updateTeamMember(profile.id, payload);
|
||||
const refreshed = await getMyProfile();
|
||||
setProfile((refreshed.data?.data ?? null) as unknown as TeamMeProfile | null);
|
||||
setEditing(false);
|
||||
setProfilePictureFile(null);
|
||||
toast.success("Profile updated successfully");
|
||||
const res = await updateTeamMe({
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
phone_number: editForm.phone_number.trim(),
|
||||
department: editForm.department.trim(),
|
||||
job_title: editForm.job_title.trim(),
|
||||
profile_picture_url: editForm.profile_picture_url.trim(),
|
||||
bio: editForm.bio.trim(),
|
||||
work_phone: editForm.work_phone.trim(),
|
||||
})
|
||||
setProfile(res.data.data)
|
||||
setEditing(false)
|
||||
toast.success(res.data.message || "Profile updated successfully")
|
||||
} catch (err) {
|
||||
console.error("Failed to update team member profile", err);
|
||||
toast.error("Failed to update profile");
|
||||
console.error("Failed to update profile", err)
|
||||
const message =
|
||||
(err as { response?: { data?: { message?: string } } })?.response?.data
|
||||
?.message ?? "Failed to update profile"
|
||||
toast.error(message)
|
||||
} finally {
|
||||
setSaving(false);
|
||||
setSaving(false)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (loading) return <LoadingSkeleton />;
|
||||
if (loading) return <LoadingSkeleton />
|
||||
|
||||
if (error || !profile) {
|
||||
return (
|
||||
<div className="w-full py-16">
|
||||
<div className="mx-auto w-full max-w-5xl py-16">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="flex flex-col items-center gap-5 p-12">
|
||||
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-grayScale-100">
|
||||
<User className="h-10 w-10 text-grayScale-300" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="text-lg font-semibold tracking-tight text-grayScale-600">
|
||||
<p className="text-lg font-semibold text-grayScale-700">
|
||||
{error || "Profile not available"}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-grayScale-400">
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
Please check your connection and try again.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => void loadProfile()}>
|
||||
Retry
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const fullName = `${profile.first_name} ${profile.last_name}`.trim()
|
||||
const initials = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}`.toUpperCase()
|
||||
const isActive = profile.status.toLowerCase() === "active"
|
||||
|
||||
const handleProfileUpdate = (nextProfile: TeamMeProfile) => {
|
||||
setProfile(nextProfile)
|
||||
setEditForm((prev) => ({
|
||||
...prev,
|
||||
profile_picture_url: nextProfile.profile_picture_url ?? "",
|
||||
}))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Account</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">My profile</h1>
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
Your team account details from the admin directory.
|
||||
</p>
|
||||
</div>
|
||||
<Button className="bg-brand-500 text-white hover:bg-brand-600" onClick={startEditing}>
|
||||
Edit profile
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card className="overflow-hidden border-grayScale-100 shadow-soft">
|
||||
<div className="h-28 bg-gradient-to-r from-brand-500/20 via-brand-300/20 to-brand-100/40" />
|
||||
<CardContent className="relative px-6 pb-6 pt-0">
|
||||
<div className="-mt-12 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div className="flex items-end gap-4">
|
||||
<ProfileAvatarUpload
|
||||
avatarUrl={profile.profile_picture_url}
|
||||
initials={initials}
|
||||
onProfileUpdate={handleProfileUpdate}
|
||||
/>
|
||||
<div className="pb-1">
|
||||
<h2 className="text-2xl font-semibold text-grayScale-800">{fullName}</h2>
|
||||
<p className="text-sm text-grayScale-500">{displayValue(profile.job_title)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2 pb-1">
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{formatStatusLabel(profile.status)}
|
||||
</Badge>
|
||||
<Badge variant={profile.email_verified ? "default" : "outline"}>
|
||||
{profile.email_verified ? "Email verified" : "Email not verified"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{profile.bio?.trim() ? (
|
||||
<p className="mt-4 text-sm leading-relaxed text-grayScale-600">{profile.bio.trim()}</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Work details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||||
<ReadOnlyField label="Team role" value={formatRoleLabel(profile.team_role)} />
|
||||
<ReadOnlyField label="Department" value={displayValue(profile.department)} />
|
||||
<ReadOnlyField label="Job title" value={displayValue(profile.job_title)} />
|
||||
<ReadOnlyField label="Member ID" value={String(profile.id)} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Contact</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||
<Mail className="h-4 w-4 text-brand-600" />
|
||||
<span>{displayValue(profile.email)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||
<Phone className="h-4 w-4 text-brand-600" />
|
||||
<span>{displayValue(profile.phone_number)}</span>
|
||||
</div>
|
||||
{profile.work_phone?.trim() ? (
|
||||
<div className="flex items-center gap-3 text-sm text-grayScale-700">
|
||||
<Phone className="h-4 w-4 text-brand-600" />
|
||||
<span>
|
||||
<span className="text-grayScale-500">Work: </span>
|
||||
{profile.work_phone.trim()}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="shadow-soft lg:col-span-2">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Account activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<CalendarDays className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||
<ReadOnlyField label="Joined" value={formatDate(profile.created_at)} />
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Clock3 className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||
<ReadOnlyField label="Last login" value={formatDateTime(profile.last_login)} />
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<BadgeCheck className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||
<ReadOnlyField
|
||||
label="Email verification"
|
||||
value={profile.email_verified ? "Verified" : "Not verified"}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Shield className="mt-0.5 h-4 w-4 text-brand-600" />
|
||||
<ReadOnlyField label="Last updated" value={formatDate(profile.updated_at)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const fullName = `${profile.first_name} ${profile.last_name}`;
|
||||
const initials = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}`.toUpperCase();
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-7xl rounded-2xl bg-[#f7f1f8] p-4 pb-8 sm:p-6">
|
||||
<div className="overflow-hidden rounded-2xl border border-[#d9bddb] bg-white">
|
||||
<div className="h-40 w-full bg-gradient-to-r from-[#d6aed6] via-[#e4cce4] to-[#cba0cd]" />
|
||||
|
||||
<div className="grid gap-0 lg:grid-cols-[280px_minmax(0,1fr)]">
|
||||
<aside className="border-r border-[#eadbea] bg-white px-5 pb-6">
|
||||
<div className="-mt-16">
|
||||
<div className="flex h-28 w-28 items-center justify-center rounded-full border-4 border-white bg-[#d6aed6] text-2xl font-bold text-[#6f2aa8]">
|
||||
{initials}
|
||||
</div>
|
||||
<h2 className="mt-3 text-2xl font-bold text-grayScale-700">{fullName}</h2>
|
||||
<p className="text-sm text-grayScale-400">{profile.job_title || "Team Member"}</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="flex w-full items-center justify-between rounded-lg border border-[#d9bddb] bg-[#f4e8f4] px-3 py-2">
|
||||
<span className="text-sm font-medium text-[#6f2aa8]">Account Status</span>
|
||||
<span className="text-sm font-semibold uppercase text-[#5e2390]">{profile.status}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 space-y-5 text-sm">
|
||||
<section>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">About</p>
|
||||
<div className="space-y-2 text-grayScale-600">
|
||||
<div className="flex items-center gap-2"><Briefcase className="h-4 w-4 text-[#6f2aa8]" />{profile.job_title || "Job title not set"}</div>
|
||||
<div className="flex items-center gap-2"><Shield className="h-4 w-4 text-[#6f2aa8]" />{profile.team_role || "Role not set"}</div>
|
||||
<div className="flex items-center gap-2"><CalendarDays className="h-4 w-4 text-[#6f2aa8]" />Hire date: {formatDate(profile.hire_date)}</div>
|
||||
<div className="flex items-center gap-2"><BadgeCheck className="h-4 w-4 text-[#6f2aa8]" />{profile.department || "Department not set"}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">Contact</p>
|
||||
<div className="space-y-2 text-grayScale-600">
|
||||
<div className="flex items-center gap-2"><Mail className="h-4 w-4 text-[#6f2aa8]" />{profile.email}</div>
|
||||
<div className="flex items-center gap-2"><Phone className="h-4 w-4 text-[#6f2aa8]" />{profile.phone_number || "—"}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-grayScale-400">Access</p>
|
||||
<p className="text-xs text-grayScale-500">Permissions from `/team/me`</p>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{(profile.permissions ?? []).length === 0 ? (
|
||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">No permissions listed</Badge>
|
||||
) : (
|
||||
profile.permissions.map((permission) => (
|
||||
<Badge key={permission} className="bg-[#ecd9ec] text-[#6f2aa8]">
|
||||
{permission}
|
||||
</Badge>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="bg-[#fdf8fd] px-5 py-6 sm:px-7">
|
||||
<div className="space-y-5">
|
||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
||||
<CardContent className="p-5">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-base font-semibold text-grayScale-700">Summary</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={startEditing}
|
||||
className="inline-flex items-center rounded-md border border-[#d9bddb] bg-[#f4e8f4] px-3 py-1.5 text-sm font-medium text-[#6f2aa8] transition-colors hover:bg-[#ecd9ec] hover:text-[#5e2390] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#c39bd4]"
|
||||
>
|
||||
Edit profile
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm text-grayScale-600">
|
||||
<div className="flex items-center gap-2"><Briefcase className="h-4 w-4 text-[#6f2aa8]" />{profile.job_title || "Role-focused work item"}</div>
|
||||
<div className="flex items-center gap-2"><Shield className="h-4 w-4 text-[#6f2aa8]" />{profile.team_role || "Team responsibility"}</div>
|
||||
<div className="flex items-center gap-2"><Mail className="h-4 w-4 text-[#6f2aa8]" />{profile.email}</div>
|
||||
<div className="flex items-center gap-2"><Phone className="h-4 w-4 text-[#6f2aa8]" />{profile.phone_number || "No phone number"}</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
||||
<CardContent className="p-5">
|
||||
<h3 className="mb-3 text-base font-semibold text-grayScale-700">Employment</h3>
|
||||
<div className="rounded-lg border border-[#dcc3df] bg-[#f4e8f4] p-3">
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.department || "Department not set"}</p>
|
||||
<p className="text-xs text-grayScale-500">Employment type: {profile.employment_type || "—"}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
||||
<CardContent className="p-5">
|
||||
<h3 className="mb-3 text-base font-semibold text-grayScale-700">More about me</h3>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Status {profile.status}</Badge>
|
||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Email {profile.email_verified ? "verified" : "not verified"}</Badge>
|
||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Joined {formatDate(profile.created_at)}</Badge>
|
||||
<Badge className="bg-[#ecd9ec] text-[#6f2aa8]">Last login {formatDateTime(profile.last_login)}</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-[#d9bddb] bg-white shadow-none">
|
||||
<CardContent className="grid gap-3 p-5 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">First Name</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.first_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Last Name</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.last_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Department</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.department || "—"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Team Role</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.team_role || "—"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Job Title</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.job_title || "—"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Hire Date</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{formatDate(profile.hire_date) || "—"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Phone Number</p>
|
||||
<p className="text-sm font-medium text-grayScale-700">{profile.phone_number || "—"}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<Dialog open={editing} onOpenChange={(open) => !saving && setEditing(open)}>
|
||||
<DialogContent className="max-h-[88vh] overflow-y-auto border-[#d9bddb] bg-[#fdf8fd] sm:max-w-3xl">
|
||||
<Dialog open={editing} onOpenChange={(open) => !busy && setEditing(open)}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-[#6f2aa8]">Edit profile</DialogTitle>
|
||||
<DialogTitle>Edit profile</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">First Name</p>
|
||||
<Input value={editForm.first_name ?? ""} onChange={(e) => updateField("first_name", e.target.value)} />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-first-name">
|
||||
First name
|
||||
</label>
|
||||
<Input
|
||||
id="profile-first-name"
|
||||
value={editForm.first_name}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, first_name: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Last Name</p>
|
||||
<Input value={editForm.last_name ?? ""} onChange={(e) => updateField("last_name", e.target.value)} />
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-last-name">
|
||||
Last name
|
||||
</label>
|
||||
<Input
|
||||
id="profile-last-name"
|
||||
value={editForm.last_name}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, last_name: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Phone Number</p>
|
||||
<Input value={editForm.phone_number ?? ""} onChange={(e) => updateField("phone_number", e.target.value)} />
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-phone">
|
||||
Phone number
|
||||
</label>
|
||||
<Input
|
||||
id="profile-phone"
|
||||
value={editForm.phone_number}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, phone_number: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Profile Picture</p>
|
||||
<div className="space-y-2">
|
||||
<FileUpload
|
||||
accept="image/*"
|
||||
onFileSelect={setProfilePictureFile}
|
||||
label="Upload profile picture"
|
||||
description="JPEG, PNG, WEBP"
|
||||
className="min-h-[90px] rounded-lg border-2 border-dashed border-grayScale-200 transition-colors hover:border-brand-400 hover:bg-brand-50/30"
|
||||
/>
|
||||
<Input
|
||||
value={editForm.profile_picture_url ?? ""}
|
||||
onChange={(e) => updateField("profile_picture_url", e.target.value)}
|
||||
placeholder="Or paste image URL (https://...)"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-work-phone">
|
||||
Work phone
|
||||
</label>
|
||||
<Input
|
||||
id="profile-work-phone"
|
||||
value={editForm.work_phone}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, work_phone: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<p className="mb-1 text-xs font-medium text-grayScale-500">Bio</p>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-department">
|
||||
Department
|
||||
</label>
|
||||
<Input
|
||||
id="profile-department"
|
||||
value={editForm.department}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, department: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-job-title">
|
||||
Job title
|
||||
</label>
|
||||
<Input
|
||||
id="profile-job-title"
|
||||
value={editForm.job_title}
|
||||
disabled={busy}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, job_title: e.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<label className="text-sm font-medium text-grayScale-700">Email</label>
|
||||
<Input value={profile.email} disabled />
|
||||
<p className="text-xs text-grayScale-500">Email is managed by your administrator.</p>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-picture">
|
||||
Profile picture
|
||||
</label>
|
||||
<PersonaProfilePictureUploadField
|
||||
value={editForm.profile_picture_url}
|
||||
disabled={busy}
|
||||
onUploadBusyChange={setUploadingPicture}
|
||||
onChange={(profile_picture_url) =>
|
||||
setEditForm((prev) => ({ ...prev, profile_picture_url }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="profile-bio">
|
||||
Bio
|
||||
</label>
|
||||
<Textarea
|
||||
value={editForm.bio ?? ""}
|
||||
onChange={(e: ChangeEvent<HTMLTextAreaElement>) => updateField("bio", e.target.value)}
|
||||
id="profile-bio"
|
||||
value={editForm.bio}
|
||||
disabled={busy}
|
||||
rows={4}
|
||||
placeholder="A short introduction about your role and background."
|
||||
onChange={(e) => setEditForm((prev) => ({ ...prev, bio: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="border-[#d9bddb] text-[#6f2aa8]"
|
||||
onClick={cancelEditing}
|
||||
disabled={saving}
|
||||
>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditing(false)} disabled={busy}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="bg-[#6f2aa8] text-white hover:bg-[#5e2390]"
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className={cn("bg-brand-500 text-white hover:bg-brand-600")}
|
||||
onClick={() => void handleSave()}
|
||||
disabled={busy}
|
||||
>
|
||||
{saving ? <SpinnerIcon className="mr-1 h-4 w-4" /> : null}
|
||||
{saving ? "Saving..." : "Save changes"}
|
||||
{saving ? <SpinnerIcon className="mr-2 h-4 w-4" /> : null}
|
||||
{saving ? "Saving…" : "Save changes"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import {
|
|||
Lock,
|
||||
Moon,
|
||||
Palette,
|
||||
Save,
|
||||
Shield,
|
||||
Sun,
|
||||
User,
|
||||
|
|
@ -21,13 +20,12 @@ import {
|
|||
} from "../components/ui/card";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Select } from "../components/ui/select";
|
||||
import { cn } from "../lib/utils";
|
||||
import { SpinnerIcon } from "../components/ui/spinner-icon";
|
||||
import { changeTeamMemberPassword } from "../api/team.api";
|
||||
import { logoutToLogin } from "../lib/auth";
|
||||
import { getMyProfile, updateProfile } from "../api/users.api";
|
||||
import type { UserProfileData } from "../types/user.types";
|
||||
import { getMyProfile } from "../api/users.api";
|
||||
import type { TeamMeProfile } from "../types/team.types";
|
||||
import { toast } from "sonner";
|
||||
import { AppVersionsTab } from "./settings/AppVersionsTab";
|
||||
import { SubscriptionPlansTab } from "./settings/SubscriptionPlansTab";
|
||||
|
|
@ -37,133 +35,16 @@ import { useTheme } from "../contexts/ThemeContext";
|
|||
type SettingsTab =
|
||||
| "subscription"
|
||||
| "app-versions"
|
||||
| "profile"
|
||||
| "security"
|
||||
| "appearance";
|
||||
|
||||
const tabs: { id: SettingsTab; label: string; icon: typeof User }[] = [
|
||||
const tabs: { id: SettingsTab; label: string; icon: typeof Shield }[] = [
|
||||
{ id: "subscription", label: "Subscription packages", icon: CreditCard },
|
||||
{ id: "app-versions", label: "App versions", icon: Smartphone },
|
||||
{ id: "profile", label: "Profile", icon: User },
|
||||
{ id: "security", label: "Security", icon: Shield },
|
||||
{ id: "appearance", label: "Appearance", icon: Palette },
|
||||
];
|
||||
|
||||
function ProfileTab({ profile }: { profile: UserProfileData }) {
|
||||
const [firstName, setFirstName] = useState(profile.first_name);
|
||||
const [lastName, setLastName] = useState(profile.last_name);
|
||||
const [nickName, setNickName] = useState(profile.nick_name || "");
|
||||
const [language, setLanguage] = useState(profile.preferred_language || "en");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateProfile({
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
nick_name: nickName,
|
||||
preferred_language: language,
|
||||
});
|
||||
toast.success("Profile settings saved");
|
||||
} catch {
|
||||
toast.error("Failed to save profile settings.");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
|
||||
<Card className="border border-grayScale-100 rounded-[6px] overflow-hidden">
|
||||
<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">
|
||||
Personal Information
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5 pb-6">
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
First Name
|
||||
</label>
|
||||
<Input
|
||||
value={firstName}
|
||||
onChange={(e) => setFirstName(e.target.value)}
|
||||
className="rounded-[6px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Last Name
|
||||
</label>
|
||||
<Input
|
||||
value={lastName}
|
||||
onChange={(e) => setLastName(e.target.value)}
|
||||
className="rounded-[6px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Nickname
|
||||
</label>
|
||||
<Input
|
||||
value={nickName}
|
||||
onChange={(e) => setNickName(e.target.value)}
|
||||
className="rounded-[6px]"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border border-grayScale-100 rounded-[6px] overflow-hidden">
|
||||
<div className="h-1 w-full bg-brand-400" />
|
||||
<CardHeader className="pb-3 border-b border-grayScale-50">
|
||||
<CardTitle className="text-sm font-bold text-grayScale-900">
|
||||
Preferences
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5 pb-6">
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Preferred Language
|
||||
</label>
|
||||
<Select
|
||||
value={language}
|
||||
onChange={(e) => setLanguage(e.target.value)}
|
||||
className="rounded-[6px]"
|
||||
>
|
||||
<option value="en">English</option>
|
||||
<option value="am">Amharic</option>
|
||||
<option value="or">Afan Oromo</option>
|
||||
<option value="ti">Tigrinya</option>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="min-w-[140px] rounded-[6px] font-bold"
|
||||
>
|
||||
{saving ? (
|
||||
<SpinnerIcon className="h-4 w-4" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{saving ? "Saving…" : "Save Changes"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SecurityTab({ memberId }: { memberId: number }) {
|
||||
const [currentPassword, setCurrentPassword] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
|
|
@ -474,7 +355,7 @@ function AppearanceTab() {
|
|||
|
||||
export function SettingsPage() {
|
||||
const [activeTab, setActiveTab] = useState<SettingsTab>("subscription");
|
||||
const [profile, setProfile] = useState<UserProfileData | null>(null);
|
||||
const [profile, setProfile] = useState<TeamMeProfile | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
|
|
@ -535,8 +416,8 @@ export function SettingsPage() {
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-col gap-8 lg:flex-row lg:items-start">
|
||||
<nav className="flex shrink-0 flex-row gap-1 overflow-x-auto rounded-[8px] border border-grayScale-100 bg-white p-1 lg:w-56 lg:flex-col">
|
||||
<div className="space-y-6">
|
||||
<nav className="flex gap-1 overflow-x-auto border-b border-grayScale-100 pb-px">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon;
|
||||
const active = activeTab === tab.id;
|
||||
|
|
@ -546,10 +427,10 @@ export function SettingsPage() {
|
|||
type="button"
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={cn(
|
||||
"flex items-center gap-2.5 whitespace-nowrap rounded-[6px] px-3 py-2.5 text-left text-sm font-medium transition-colors",
|
||||
"flex shrink-0 items-center gap-2 whitespace-nowrap border-b-2 px-4 py-3 text-sm font-medium transition-colors",
|
||||
active
|
||||
? "bg-brand-50 text-brand-600"
|
||||
: "text-grayScale-600 hover:bg-grayScale-50",
|
||||
? "border-brand-500 text-brand-600"
|
||||
: "border-transparent text-grayScale-500 hover:border-grayScale-200 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
|
|
@ -559,10 +440,9 @@ export function SettingsPage() {
|
|||
})}
|
||||
</nav>
|
||||
|
||||
<main className="min-h-[400px] min-w-0 w-full flex-1">
|
||||
<main className="min-h-[400px] min-w-0 w-full">
|
||||
{activeTab === "subscription" && <SubscriptionPlansTab />}
|
||||
{activeTab === "app-versions" && <AppVersionsTab />}
|
||||
{activeTab === "profile" && <ProfileTab profile={profile} />}
|
||||
{activeTab === "security" && <SecurityTab memberId={profile.id} />}
|
||||
{activeTab === "appearance" && <AppearanceTab />}
|
||||
</main>
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ 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";
|
||||
|
|
@ -713,19 +714,12 @@ export function AddNewPracticePage() {
|
|||
<label className="text-sm font-medium text-grayScale-700">
|
||||
Shuffle questions
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShuffleQuestions(!shuffleQuestions)}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out ${
|
||||
shuffleQuestions ? "bg-brand-500" : "bg-grayScale-300"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-in-out ${
|
||||
shuffleQuestions ? "translate-x-5" : "translate-x-0"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<ToggleSwitch
|
||||
variant="plain"
|
||||
checked={shuffleQuestions}
|
||||
aria-label="Shuffle questions"
|
||||
onCheckedChange={() => setShuffleQuestions(!shuffleQuestions)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ 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 { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
|
|
@ -27,6 +28,7 @@ import {
|
|||
} 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 { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||
|
|
@ -228,6 +230,15 @@ export function AllCoursesPage() {
|
|||
}
|
||||
}
|
||||
|
||||
const clearFilters = () => {
|
||||
setCategoryFilter("all")
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: categoryFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-32">
|
||||
|
|
@ -275,41 +286,41 @@ export function AllCoursesPage() {
|
|||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5 pt-5">
|
||||
{/* Search / Filters */}
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
placeholder="Search by title, description, or category…"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select
|
||||
value={categoryFilter}
|
||||
onChange={(e) => {
|
||||
setCategoryFilter(e.target.value as typeof categoryFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<option value="all">All Categories</option>
|
||||
{categories.map((cat) => (
|
||||
<option key={cat.id} value={String(cat.id)}>
|
||||
{cat.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-xs font-medium text-grayScale-400">
|
||||
Showing {filteredCourses.length} of {courses.length} courses
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
className="border-0 shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={`Showing ${filteredCourses.length} of ${courses.length} courses`}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
placeholder="Search by title, description, or category…"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Select
|
||||
value={categoryFilter}
|
||||
onChange={(e) => {
|
||||
setCategoryFilter(e.target.value as typeof categoryFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<option value="all">All Categories</option>
|
||||
{categories.map((cat) => (
|
||||
<option key={cat.id} value={String(cat.id)}>
|
||||
{cat.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{/* Courses Table */}
|
||||
{filteredCourses.length > 0 ? (
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ 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"
|
||||
|
|
@ -18,6 +19,7 @@ import {
|
|||
updateModule,
|
||||
} from "../../api/courses.api"
|
||||
import { uploadImageFile } from "../../api/files.api"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import type { CourseHierarchyRow, HumanLanguageHierarchyFlatRow, Practice } from "../../types/course.types"
|
||||
|
||||
type IdFilterValue = number | "ALL"
|
||||
|
|
@ -650,6 +652,18 @@ export function HumanLanguageHierarchyPage() {
|
|||
window.sessionStorage.setItem(HUMAN_LANGUAGE_RETURN_STATE_KEY, JSON.stringify(payload))
|
||||
}
|
||||
|
||||
const clearFilters = () => {
|
||||
setSelectedSubCategoryId("ALL")
|
||||
setSelectedCourseId("ALL")
|
||||
setSelectedLevelId("ALL")
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: selectedSubCategoryId, defaultValue: "ALL" },
|
||||
{ value: selectedCourseId, defaultValue: "ALL" },
|
||||
{ value: selectedLevelId, defaultValue: "ALL" },
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
|
|
@ -667,12 +681,12 @@ export function HumanLanguageHierarchyPage() {
|
|||
</Button>
|
||||
</div>
|
||||
|
||||
<Card className="border border-grayScale-200 shadow-sm">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg">Filters</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
defaultOpen={activeFilterCount > 0}
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="hl-subcategory-filter" className="text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||
Subcategory
|
||||
|
|
@ -764,8 +778,7 @@ export function HumanLanguageHierarchyPage() {
|
|||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{selectedSubCategoryId !== "ALL" ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Link, useLocation, useNavigate, useParams } from "react-router-dom"
|
|||
import { ArrowLeft, BookOpen, Eye, FileText, Plus, Search, Trophy, Video } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Card } from "../../components/ui/card"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../../components/ui/dialog"
|
||||
|
|
@ -12,6 +13,7 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
|||
import { Textarea } from "../../components/ui/textarea"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import {
|
||||
getLessonsBySubModule,
|
||||
getQuestionSetsByOwner,
|
||||
|
|
@ -347,6 +349,17 @@ export function HumanLanguageSubModulePage() {
|
|||
() => filterLessons(lessons, lessonSearch, lessonActiveFilter),
|
||||
[lessons, lessonSearch, lessonActiveFilter],
|
||||
)
|
||||
|
||||
const practiceActiveFilterCount = countActiveFilters([
|
||||
{ value: practiceStatusFilter, defaultValue: "all" },
|
||||
])
|
||||
const lessonActiveFilterCount = countActiveFilters([
|
||||
{ value: lessonActiveFilter, defaultValue: "all" },
|
||||
])
|
||||
const capstoneActiveFilterCount = countActiveFilters([
|
||||
{ value: capstoneStatusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const subModuleLabel = useMemo(() => {
|
||||
const rawTitle = subCourse?.title?.trim()
|
||||
if (!rawTitle) return "Sub-module"
|
||||
|
|
@ -797,19 +810,24 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
{activeTab === "practices" ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
||||
<div className="relative min-w-[200px] flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={practiceSearch}
|
||||
onChange={(e) => setPracticeSearch(e.target.value)}
|
||||
aria-label="Search practices"
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={practiceActiveFilterCount}
|
||||
onClearFilters={() => setPracticeStatusFilter("all")}
|
||||
search={
|
||||
<div className="relative min-w-[200px] w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={practiceSearch}
|
||||
onChange={(e) => setPracticeSearch(e.target.value)}
|
||||
aria-label="Search practices"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Select
|
||||
className="w-full sm:w-48 sm:shrink-0"
|
||||
className="w-full sm:w-48"
|
||||
value={practiceStatusFilter}
|
||||
onChange={(e) => setPracticeStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
||||
aria-label="Filter practices by status"
|
||||
|
|
@ -819,7 +837,7 @@ export function HumanLanguageSubModulePage() {
|
|||
<option value="DRAFT">Draft</option>
|
||||
<option value="ARCHIVED">Archived</option>
|
||||
</Select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
{renderQuestionSetTable(
|
||||
filteredPractices,
|
||||
practices,
|
||||
|
|
@ -833,19 +851,24 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
{activeTab === "lessons" ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
||||
<div className="relative min-w-[200px] flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={lessonSearch}
|
||||
onChange={(e) => setLessonSearch(e.target.value)}
|
||||
aria-label="Search lessons"
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={lessonActiveFilterCount}
|
||||
onClearFilters={() => setLessonActiveFilter("all")}
|
||||
search={
|
||||
<div className="relative min-w-[200px] w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={lessonSearch}
|
||||
onChange={(e) => setLessonSearch(e.target.value)}
|
||||
aria-label="Search lessons"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Select
|
||||
className="w-full sm:w-48 sm:shrink-0"
|
||||
className="w-full sm:w-48"
|
||||
value={lessonActiveFilter}
|
||||
onChange={(e) => setLessonActiveFilter(e.target.value as LessonActiveFilter)}
|
||||
aria-label="Filter lessons by status"
|
||||
|
|
@ -854,26 +877,31 @@ export function HumanLanguageSubModulePage() {
|
|||
<option value="active">Active only</option>
|
||||
<option value="inactive">Inactive only</option>
|
||||
</Select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
{renderLessonsTable(filteredLessons, lessons)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{activeTab === "capstones" ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
||||
<div className="relative min-w-[200px] flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={capstoneSearch}
|
||||
onChange={(e) => setCapstoneSearch(e.target.value)}
|
||||
aria-label="Search capstones"
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={capstoneActiveFilterCount}
|
||||
onClearFilters={() => setCapstoneStatusFilter("all")}
|
||||
search={
|
||||
<div className="relative min-w-[200px] w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by title or description…"
|
||||
value={capstoneSearch}
|
||||
onChange={(e) => setCapstoneSearch(e.target.value)}
|
||||
aria-label="Search capstones"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Select
|
||||
className="w-full sm:w-48 sm:shrink-0"
|
||||
className="w-full sm:w-48"
|
||||
value={capstoneStatusFilter}
|
||||
onChange={(e) => setCapstoneStatusFilter(e.target.value as "all" | QuestionSetStatus)}
|
||||
aria-label="Filter capstones by status"
|
||||
|
|
@ -883,7 +911,7 @@ export function HumanLanguageSubModulePage() {
|
|||
<option value="DRAFT">Draft</option>
|
||||
<option value="ARCHIVED">Archived</option>
|
||||
</Select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
{renderQuestionSetTable(
|
||||
filteredCapstones,
|
||||
capstones,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import {
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
DialogTitle,
|
||||
} from "../../components/ui/dialog"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { QuestionTypeCard } from "./components/QuestionTypeCard"
|
||||
|
|
@ -71,6 +73,11 @@ export function QuestionTypeLibraryPage() {
|
|||
const hasActiveFilters =
|
||||
query.trim().length > 0 || statusFilter !== "All" || scopeFilter !== "all"
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "All" },
|
||||
{ value: scopeFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
|
|
@ -236,28 +243,33 @@ export function QuestionTypeLibraryPage() {
|
|||
</CardHeader>
|
||||
|
||||
<CardContent className="p-0">
|
||||
<div className="border-b border-grayScale-100 bg-grayScale-50/60 px-6 py-5 space-y-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="h-11 pl-11 pr-10 rounded-[10px] border-grayScale-200 bg-white placeholder:text-grayScale-400 text-sm shadow-sm"
|
||||
placeholder="Search by display name, key, or id on this page…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
{query ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQuery("")}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-grayScale-400 hover:bg-grayScale-100 hover:text-grayScale-600"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="border-b border-grayScale-100 bg-grayScale-50/60 px-6 py-5">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 bg-transparent shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
search={
|
||||
<div className="relative">
|
||||
<Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="h-11 pl-11 pr-10 rounded-[10px] border-grayScale-200 bg-white placeholder:text-grayScale-400 text-sm shadow-sm"
|
||||
placeholder="Search by display name, key, or id on this page…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
{query ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQuery("")}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-grayScale-400 hover:bg-grayScale-100 hover:text-grayScale-600"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
|
|
@ -297,20 +309,7 @@ export function QuestionTypeLibraryPage() {
|
|||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasActiveFilters ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 shrink-0 self-start rounded-[8px] px-3 text-xs font-semibold text-grayScale-500 hover:text-brand-600 lg:self-center"
|
||||
disabled={loading}
|
||||
onClick={clearFilters}
|
||||
>
|
||||
Clear filters
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Link } from "react-router-dom"
|
|||
import { Plus, Search, Edit, Trash2, HelpCircle, X, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react"
|
||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
|
|
@ -17,6 +18,7 @@ import {
|
|||
} from "../../components/ui/table"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { deleteQuestion, getQuestionById, getQuestions, updateQuestion } from "../../api/courses.api"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import type { QuestionDetail } from "../../types/course.types"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
|
|
@ -321,6 +323,19 @@ export function QuestionsPage() {
|
|||
return pages
|
||||
}
|
||||
|
||||
const clearFilters = () => {
|
||||
setTypeFilter("all")
|
||||
setDifficultyFilter("all")
|
||||
setStatusFilter("all")
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: typeFilter, defaultValue: "all" },
|
||||
{ value: difficultyFilter, defaultValue: "all" },
|
||||
{ value: statusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Page Header */}
|
||||
|
|
@ -359,23 +374,29 @@ export function QuestionsPage() {
|
|||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5 pt-5">
|
||||
{/* Search and Filters */}
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
placeholder="Search questions..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AdminFiltersPanel
|
||||
className="border-0 shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={`Showing ${paginatedQuestions.length} of ${totalCount} questions`}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
placeholder="Search questions..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10 transition-colors focus:border-brand-300 focus:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select
|
||||
value={typeFilter}
|
||||
onChange={(e) => {
|
||||
setTypeFilter(e.target.value as QuestionTypeFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<option value="all">All Types</option>
|
||||
|
|
@ -388,6 +409,7 @@ export function QuestionsPage() {
|
|||
value={difficultyFilter}
|
||||
onChange={(e) => {
|
||||
setDifficultyFilter(e.target.value as DifficultyFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<option value="all">All Difficulties</option>
|
||||
|
|
@ -399,6 +421,7 @@ export function QuestionsPage() {
|
|||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value as StatusFilter)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<option value="all">All Statuses</option>
|
||||
|
|
@ -407,12 +430,7 @@ export function QuestionsPage() {
|
|||
<option value="INACTIVE">Inactive</option>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Results count */}
|
||||
<div className="text-xs font-medium text-grayScale-400">
|
||||
Showing {paginatedQuestions.length} of {totalCount} questions
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<Table>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
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"
|
||||
|
|
@ -30,6 +31,7 @@ import {
|
|||
} from "../../components/ui/dropdown-menu"
|
||||
import type { Course, CourseCategory, QuestionDetail, QuestionSet, SubCourse } from "../../types/course.types"
|
||||
import { toast } from "sonner"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
|
||||
const MAX_AUDIO_SIZE_BYTES = 50 * 1024 * 1024
|
||||
|
|
@ -1272,6 +1274,14 @@ export function SpeakingPage() {
|
|||
return Array.from(groups.values())
|
||||
}, [audioQuestions])
|
||||
|
||||
const clearAudioFilters = () => {
|
||||
setSelectedPracticeId("")
|
||||
setPracticeFilterSearch("")
|
||||
setAudioPage(1)
|
||||
}
|
||||
|
||||
const audioActiveFilterCount = countActiveFilters([{ value: selectedPracticeId }])
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-7xl space-y-6 pb-10 sm:space-y-8 sm:pb-12">
|
||||
<div className="flex flex-col gap-4 border-b border-grayScale-100 pb-6 sm:flex-row sm:items-end sm:justify-between sm:pb-8">
|
||||
|
|
@ -1305,68 +1315,73 @@ export function SpeakingPage() {
|
|||
<p className="mt-1 text-xs font-normal text-grayScale-500 sm:text-sm">
|
||||
Tap a row to view details. Speaking practices create AUDIO question sets linked to a sub-course.
|
||||
</p>
|
||||
<div className="mt-3 max-w-md space-y-1.5">
|
||||
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">
|
||||
Filter by practice
|
||||
</label>
|
||||
<DropdownMenu open={practiceFilterOpen} onOpenChange={setPracticeFilterOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 w-full justify-between rounded-md border border-grayScale-200 bg-white px-3 text-sm font-normal text-grayScale-700 hover:bg-grayScale-50"
|
||||
>
|
||||
<span className="truncate">
|
||||
{selectedPracticeId
|
||||
? `${practiceOptions.find((p) => p.id === Number(selectedPracticeId))?.title ?? "Practice"} (#${selectedPracticeId})`
|
||||
: "All practices"}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[420px] max-w-[92vw] p-2">
|
||||
<Input
|
||||
value={practiceFilterSearch}
|
||||
onChange={(e) => setPracticeFilterSearch(e.target.value)}
|
||||
placeholder="Search practices..."
|
||||
className="mb-2 h-9"
|
||||
/>
|
||||
<div className="max-h-64 overflow-auto">
|
||||
<DropdownMenuRadioGroup
|
||||
value={selectedPracticeId}
|
||||
onValueChange={(value) => {
|
||||
setSelectedPracticeId(value)
|
||||
setAudioPage(1)
|
||||
setPracticeFilterOpen(false)
|
||||
}}
|
||||
>
|
||||
<DropdownMenuRadioItem value="">All practices</DropdownMenuRadioItem>
|
||||
{filteredPracticeOptions.map((practice) => (
|
||||
<DropdownMenuRadioItem key={practice.id} value={String(practice.id)}>
|
||||
{practice.title} (#{practice.id})
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="mt-3 max-w-md space-y-1.5">
|
||||
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">Search</label>
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => {
|
||||
setSearchQuery(e.target.value)
|
||||
setAudioPage(1)
|
||||
}}
|
||||
placeholder="Search question text, answer text, or practice..."
|
||||
className="h-10"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs font-normal text-grayScale-400 sm:text-sm">
|
||||
Showing page {audioPage} of {Math.max(1, Math.ceil(audioTotalCount / audioPageSize))} ({audioTotalCount} total)
|
||||
</p>
|
||||
</CardHeader>
|
||||
<div className="border-b border-grayScale-100 px-5 py-4 sm:px-6">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 shadow-none"
|
||||
activeFilterCount={audioActiveFilterCount}
|
||||
onClearFilters={clearAudioFilters}
|
||||
summary={`Showing page ${audioPage} of ${Math.max(1, Math.ceil(audioTotalCount / audioPageSize))} (${audioTotalCount} total)`}
|
||||
search={
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => {
|
||||
setSearchQuery(e.target.value)
|
||||
setAudioPage(1)
|
||||
}}
|
||||
placeholder="Search question text, answer text, or practice..."
|
||||
className="h-10"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className="max-w-md space-y-1.5">
|
||||
<label className="text-xs font-medium uppercase tracking-wide text-grayScale-500">
|
||||
Filter by practice
|
||||
</label>
|
||||
<DropdownMenu open={practiceFilterOpen} onOpenChange={setPracticeFilterOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-10 w-full justify-between rounded-md border border-grayScale-200 bg-white px-3 text-sm font-normal text-grayScale-700 hover:bg-grayScale-50"
|
||||
>
|
||||
<span className="truncate">
|
||||
{selectedPracticeId
|
||||
? `${practiceOptions.find((p) => p.id === Number(selectedPracticeId))?.title ?? "Practice"} (#${selectedPracticeId})`
|
||||
: "All practices"}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[420px] max-w-[92vw] p-2">
|
||||
<Input
|
||||
value={practiceFilterSearch}
|
||||
onChange={(e) => setPracticeFilterSearch(e.target.value)}
|
||||
placeholder="Search practices..."
|
||||
className="mb-2 h-9"
|
||||
/>
|
||||
<div className="max-h-64 overflow-auto">
|
||||
<DropdownMenuRadioGroup
|
||||
value={selectedPracticeId}
|
||||
onValueChange={(value) => {
|
||||
setSelectedPracticeId(value)
|
||||
setAudioPage(1)
|
||||
setPracticeFilterOpen(false)
|
||||
}}
|
||||
>
|
||||
<DropdownMenuRadioItem value="">All practices</DropdownMenuRadioItem>
|
||||
{filteredPracticeOptions.map((practice) => (
|
||||
<DropdownMenuRadioItem key={practice.id} value={String(practice.id)}>
|
||||
{practice.title} (#{practice.id})
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
</div>
|
||||
<CardContent className="px-4 pb-6 pt-5 sm:px-6">
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center gap-2 py-14 text-center text-sm text-grayScale-500">
|
||||
|
|
|
|||
|
|
@ -16,19 +16,19 @@ import {
|
|||
createCourseVideo,
|
||||
updateSubCourseVideo,
|
||||
deleteSubCourseVideo,
|
||||
getRatings,
|
||||
getVimeoSample,
|
||||
} from "../../api/courses.api"
|
||||
import { getRatings } from "../../api/ratings.api"
|
||||
import { uploadVideoFile } from "../../api/files.api"
|
||||
import type {
|
||||
SubCourse,
|
||||
QuestionSet,
|
||||
SubCourseVideo,
|
||||
Rating,
|
||||
VimeoSampleVideo,
|
||||
VideoStatus,
|
||||
VideoVisibility,
|
||||
} from "../../types/course.types"
|
||||
import type { Rating } from "../../types/ratings.types"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
|
||||
type TabType = "video" | "practice" | "ratings"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { Search } from "lucide-react"
|
||||
import { AdminFiltersPanel } from "../../../components/filters/AdminFiltersPanel"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { Select } from "../../../components/ui/select"
|
||||
import { countActiveFilters } from "../../../lib/adminFilterUtils"
|
||||
import type { PublishStatusFilter } from "../../../lib/contentListFilters"
|
||||
import { cn } from "../../../lib/utils"
|
||||
|
||||
|
|
@ -23,28 +25,33 @@ export function ContentListSearchFilterBar({
|
|||
searchAriaLabel = "Search content",
|
||||
className,
|
||||
}: ContentListSearchFilterBarProps) {
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: publishStatusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-3 rounded-xl border border-grayScale-100 bg-white p-4 shadow-sm",
|
||||
className,
|
||||
)}
|
||||
<AdminFiltersPanel
|
||||
className={cn("shadow-sm", className)}
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={() => onPublishStatusFilterChange("all")}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400"
|
||||
aria-hidden
|
||||
/>
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder={searchPlaceholder}
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
aria-label={searchAriaLabel}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="relative min-w-[200px] flex-1">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400"
|
||||
aria-hidden
|
||||
/>
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder={searchPlaceholder}
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
aria-label={searchAriaLabel}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
className="w-full sm:w-48 sm:shrink-0"
|
||||
className="w-full sm:w-48"
|
||||
value={publishStatusFilter}
|
||||
onChange={(e) =>
|
||||
onPublishStatusFilterChange(e.target.value as PublishStatusFilter)
|
||||
|
|
@ -55,6 +62,6 @@ export function ContentListSearchFilterBar({
|
|||
<option value="PUBLISHED">Published</option>
|
||||
<option value="DRAFT">Draft</option>
|
||||
</Select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,11 +20,13 @@ import { cn } from "../../../lib/utils";
|
|||
import {
|
||||
applyShortPreviewToEmbedUrl,
|
||||
DEFAULT_PREVIEW_MAX_SECONDS,
|
||||
extractVimeoVideoId,
|
||||
formatPreviewLength,
|
||||
formatVideoDurationLabel,
|
||||
getVideoPreview,
|
||||
isDirectVideoFileUrl,
|
||||
} from "../../../lib/videoPreview";
|
||||
import { fetchVimeoDurationSeconds } from "../../../lib/vimeoVideoCache";
|
||||
import { PreviewLimitedFileVideo } from "./PreviewLimitedFileVideo";
|
||||
import type {
|
||||
ContentAccessTier,
|
||||
|
|
@ -121,6 +123,9 @@ export function VideoCard({
|
|||
const [probedDurationSeconds, setProbedDurationSeconds] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
const [vimeoDurationSeconds, setVimeoDurationSeconds] = useState<
|
||||
number | null
|
||||
>(null);
|
||||
const [previewOpen, setPreviewOpen] = useState(false);
|
||||
/** Iframe players ignore URL limits in many cases — unmount after real time. */
|
||||
const [iframeSessionDone, setIframeSessionDone] = useState(false);
|
||||
|
|
@ -194,6 +199,34 @@ export function VideoCard({
|
|||
};
|
||||
}, [duration, durationSeconds, videoUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (duration?.trim()) {
|
||||
setVimeoDurationSeconds(null);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof durationSeconds === "number" &&
|
||||
Number.isFinite(durationSeconds) &&
|
||||
durationSeconds > 0
|
||||
) {
|
||||
setVimeoDurationSeconds(null);
|
||||
return;
|
||||
}
|
||||
const url = videoUrl?.trim() ?? "";
|
||||
const vimeoId = extractVimeoVideoId(url);
|
||||
if (!vimeoId) {
|
||||
setVimeoDurationSeconds(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void fetchVimeoDurationSeconds(vimeoId).then((seconds) => {
|
||||
if (!cancelled) setVimeoDurationSeconds(seconds);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [duration, durationSeconds, videoUrl]);
|
||||
|
||||
const durationLabel = (() => {
|
||||
const trimmed = duration?.trim();
|
||||
if (trimmed) return trimmed;
|
||||
|
|
@ -204,6 +237,13 @@ export function VideoCard({
|
|||
? durationSeconds
|
||||
: null;
|
||||
if (fromApi != null) return formatVideoDurationLabel(fromApi);
|
||||
if (
|
||||
vimeoDurationSeconds != null &&
|
||||
Number.isFinite(vimeoDurationSeconds) &&
|
||||
vimeoDurationSeconds > 0
|
||||
) {
|
||||
return formatVideoDurationLabel(vimeoDurationSeconds);
|
||||
}
|
||||
if (
|
||||
probedDurationSeconds != null &&
|
||||
Number.isFinite(probedDurationSeconds) &&
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Check, ArrowRight, Loader2 } from "lucide-react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Button } from "../../../../components/ui/button";
|
||||
import {
|
||||
Avatar,
|
||||
|
|
@ -67,7 +68,10 @@ export function PersonaStep({
|
|||
No active personas available.
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-grayScale-400">
|
||||
Add personas in the admin panel, then return here.
|
||||
<Link to="/personas" className="font-medium text-brand-600 hover:underline">
|
||||
Add personas
|
||||
</Link>{" "}
|
||||
in the admin panel, then return here.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
|
|
|
|||
185
src/pages/faqs/EditFaqPage.tsx
Normal file
185
src/pages/faqs/EditFaqPage.tsx
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Link, useNavigate, useParams } from "react-router-dom"
|
||||
import { ArrowLeft } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getFAQById, getFAQs, updateFAQ } from "../../api/faq.api"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { useFaqPermissions } from "../../hooks/useFaqPermissions"
|
||||
import { deriveFaqCategories } from "../../lib/faqDisplay"
|
||||
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
||||
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
||||
import { FaqAccessDenied } from "./components/FaqAccessDenied"
|
||||
import {
|
||||
draftToUpdatePayload,
|
||||
FaqForm,
|
||||
validateFaqDraft,
|
||||
type FaqFormDraft,
|
||||
} from "./components/FaqForm"
|
||||
|
||||
function faqToDraft(faq: FAQ): FaqFormDraft {
|
||||
return {
|
||||
question: faq.question,
|
||||
answer: faq.answer,
|
||||
category: faq.category ?? "",
|
||||
display_order: String(faq.display_order ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
export function EditFaqPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const faqId = Number(id)
|
||||
const { canGet, canUpdate, loading: permissionsLoading } = useFaqPermissions()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savingAction, setSavingAction] = useState<"draft" | "publish" | null>(null)
|
||||
const [draft, setDraft] = useState<FaqFormDraft | null>(null)
|
||||
const [currentStatus, setCurrentStatus] = useState<FAQStatus>("INACTIVE")
|
||||
const [categories, setCategories] = useState<string[]>([])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!Number.isFinite(faqId) || faqId <= 0) {
|
||||
toast.error("Invalid FAQ ID")
|
||||
navigate("/help/faqs", { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
if (!canGet) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setPermissionDenied(false)
|
||||
try {
|
||||
const [faqRes, listRes] = await Promise.all([
|
||||
getFAQById(faqId),
|
||||
getFAQs({ limit: 200, offset: 0 }),
|
||||
])
|
||||
|
||||
if (!faqRes.data) {
|
||||
toast.error("FAQ not found")
|
||||
navigate("/help/faqs", { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
setDraft(faqToDraft(faqRes.data))
|
||||
setCurrentStatus(faqRes.data.status)
|
||||
setCategories(deriveFaqCategories(listRes.data.faqs))
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
if (status === 404) {
|
||||
toast.error("FAQ not found")
|
||||
navigate("/help/faqs", { replace: true })
|
||||
return
|
||||
}
|
||||
if (isFaqForbiddenError(e)) {
|
||||
setPermissionDenied(true)
|
||||
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view this FAQ"))
|
||||
return
|
||||
}
|
||||
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQ"))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [faqId, canGet, navigate])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const handleSave = async (status: FAQStatus) => {
|
||||
if (!draft) return
|
||||
if (!canUpdate) {
|
||||
toast.error("You do not have permission to update FAQs")
|
||||
return
|
||||
}
|
||||
|
||||
const validationError = validateFaqDraft(draft)
|
||||
if (validationError) {
|
||||
toast.error(validationError)
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setSavingAction(status === "ACTIVE" ? "publish" : "draft")
|
||||
try {
|
||||
const response = await updateFAQ(faqId, draftToUpdatePayload(draft, status))
|
||||
if (!response.data) {
|
||||
throw new Error("Empty update response")
|
||||
}
|
||||
setDraft(faqToDraft(response.data))
|
||||
setCurrentStatus(response.data.status)
|
||||
toast.success(
|
||||
status === "ACTIVE"
|
||||
? response.message ?? "FAQ published successfully"
|
||||
: response.message ?? "FAQ saved as draft",
|
||||
)
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
toast.error(getFaqApiErrorMessage(e, "Failed to update FAQ"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
setSavingAction(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (!permissionsLoading && !canGet) {
|
||||
return <FaqAccessDenied />
|
||||
}
|
||||
|
||||
if (!permissionsLoading && permissionDenied) {
|
||||
return <FaqAccessDenied apiForbidden />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-3xl space-y-6 pb-12">
|
||||
<Link
|
||||
to="/help/faqs"
|
||||
className="group flex w-fit items-center gap-2 text-sm font-semibold text-grayScale-600 transition-colors hover:text-brand-500"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 transition-transform group-hover:-translate-x-0.5" />
|
||||
Back to FAQs
|
||||
</Link>
|
||||
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-semibold text-grayScale-500">Help center</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-900">
|
||||
Edit FAQ
|
||||
</h1>
|
||||
<p className="max-w-2xl text-sm text-grayScale-500">
|
||||
Update question, answer, category, or display order. Save as draft or publish when ready.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardHeader className="border-b border-grayScale-100 pb-4">
|
||||
<CardTitle className="text-lg">FAQ details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-6 sm:p-8">
|
||||
{loading || !draft ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<SpinnerIcon className="h-6 w-6" />
|
||||
</div>
|
||||
) : (
|
||||
<FaqForm
|
||||
draft={draft}
|
||||
saving={saving}
|
||||
savingAction={savingAction}
|
||||
categories={categories}
|
||||
currentStatus={currentStatus}
|
||||
onChange={(patch) => setDraft((prev) => (prev ? { ...prev, ...patch } : prev))}
|
||||
onSaveDraft={() => void handleSave("INACTIVE")}
|
||||
onPublish={() => void handleSave("ACTIVE")}
|
||||
onCancel={() => navigate("/help/faqs")}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
465
src/pages/faqs/FaqsPage.tsx
Normal file
465
src/pages/faqs/FaqsPage.tsx
Normal file
|
|
@ -0,0 +1,465 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleHelp,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ExternalLink,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getFAQs, updateFAQ } from "../../api/faq.api"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../components/ui/table"
|
||||
import { useFaqPermissions } from "../../hooks/useFaqPermissions"
|
||||
import {
|
||||
deriveFaqCategories,
|
||||
faqStatusBadgeVariant,
|
||||
faqStatusLabel,
|
||||
formatFaqDate,
|
||||
suggestNextDisplayOrder,
|
||||
} from "../../lib/faqDisplay"
|
||||
import { getFaqApiErrorMessage, isFaqForbiddenError } from "../../lib/faqErrors"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { FAQ, FAQStatus } from "../../types/faq.types"
|
||||
import { CreateFaqDialog } from "./components/CreateFaqDialog"
|
||||
import { FaqDeleteDialog } from "./components/FaqDeleteDialog"
|
||||
import { FaqAccessDenied } from "./components/FaqAccessDenied"
|
||||
import { FaqPublicPreviewDialog } from "./components/FaqPublicPreviewDialog"
|
||||
|
||||
type StatusFilter = "all" | FAQStatus
|
||||
|
||||
export function FaqsPage() {
|
||||
const { canList, canCreate, canUpdate, canDelete, canGet, loading: permissionsLoading } =
|
||||
useFaqPermissions()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||
const [faqs, setFaqs] = useState<FAQ[]>([])
|
||||
const [totalCount, setTotalCount] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [query, setQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all")
|
||||
const [categoryFilter, setCategoryFilter] = useState("")
|
||||
const [allCategories, setAllCategories] = useState<string[]>([])
|
||||
const [faqPendingDelete, setFaqPendingDelete] = useState<FAQ | null>(null)
|
||||
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||
const [previewOpen, setPreviewOpen] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [suggestedDisplayOrder, setSuggestedDisplayOrder] = useState(1)
|
||||
|
||||
const offset = (page - 1) * pageSize
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!canList) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setError(false)
|
||||
setPermissionDenied(false)
|
||||
try {
|
||||
const res = await getFAQs({
|
||||
status: statusFilter === "all" ? undefined : statusFilter,
|
||||
category: categoryFilter || undefined,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
})
|
||||
setFaqs(res.data.faqs)
|
||||
setTotalCount(res.data.total_count)
|
||||
|
||||
const categoryRes = await getFAQs({ limit: 200, offset: 0 })
|
||||
setAllCategories(deriveFaqCategories(categoryRes.data.faqs))
|
||||
setSuggestedDisplayOrder(suggestNextDisplayOrder(categoryRes.data.faqs))
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setError(true)
|
||||
setFaqs([])
|
||||
setTotalCount(0)
|
||||
if (isFaqForbiddenError(e)) {
|
||||
setPermissionDenied(true)
|
||||
toast.error(getFaqApiErrorMessage(e, "You do not have permission to view FAQs"))
|
||||
} else {
|
||||
toast.error(getFaqApiErrorMessage(e, "Failed to load FAQs"))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [canList, statusFilter, categoryFilter, pageSize, offset])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1)
|
||||
}, [statusFilter, categoryFilter, pageSize])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return faqs
|
||||
return faqs.filter((faq) => {
|
||||
const haystack = [faq.question, faq.answer, faq.category ?? ""]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return haystack.includes(q)
|
||||
})
|
||||
}, [faqs, query])
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||
const pageStart = totalCount === 0 ? 0 : offset + 1
|
||||
const pageEnd = Math.min(offset + faqs.length, totalCount)
|
||||
const canPrev = page > 1
|
||||
const canNext = page < totalPages
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "all" },
|
||||
{ value: categoryFilter },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStatusFilter("all")
|
||||
setCategoryFilter("")
|
||||
}
|
||||
|
||||
const handleToggleStatus = async (faq: FAQ) => {
|
||||
if (!canUpdate) {
|
||||
toast.error("You do not have permission to update FAQs")
|
||||
return
|
||||
}
|
||||
|
||||
const nextStatus: FAQStatus = faq.status === "ACTIVE" ? "INACTIVE" : "ACTIVE"
|
||||
setTogglingId(faq.id)
|
||||
try {
|
||||
const res = await updateFAQ(faq.id, { status: nextStatus })
|
||||
if (res.data) {
|
||||
setFaqs((prev) => prev.map((row) => (row.id === faq.id ? res.data! : row)))
|
||||
}
|
||||
toast.success(
|
||||
nextStatus === "ACTIVE" ? "FAQ published" : "FAQ moved to draft",
|
||||
)
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg = getFaqApiErrorMessage(e, "Failed to update FAQ status")
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setTogglingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (!permissionsLoading && !canList) {
|
||||
return <FaqAccessDenied />
|
||||
}
|
||||
|
||||
if (!permissionsLoading && permissionDenied) {
|
||||
return <FaqAccessDenied apiForbidden />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Help center</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">
|
||||
FAQs
|
||||
</h1>
|
||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||
Manage frequently asked questions shown in the learner help center.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" className="shrink-0" onClick={() => setPreviewOpen(true)}>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Preview as learner
|
||||
</Button>
|
||||
{canCreate ? (
|
||||
<Button
|
||||
className="shrink-0 bg-brand-500 text-white hover:bg-brand-600"
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add FAQ
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="shrink-0"
|
||||
disabled={loading}
|
||||
onClick={() => void load()}
|
||||
>
|
||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
loading
|
||||
? "Loading…"
|
||||
: `${filtered.length} shown on page · ${totalCount} total`
|
||||
}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search question or answer…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(["all", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(tab)}
|
||||
className={cn(
|
||||
"h-9 rounded-full px-3 text-xs font-semibold transition-colors",
|
||||
statusFilter === tab
|
||||
? "bg-brand-500 text-white"
|
||||
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
{tab === "all" ? "All" : tab === "ACTIVE" ? "Published" : "Draft"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label htmlFor="faq-category-filter" className="text-xs font-semibold text-grayScale-500">
|
||||
Category
|
||||
</label>
|
||||
<select
|
||||
id="faq-category-filter"
|
||||
value={categoryFilter}
|
||||
onChange={(e) => setCategoryFilter(e.target.value)}
|
||||
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm text-grayScale-800"
|
||||
>
|
||||
<option value="">All categories</option>
|
||||
{allCategories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
<SpinnerIcon className="h-6 w-6" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="flex flex-col items-center gap-3 py-16 text-center">
|
||||
<p className="text-sm text-destructive">Could not load FAQs.</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
Retry
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : filtered.length === 0 ? (
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||
<div className="grid h-14 w-14 place-items-center rounded-2xl bg-brand-100/50 text-brand-500">
|
||||
<CircleHelp className="h-7 w-7" />
|
||||
</div>
|
||||
<p className="text-sm text-grayScale-500">
|
||||
{faqs.length === 0
|
||||
? "No FAQs yet. Create your first FAQ to populate the help center."
|
||||
: "No FAQs match your search or filters."}
|
||||
</p>
|
||||
{canCreate && faqs.length === 0 ? (
|
||||
<Button
|
||||
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add FAQ
|
||||
</Button>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="overflow-hidden border border-grayScale-100 shadow-none">
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Question</TableHead>
|
||||
<TableHead>Category</TableHead>
|
||||
<TableHead className="w-20 text-center">Order</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Updated</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filtered.map((faq) => (
|
||||
<TableRow key={faq.id}>
|
||||
<TableCell className="max-w-xs">
|
||||
<p className="line-clamp-2 font-medium text-grayScale-900">
|
||||
{faq.question}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{faq.category ? (
|
||||
<Badge variant="secondary">{faq.category}</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-grayScale-400">—</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-sm text-grayScale-600">
|
||||
{faq.display_order}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={faqStatusBadgeVariant(faq.status)}>
|
||||
{faqStatusLabel(faq.status)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-grayScale-500">
|
||||
{formatFaqDate(faq.updated_at || faq.created_at)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{canUpdate ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={togglingId === faq.id}
|
||||
onClick={() => void handleToggleStatus(faq)}
|
||||
title={
|
||||
faq.status === "ACTIVE" ? "Unpublish" : "Publish"
|
||||
}
|
||||
>
|
||||
{faq.status === "ACTIVE" ? (
|
||||
<EyeOff className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Eye className="h-3.5 w-3.5" />
|
||||
)}
|
||||
<span className="sr-only">
|
||||
{faq.status === "ACTIVE" ? "Unpublish" : "Publish"}
|
||||
</span>
|
||||
</Button>
|
||||
) : null}
|
||||
{canGet ? (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link to={`/help/faqs/${faq.id}/edit`}>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
<span className="sr-only">Edit</span>
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
{canDelete ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={() => setFaqPendingDelete(faq)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
<span className="sr-only">Delete</span>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{!loading && !error && totalCount > 0 ? (
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p className="text-sm text-grayScale-500">
|
||||
Showing {pageStart}–{pageEnd} of {totalCount}
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size} per page
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!canPrev}
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="text-sm text-grayScale-600">
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!canNext}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<FaqPublicPreviewDialog open={previewOpen} onOpenChange={setPreviewOpen} />
|
||||
|
||||
<CreateFaqDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
categories={allCategories}
|
||||
suggestedDisplayOrder={suggestedDisplayOrder}
|
||||
onCreated={() => void load()}
|
||||
/>
|
||||
|
||||
<FaqDeleteDialog
|
||||
faq={faqPendingDelete}
|
||||
open={faqPendingDelete !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setFaqPendingDelete(null)
|
||||
}}
|
||||
onDeleted={() => {
|
||||
setFaqPendingDelete(null)
|
||||
void load()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
111
src/pages/faqs/components/CreateFaqDialog.tsx
Normal file
111
src/pages/faqs/components/CreateFaqDialog.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { Plus } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { createFAQ } from "../../../api/faq.api"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
|
||||
import {
|
||||
draftToCreatePayload,
|
||||
EMPTY_FAQ_FORM_DRAFT,
|
||||
FaqForm,
|
||||
validateFaqDraft,
|
||||
type FaqFormDraft,
|
||||
} from "./FaqForm"
|
||||
import type { FAQStatus } from "../../../types/faq.types"
|
||||
|
||||
type CreateFaqDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
categories: string[]
|
||||
suggestedDisplayOrder: number
|
||||
onCreated?: () => void
|
||||
}
|
||||
|
||||
export function CreateFaqDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
categories,
|
||||
suggestedDisplayOrder,
|
||||
onCreated,
|
||||
}: CreateFaqDialogProps) {
|
||||
const [draft, setDraft] = useState<FaqFormDraft>(EMPTY_FAQ_FORM_DRAFT)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [savingAction, setSavingAction] = useState<"draft" | "publish" | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDraft({
|
||||
...EMPTY_FAQ_FORM_DRAFT,
|
||||
display_order: String(suggestedDisplayOrder),
|
||||
})
|
||||
setSavingAction(null)
|
||||
}
|
||||
}, [open, suggestedDisplayOrder])
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !saving) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleCreate = async (status: FAQStatus) => {
|
||||
const validationError = validateFaqDraft(draft)
|
||||
if (validationError) {
|
||||
toast.error(validationError)
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setSavingAction(status === "ACTIVE" ? "publish" : "draft")
|
||||
try {
|
||||
const response = await createFAQ(draftToCreatePayload(draft, status))
|
||||
if (!response.data) {
|
||||
throw new Error("Empty create response")
|
||||
}
|
||||
toast.success(
|
||||
status === "ACTIVE"
|
||||
? response.message ?? "FAQ published successfully"
|
||||
: response.message ?? "FAQ saved as draft",
|
||||
)
|
||||
onOpenChange(false)
|
||||
onCreated?.()
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
toast.error(getFaqApiErrorMessage(e, "Failed to create FAQ"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
setSavingAction(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Plus className="h-5 w-5 text-brand-500" />
|
||||
New FAQ
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a question and answer for the learner help center.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<FaqForm
|
||||
draft={draft}
|
||||
saving={saving}
|
||||
savingAction={savingAction}
|
||||
categories={categories}
|
||||
onChange={(patch) => setDraft((prev) => ({ ...prev, ...patch }))}
|
||||
onSaveDraft={() => void handleCreate("INACTIVE")}
|
||||
onPublish={() => void handleCreate("ACTIVE")}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
97
src/pages/faqs/components/FaqAccessDenied.tsx
Normal file
97
src/pages/faqs/components/FaqAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { CircleHelp, LogOut, RefreshCw } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Card, CardContent } from "../../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { getSessionTeamRole, hasFaqRoleBypass } from "../../../lib/faqPermissions"
|
||||
import { FAQ_FORBIDDEN_MESSAGE } from "../../../lib/faqErrors"
|
||||
|
||||
type FaqAccessDeniedProps = {
|
||||
apiForbidden?: boolean
|
||||
}
|
||||
|
||||
export function FaqAccessDenied({ apiForbidden = false }: FaqAccessDeniedProps) {
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const teamRole = getSessionTeamRole()
|
||||
const canSync = hasFaqRoleBypass()
|
||||
|
||||
const handleSync = async () => {
|
||||
setSyncing(true)
|
||||
try {
|
||||
const res = await syncRbacPermissions()
|
||||
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg =
|
||||
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||
"Failed to sync RBAC permissions"
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||
<CircleHelp className="h-10 w-10 text-grayScale-300" />
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||
{apiForbidden ? "FAQ access denied" : "No permission to view FAQs"}
|
||||
</h2>
|
||||
<p className="text-sm text-grayScale-600">
|
||||
{apiForbidden
|
||||
? FAQ_FORBIDDEN_MESSAGE
|
||||
: "Your account does not have the faqs.list permission."}
|
||||
</p>
|
||||
{teamRole ? (
|
||||
<p className="text-xs text-grayScale-500">
|
||||
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||
<li>Use a team account mapped to ADMIN, SUPER_ADMIN, or INSTRUCTOR with faqs.* permissions</li>
|
||||
<li>Ensure migrations 000059 and 000084 are applied on the API database</li>
|
||||
<li>After RBAC sync or deploy, sign out and sign in again for a fresh token</li>
|
||||
<li>Custom roles need faqs.list, faqs.get, faqs.create, faqs.update, and faqs.delete assigned</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{canSync ? (
|
||||
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||
{syncing ? (
|
||||
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sync RBAC permissions
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="outline" asChild>
|
||||
<Link to="/roles">Manage roles</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
localStorage.clear()
|
||||
window.location.href = "/login"
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign in again
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
91
src/pages/faqs/components/FaqDeleteDialog.tsx
Normal file
91
src/pages/faqs/components/FaqDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useState } from "react"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { deleteFAQ } from "../../../api/faq.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { getFaqApiErrorMessage } from "../../../lib/faqErrors"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import type { FAQ } from "../../../types/faq.types"
|
||||
|
||||
type FaqDeleteDialogProps = {
|
||||
faq: FAQ | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onDeleted?: () => void
|
||||
}
|
||||
|
||||
export function FaqDeleteDialog({
|
||||
faq,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDeleted,
|
||||
}: FaqDeleteDialogProps) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !deleting) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!faq) return
|
||||
|
||||
setDeleting(true)
|
||||
try {
|
||||
const response = await deleteFAQ(faq.id)
|
||||
toast.success(response.message ?? "FAQ deleted successfully")
|
||||
onOpenChange(false)
|
||||
onDeleted?.()
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg = getFaqApiErrorMessage(e, "Failed to delete FAQ")
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||
Delete FAQ?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-left text-grayScale-600">
|
||||
This permanently removes the FAQ from the help center. This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{faq ? (
|
||||
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||
<p className="text-sm font-semibold text-grayScale-900">{faq.question}</p>
|
||||
<p className="text-xs text-grayScale-500">#{faq.id}</p>
|
||||
</div>
|
||||
) : null}
|
||||
<DialogFooter className="gap-2 sm:gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={deleting}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleting || !faq}
|
||||
onClick={() => void handleConfirm()}
|
||||
>
|
||||
{deleting ? "Deleting…" : "Delete FAQ"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
167
src/pages/faqs/components/FaqForm.tsx
Normal file
167
src/pages/faqs/components/FaqForm.tsx
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
import { Badge } from "../../../components/ui/badge"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { Textarea } from "../../../components/ui/textarea"
|
||||
import { faqStatusBadgeVariant, faqStatusLabel } from "../../../lib/faqDisplay"
|
||||
import type { FAQStatus } from "../../../types/faq.types"
|
||||
|
||||
export type FaqFormDraft = {
|
||||
question: string
|
||||
answer: string
|
||||
category: string
|
||||
display_order: string
|
||||
}
|
||||
|
||||
export const EMPTY_FAQ_FORM_DRAFT: FaqFormDraft = {
|
||||
question: "",
|
||||
answer: "",
|
||||
category: "",
|
||||
display_order: "0",
|
||||
}
|
||||
|
||||
type FaqFormProps = {
|
||||
draft: FaqFormDraft
|
||||
saving: boolean
|
||||
savingAction?: "draft" | "publish" | null
|
||||
categories: string[]
|
||||
currentStatus?: FAQStatus
|
||||
onChange: (patch: Partial<FaqFormDraft>) => void
|
||||
onSaveDraft: () => void
|
||||
onPublish: () => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
export function FaqForm({
|
||||
draft,
|
||||
saving,
|
||||
savingAction = null,
|
||||
categories,
|
||||
currentStatus,
|
||||
onChange,
|
||||
onSaveDraft,
|
||||
onPublish,
|
||||
onCancel,
|
||||
}: FaqFormProps) {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||
Question
|
||||
</p>
|
||||
<Textarea
|
||||
value={draft.question}
|
||||
onChange={(e) => onChange({ question: e.target.value })}
|
||||
placeholder="How do I reset my password?"
|
||||
rows={2}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||
Answer
|
||||
</p>
|
||||
<Textarea
|
||||
value={draft.answer}
|
||||
onChange={(e) => onChange({ answer: e.target.value })}
|
||||
placeholder="Go to login and click 'Forgot Password'."
|
||||
rows={6}
|
||||
disabled={saving}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-grayScale-400">Plain text only.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||
Category
|
||||
</p>
|
||||
<Input
|
||||
value={draft.category}
|
||||
onChange={(e) => onChange({ category: e.target.value })}
|
||||
placeholder="Account"
|
||||
list="faq-category-suggestions"
|
||||
disabled={saving}
|
||||
/>
|
||||
{categories.length > 0 ? (
|
||||
<datalist id="faq-category-suggestions">
|
||||
{categories.map((category) => (
|
||||
<option key={category} value={category} />
|
||||
))}
|
||||
</datalist>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-500">
|
||||
Display order
|
||||
</p>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={draft.display_order}
|
||||
onChange={(e) => onChange({ display_order: e.target.value })}
|
||||
disabled={saving}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-grayScale-400">
|
||||
Lower numbers appear first.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-grayScale-100 pt-5">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" disabled={saving} onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
{currentStatus ? (
|
||||
<Badge variant={faqStatusBadgeVariant(currentStatus)}>
|
||||
Currently {faqStatusLabel(currentStatus)}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
onClick={onSaveDraft}
|
||||
>
|
||||
{saving && savingAction === "draft" ? "Saving draft…" : "Save as draft"}
|
||||
</Button>
|
||||
<Button
|
||||
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||
disabled={saving}
|
||||
onClick={onPublish}
|
||||
>
|
||||
{saving && savingAction === "publish" ? "Publishing…" : "Publish FAQ"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function validateFaqDraft(draft: FaqFormDraft): string | null {
|
||||
if (!draft.question.trim()) return "Question is required"
|
||||
if (!draft.answer.trim()) return "Answer is required"
|
||||
const order = Number(draft.display_order)
|
||||
if (!Number.isFinite(order) || order < 0) {
|
||||
return "Display order must be a non-negative number"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function draftToCreatePayload(draft: FaqFormDraft, status: FAQStatus) {
|
||||
const category = draft.category.trim()
|
||||
return {
|
||||
question: draft.question.trim(),
|
||||
answer: draft.answer.trim(),
|
||||
category: category || null,
|
||||
display_order: Number(draft.display_order),
|
||||
status,
|
||||
}
|
||||
}
|
||||
|
||||
export function draftToUpdatePayload(draft: FaqFormDraft, status: FAQStatus) {
|
||||
return draftToCreatePayload(draft, status)
|
||||
}
|
||||
136
src/pages/faqs/components/FaqPublicPreviewDialog.tsx
Normal file
136
src/pages/faqs/components/FaqPublicPreviewDialog.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Eye } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getPublicFAQs } from "../../../api/faq.api"
|
||||
import { Badge } from "../../../components/ui/badge"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { deriveFaqCategories } from "../../../lib/faqDisplay"
|
||||
import type { FAQ } from "../../../types/faq.types"
|
||||
|
||||
type FaqPublicPreviewDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function FaqPublicPreviewDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: FaqPublicPreviewDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [faqs, setFaqs] = useState<FAQ[]>([])
|
||||
const [categoryFilter, setCategoryFilter] = useState("")
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await getPublicFAQs({ limit: 200, offset: 0 })
|
||||
setFaqs(res.data.faqs)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setFaqs([])
|
||||
toast.error("Failed to load public FAQ preview")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
void load()
|
||||
}
|
||||
}, [open, load])
|
||||
|
||||
const categories = deriveFaqCategories(faqs)
|
||||
const filtered = categoryFilter
|
||||
? faqs.filter((faq) => faq.category === categoryFilter)
|
||||
: faqs
|
||||
|
||||
const grouped = filtered.reduce<Record<string, FAQ[]>>((acc, faq) => {
|
||||
const key = faq.category?.trim() || "General"
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key].push(faq)
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5 text-brand-500" />
|
||||
Preview as learner
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Published FAQs from GET /faqs (ACTIVE only, no authentication).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label htmlFor="preview-category" className="text-xs font-semibold text-grayScale-500">
|
||||
Category
|
||||
</label>
|
||||
<select
|
||||
id="preview-category"
|
||||
value={categoryFilter}
|
||||
onChange={(e) => setCategoryFilter(e.target.value)}
|
||||
className="h-9 rounded-lg border border-grayScale-200 bg-white px-3 text-sm"
|
||||
>
|
||||
<option value="">All categories</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button variant="outline" size="sm" disabled={loading} onClick={() => void load()}>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[55vh] space-y-4 overflow-y-auto pr-1">
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-12">
|
||||
<SpinnerIcon className="h-6 w-6" />
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<p className="py-12 text-center text-sm text-grayScale-500">
|
||||
No published FAQs are visible on the public help center.
|
||||
</p>
|
||||
) : (
|
||||
Object.entries(grouped).map(([category, rows]) => (
|
||||
<div key={category} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-semibold text-grayScale-800">{category}</h3>
|
||||
<Badge variant="secondary" className="text-[10px]">
|
||||
{rows.length}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{rows.map((faq) => (
|
||||
<div
|
||||
key={faq.id}
|
||||
className="rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3"
|
||||
>
|
||||
<p className="text-sm font-semibold text-grayScale-900">{faq.question}</p>
|
||||
<p className="mt-1 whitespace-pre-wrap text-sm text-grayScale-600">
|
||||
{faq.answer}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
|
@ -10,7 +10,6 @@ import {
|
|||
Clock,
|
||||
User,
|
||||
Trash2,
|
||||
X,
|
||||
Info,
|
||||
Bug,
|
||||
Video,
|
||||
|
|
@ -22,8 +21,10 @@ import {
|
|||
ArrowUpCircle,
|
||||
MessageCircle,
|
||||
} from "lucide-react";
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
|
|
@ -300,10 +301,12 @@ export function IssuesPage() {
|
|||
}
|
||||
};
|
||||
|
||||
const hasActiveFilters = statusFilter || typeFilter;
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter },
|
||||
{ value: typeFilter },
|
||||
]);
|
||||
|
||||
const clearFilters = () => {
|
||||
setSearchQuery("");
|
||||
setStatusFilter("");
|
||||
setTypeFilter("");
|
||||
setPage(1);
|
||||
|
|
@ -423,68 +426,66 @@ export function IssuesPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by subject, description, or type..."
|
||||
className="pl-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
loading
|
||||
? "Loading…"
|
||||
: `${filteredIssues.length} shown · ${totalCount} total`
|
||||
}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by subject, description, or type..."
|
||||
className="pl-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="relative">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Status: All</option>
|
||||
{STATUSES.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{getStatusConfig(s).label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Status: All</option>
|
||||
{STATUSES.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{getStatusConfig(s).label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
<div className="relative">
|
||||
<select
|
||||
value={typeFilter}
|
||||
onChange={(e) => {
|
||||
setTypeFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Type: All</option>
|
||||
{ISSUE_TYPES.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{getIssueTypeConfig(t).label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
value={typeFilter}
|
||||
onChange={(e) => {
|
||||
setTypeFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Type: All</option>
|
||||
{ISSUE_TYPES.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{getIssueTypeConfig(t).label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
{hasActiveFilters && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={clearFilters}
|
||||
className="gap-1 text-grayScale-400 hover:text-grayScale-600"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-xl border bg-white">
|
||||
|
|
@ -518,7 +519,7 @@ export function IssuesPage() {
|
|||
<div>
|
||||
<p className="text-sm font-medium text-grayScale-500">No issues found</p>
|
||||
<p className="text-xs text-grayScale-400 mt-1">
|
||||
{hasActiveFilters || searchQuery
|
||||
{activeFilterCount > 0 || searchQuery
|
||||
? "Try adjusting your filters or search query"
|
||||
: "Reported issues will appear here"}
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -6,10 +6,12 @@ import {
|
|||
getEmailTemplates,
|
||||
parseEmailTemplatesResponse,
|
||||
} from "../../api/emailTemplates.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { cn } from "../../lib/utils"
|
||||
import {
|
||||
|
|
@ -69,6 +71,14 @@ export function EmailTemplatesPage() {
|
|||
})
|
||||
}, [templates, query, statusFilter])
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "All" },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStatusFilter("All")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
|
|
@ -101,43 +111,44 @@ export function EmailTemplatesPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="space-y-4 p-4 sm:p-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by name, slug, subject, or variable…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(["All", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(tab)}
|
||||
className={cn(
|
||||
"h-9 rounded-full px-3 text-xs font-semibold transition-colors",
|
||||
statusFilter === tab
|
||||
? "bg-brand-500 text-white"
|
||||
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
{tab === "All" ? "All" : tab === "ACTIVE" ? "Active" : "Inactive"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
loading
|
||||
? "Loading…"
|
||||
: `${filtered.length} shown · ${totalCount} total from API`
|
||||
}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="pl-9"
|
||||
placeholder="Search by name, slug, subject, or variable…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{loading
|
||||
? "Loading…"
|
||||
: `${filtered.length} shown · ${totalCount} total from API`}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(["All", "ACTIVE", "INACTIVE"] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setStatusFilter(tab)}
|
||||
className={cn(
|
||||
"h-9 rounded-full px-3 text-xs font-semibold transition-colors",
|
||||
statusFilter === tab
|
||||
? "bg-brand-500 text-white"
|
||||
: "bg-grayScale-100 text-grayScale-600 hover:bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
{tab === "All" ? "All" : tab === "ACTIVE" ? "Active" : "Inactive"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex justify-center py-16">
|
||||
|
|
|
|||
|
|
@ -11,7 +11,9 @@ import {
|
|||
MailX,
|
||||
Search,
|
||||
ChevronDown,
|
||||
Trash2,
|
||||
} from "lucide-react"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
|
|
@ -24,6 +26,7 @@ import {
|
|||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "../../components/ui/dropdown-menu"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
|
|
@ -37,6 +40,7 @@ import {
|
|||
markAllUnread,
|
||||
} from "../../api/notifications.api"
|
||||
import { NotificationDetailDialog } from "../../components/notifications/NotificationDetailDialog"
|
||||
import { NotificationDeleteDialog } from "../../components/notifications/NotificationDeleteDialog"
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_TYPE_CONFIG,
|
||||
formatNotificationTimestamp,
|
||||
|
|
@ -183,6 +187,7 @@ export function NotificationsPage() {
|
|||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
const [detailError, setDetailError] = useState(false)
|
||||
const [notificationPendingDelete, setNotificationPendingDelete] = useState<Notification | null>(null)
|
||||
|
||||
const [channelFilter, setChannelFilter] = useState<"all" | "push" | "sms">("all")
|
||||
const [activeStatusTab, setActiveStatusTab] = useState<"all" | "read" | "unread">("all")
|
||||
|
|
@ -303,6 +308,20 @@ export function NotificationsPage() {
|
|||
return true
|
||||
})
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: activeStatusTab, defaultValue: "all" },
|
||||
{ value: channelFilter, defaultValue: "all" },
|
||||
{ value: typeFilter, defaultValue: "all" },
|
||||
{ value: levelFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setActiveStatusTab("all")
|
||||
setChannelFilter("all")
|
||||
setTypeFilter("all")
|
||||
setLevelFilter("all")
|
||||
}
|
||||
|
||||
const loadNotificationDetail = useCallback(async (id: string) => {
|
||||
setDetailLoading(true)
|
||||
setDetailError(false)
|
||||
|
|
@ -341,6 +360,22 @@ export function NotificationsPage() {
|
|||
void loadNotificationDetail(notification.id)
|
||||
}
|
||||
|
||||
const handleNotificationDeleted = useCallback((id: string) => {
|
||||
const removed = notifications.find((n) => n.id === id)
|
||||
setNotifications((prev) => prev.filter((n) => n.id !== id))
|
||||
setTotalCount((prev) => Math.max(0, prev - 1))
|
||||
if (removed && !removed.is_read) {
|
||||
setGlobalUnread((prev) => Math.max(0, prev - 1))
|
||||
}
|
||||
if (selectedNotificationId === id) {
|
||||
setDetailOpen(false)
|
||||
setSelectedNotification(null)
|
||||
setSelectedNotificationId(null)
|
||||
}
|
||||
setNotificationPendingDelete(null)
|
||||
window.dispatchEvent(new Event("notifications-updated"))
|
||||
}, [notifications, selectedNotificationId])
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl bg-grayScale-50/60 rounded-2xl px-3 py-4 sm:px-4 sm:py-5">
|
||||
{/* Header */}
|
||||
|
|
@ -485,34 +520,13 @@ export function NotificationsPage() {
|
|||
{/* Filters + table */}
|
||||
{!loading && !error && notifications.length > 0 && (
|
||||
<>
|
||||
{/* Status tabs */}
|
||||
<div className="mb-2 border-b border-grayScale-200">
|
||||
<div className="-mb-px flex gap-6">
|
||||
{(["all", "unread", "read"] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setActiveStatusTab(tab)}
|
||||
className={cn(
|
||||
"relative px-1 pb-3.5 pt-1 text-sm font-semibold transition-all",
|
||||
activeStatusTab === tab
|
||||
? "text-brand-600"
|
||||
: "text-grayScale-400 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
{tab === "all" ? "All" : tab === "unread" ? "Unread" : "Read"}
|
||||
{activeStatusTab === tab && (
|
||||
<span className="absolute inset-x-0 bottom-0 h-0.5 rounded-full bg-brand-500" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<Card className="mb-3 shadow-none">
|
||||
<CardContent className="flex flex-wrap items-center gap-3 p-4">
|
||||
<div className="relative flex-1 min-w-[180px] max-w-sm">
|
||||
<AdminFiltersPanel
|
||||
className="mb-3"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={`${filteredNotifications.length} shown · ${totalCount} total`}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by title, message, or type…"
|
||||
|
|
@ -521,84 +535,107 @@ export function NotificationsPage() {
|
|||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Channel</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[130px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">{channelFilter === "all" ? "All" : channelFilter.toUpperCase()}</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[130px]">
|
||||
<DropdownMenuRadioGroup
|
||||
value={channelFilter}
|
||||
onValueChange={(value) => setChannelFilter(value as typeof channelFilter)}
|
||||
>
|
||||
<DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="push">Push</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="sms">SMS</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Type</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[150px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">
|
||||
{typeFilter === "all" ? "All types" : formatNotificationTypeLabel(typeFilter)}
|
||||
</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[220px]">
|
||||
<DropdownMenuRadioGroup value={typeFilter} onValueChange={setTypeFilter}>
|
||||
<DropdownMenuRadioItem value="all">All types</DropdownMenuRadioItem>
|
||||
{Array.from(new Set(notifications.map((n) => n.type))).map((t) => (
|
||||
<DropdownMenuRadioItem key={t} value={t}>
|
||||
{formatNotificationTypeLabel(t)}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Level</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[130px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">{levelFilter === "all" ? "All levels" : levelFilter}</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[150px]">
|
||||
<DropdownMenuRadioGroup value={levelFilter} onValueChange={setLevelFilter}>
|
||||
<DropdownMenuRadioItem value="all">All levels</DropdownMenuRadioItem>
|
||||
{Array.from(new Set(notifications.map((n) => n.level))).map((lvl) => (
|
||||
<DropdownMenuRadioItem key={lvl} value={lvl}>
|
||||
{lvl}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="border-b border-grayScale-200">
|
||||
<div className="-mb-px flex gap-6">
|
||||
{(["all", "unread", "read"] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
type="button"
|
||||
onClick={() => setActiveStatusTab(tab)}
|
||||
className={cn(
|
||||
"relative px-1 pb-3.5 pt-1 text-sm font-semibold transition-all",
|
||||
activeStatusTab === tab
|
||||
? "text-brand-600"
|
||||
: "text-grayScale-400 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
{tab === "all" ? "All" : tab === "unread" ? "Unread" : "Read"}
|
||||
{activeStatusTab === tab && (
|
||||
<span className="absolute inset-x-0 bottom-0 h-0.5 rounded-full bg-brand-500" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Channel</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[130px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">{channelFilter === "all" ? "All" : channelFilter.toUpperCase()}</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[130px]">
|
||||
<DropdownMenuRadioGroup
|
||||
value={channelFilter}
|
||||
onValueChange={(value) => setChannelFilter(value as typeof channelFilter)}
|
||||
>
|
||||
<DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="push">Push</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="sms">SMS</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Type</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[150px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">
|
||||
{typeFilter === "all" ? "All types" : formatNotificationTypeLabel(typeFilter)}
|
||||
</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[220px]">
|
||||
<DropdownMenuRadioGroup value={typeFilter} onValueChange={setTypeFilter}>
|
||||
<DropdownMenuRadioItem value="all">All types</DropdownMenuRadioItem>
|
||||
{Array.from(new Set(notifications.map((n) => n.type))).map((t) => (
|
||||
<DropdownMenuRadioItem key={t} value={t}>
|
||||
{formatNotificationTypeLabel(t)}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-grayScale-500">Level</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 w-[130px] justify-between rounded-lg border-grayScale-200 px-2.5 text-xs font-normal text-grayScale-600"
|
||||
>
|
||||
<span className="truncate">{levelFilter === "all" ? "All levels" : levelFilter}</span>
|
||||
<ChevronDown className="ml-2 h-3.5 w-3.5 text-grayScale-400" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[150px]">
|
||||
<DropdownMenuRadioGroup value={levelFilter} onValueChange={setLevelFilter}>
|
||||
<DropdownMenuRadioItem value="all">All levels</DropdownMenuRadioItem>
|
||||
{Array.from(new Set(notifications.map((n) => n.level))).map((lvl) => (
|
||||
<DropdownMenuRadioItem key={lvl} value={lvl}>
|
||||
{lvl}
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<Card className="overflow-hidden rounded-xl border bg-white shadow-none">
|
||||
<CardContent className="p-0">
|
||||
|
|
@ -719,6 +756,15 @@ export function NotificationsPage() {
|
|||
>
|
||||
View
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={() => setNotificationPendingDelete(n)}
|
||||
title="Delete notification"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
|
@ -815,6 +861,20 @@ export function NotificationsPage() {
|
|||
? () => void loadNotificationDetail(selectedNotificationId)
|
||||
: undefined
|
||||
}
|
||||
onDelete={
|
||||
selectedNotification
|
||||
? () => setNotificationPendingDelete(selectedNotification)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<NotificationDeleteDialog
|
||||
notification={notificationPendingDelete}
|
||||
open={notificationPendingDelete !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setNotificationPendingDelete(null)
|
||||
}}
|
||||
onDeleted={handleNotificationDeleted}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import {
|
|||
cancelScheduledNotification,
|
||||
getScheduledNotifications,
|
||||
} from "../../api/notifications.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
|
|
@ -32,6 +33,7 @@ import {
|
|||
formatScheduledAtLabel,
|
||||
scheduledStatusBadgeVariant,
|
||||
} from "../../lib/notificationBulk"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination"
|
||||
import type {
|
||||
|
|
@ -133,6 +135,16 @@ export function ScheduledNotificationsPage() {
|
|||
return "—"
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter },
|
||||
{ value: channelFilter },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStatusFilter("")
|
||||
setChannelFilter("")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
|
|
@ -160,36 +172,43 @@ export function ScheduledNotificationsPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
loading
|
||||
? "Loading…"
|
||||
: `${totalCount} job${totalCount === 1 ? "" : "s"}`
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<Select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
|
||||
className="sm:max-w-[180px]"
|
||||
>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
value={channelFilter}
|
||||
onChange={(e) => setChannelFilter(e.target.value as typeof channelFilter)}
|
||||
className="sm:max-w-[180px]"
|
||||
>
|
||||
{CHANNEL_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="space-y-4 p-4 sm:p-6">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<Select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
|
||||
className="sm:max-w-[180px]"
|
||||
>
|
||||
{STATUS_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
value={channelFilter}
|
||||
onChange={(e) => setChannelFilter(e.target.value as typeof channelFilter)}
|
||||
className="sm:max-w-[180px]"
|
||||
>
|
||||
{CHANNEL_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Badge variant="secondary" className="w-fit">
|
||||
{totalCount} job{totalCount === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center py-16 text-sm text-grayScale-500">
|
||||
<SpinnerIcon className="mr-2 h-5 w-5" alt="" />
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
import { Link } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
import { getPayments } from "../../api/payments.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
|
|
@ -26,7 +27,9 @@ import {
|
|||
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 { cn } from "../../lib/utils"
|
||||
import {
|
||||
formatPaymentAmount,
|
||||
|
|
@ -37,6 +40,7 @@ import {
|
|||
paymentCustomerName,
|
||||
paymentStatusBadgeVariant,
|
||||
} from "../../lib/payments"
|
||||
import { SUBSCRIPTION_CURRENCIES } from "../../lib/subscriptionPlans"
|
||||
import type {
|
||||
Payment,
|
||||
PaymentPlanCategory,
|
||||
|
|
@ -92,19 +96,11 @@ export function PaymentsPage() {
|
|||
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
||||
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
|
||||
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
|
||||
const [currencyInput, setCurrencyInput] = useState("")
|
||||
const [referenceInput, setReferenceInput] = useState("")
|
||||
const [currencyFilter, setCurrencyFilter] = useState("")
|
||||
const [referenceInput, setReferenceInput] = useState("")
|
||||
const [referenceFilter, setReferenceFilter] = useState("")
|
||||
const [selected, setSelected] = useState<Payment | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setCurrencyFilter(currencyInput.trim().toUpperCase())
|
||||
}, TEXT_FILTER_DEBOUNCE_MS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [currencyInput])
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setReferenceFilter(referenceInput.trim())
|
||||
|
|
@ -114,7 +110,7 @@ export function PaymentsPage() {
|
|||
|
||||
useEffect(() => {
|
||||
setOffset(0)
|
||||
}, [currencyFilter, referenceFilter])
|
||||
}, [referenceFilter])
|
||||
|
||||
const listFilters: PaymentListFilters = {
|
||||
status: statusFilter,
|
||||
|
|
@ -124,13 +120,15 @@ export function PaymentsPage() {
|
|||
reference: referenceFilter,
|
||||
}
|
||||
|
||||
const hasActiveFilters = Boolean(
|
||||
listFilters.status ||
|
||||
listFilters.provider ||
|
||||
listFilters.planCategory ||
|
||||
listFilters.currency ||
|
||||
listFilters.reference,
|
||||
)
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter },
|
||||
{ value: providerFilter },
|
||||
{ value: planCategoryFilter },
|
||||
{ value: currencyFilter },
|
||||
{ value: referenceFilter },
|
||||
])
|
||||
|
||||
const hasActiveFilters = activeFilterCount > 0
|
||||
|
||||
const fetchPayments = useCallback(
|
||||
async (nextOffset: number, limit: number, filters: PaymentListFilters) => {
|
||||
|
|
@ -193,9 +191,8 @@ export function PaymentsPage() {
|
|||
setStatusFilter("")
|
||||
setProviderFilter("")
|
||||
setPlanCategoryFilter("")
|
||||
setCurrencyInput("")
|
||||
setReferenceInput("")
|
||||
setCurrencyFilter("")
|
||||
setReferenceInput("")
|
||||
setReferenceFilter("")
|
||||
setOffset(0)
|
||||
}
|
||||
|
|
@ -282,7 +279,10 @@ export function PaymentsPage() {
|
|||
<CardTitle className="text-sm font-bold text-grayScale-900">Transaction history</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||
<div className="flex flex-col gap-3 rounded-[8px] border border-grayScale-100 bg-grayScale-50/40 p-3 sm:p-4">
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="mr-1 text-[11px] font-bold uppercase tracking-wider text-grayScale-400">
|
||||
Status
|
||||
|
|
@ -333,27 +333,23 @@ export function PaymentsPage() {
|
|||
>
|
||||
Currency
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="payments-currency-filter"
|
||||
value={currencyInput}
|
||||
onChange={(e) => setCurrencyInput(e.target.value)}
|
||||
placeholder="e.g. ETB"
|
||||
disabled={loading}
|
||||
className="h-9 rounded-[6px] border-grayScale-200 pr-8 text-sm uppercase"
|
||||
/>
|
||||
{currencyInput ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Clear currency filter"
|
||||
disabled={loading}
|
||||
onClick={() => setCurrencyInput("")}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-grayScale-400 hover:text-grayScale-600"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<Select
|
||||
id="payments-currency-filter"
|
||||
value={currencyFilter}
|
||||
onChange={(e) => {
|
||||
setCurrencyFilter(e.target.value)
|
||||
setOffset(0)
|
||||
}}
|
||||
disabled={loading}
|
||||
className="h-9 rounded-[6px] text-sm"
|
||||
>
|
||||
<option value="">All currencies</option>
|
||||
{SUBSCRIPTION_CURRENCIES.map((currency) => (
|
||||
<option key={currency} value={currency}>
|
||||
{currency}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label
|
||||
|
|
@ -389,21 +385,7 @@ export function PaymentsPage() {
|
|||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{hasActiveFilters ? (
|
||||
<div className="flex justify-end border-t border-grayScale-100 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 rounded-[6px] px-2 text-xs text-grayScale-500"
|
||||
disabled={loading}
|
||||
onClick={clearFilters}
|
||||
>
|
||||
Clear all filters
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||
|
|
|
|||
441
src/pages/personas/PersonasPage.tsx
Normal file
441
src/pages/personas/PersonasPage.tsx
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Pencil,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Trash2,
|
||||
UserCircle2,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { listPersonas, updatePersona } from "../../api/personas.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { ToggleSwitch } from "../../components/ui/toggle-switch"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../components/ui/table"
|
||||
import { usePersonaPermissions } from "../../hooks/usePersonaPermissions"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import {
|
||||
formatPersonaDate,
|
||||
personaAvatarUrl,
|
||||
personaGenderLabel,
|
||||
personaStatusLabel,
|
||||
} from "../../lib/personaDisplay"
|
||||
import {
|
||||
getPersonaApiErrorMessage,
|
||||
isPersonaForbiddenError,
|
||||
} from "../../lib/personasErrors"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import type { LmsPersona } from "../../types/persona.types"
|
||||
import { CreatePersonaDialog } from "./components/CreatePersonaDialog"
|
||||
import { EditPersonaDialog } from "./components/EditPersonaDialog"
|
||||
import { PersonaAccessDenied } from "./components/PersonaAccessDenied"
|
||||
import { PersonaDeleteDialog } from "./components/PersonaDeleteDialog"
|
||||
|
||||
type PersonaStatusFilter = "all" | "active" | "inactive"
|
||||
|
||||
export function PersonasPage() {
|
||||
const {
|
||||
canList,
|
||||
canCreate,
|
||||
canUpdate,
|
||||
canDelete,
|
||||
loading: permissionsLoading,
|
||||
} = usePersonaPermissions()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||
const [personas, setPersonas] = useState<LmsPersona[]>([])
|
||||
const [totalCount, setTotalCount] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [query, setQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<PersonaStatusFilter>("all")
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [personaPendingEdit, setPersonaPendingEdit] = useState<LmsPersona | null>(null)
|
||||
const [personaPendingDelete, setPersonaPendingDelete] = useState<LmsPersona | null>(null)
|
||||
const [togglingId, setTogglingId] = useState<number | null>(null)
|
||||
|
||||
const offset = (page - 1) * pageSize
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!canList) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setError(false)
|
||||
setPermissionDenied(false)
|
||||
|
||||
try {
|
||||
const res = await listPersonas({
|
||||
active_only: statusFilter === "active",
|
||||
limit: pageSize,
|
||||
offset,
|
||||
})
|
||||
setPersonas(res.data.personas)
|
||||
setTotalCount(res.data.total_count)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setError(true)
|
||||
setPersonas([])
|
||||
setTotalCount(0)
|
||||
if (isPersonaForbiddenError(e)) {
|
||||
setPermissionDenied(true)
|
||||
toast.error(getPersonaApiErrorMessage(e, "You do not have permission to view personas"))
|
||||
} else {
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to load personas"))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [canList, statusFilter, pageSize, offset])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1)
|
||||
}, [statusFilter, pageSize])
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let rows = personas
|
||||
if (statusFilter === "inactive") {
|
||||
rows = rows.filter((persona) => !persona.is_active)
|
||||
}
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return rows
|
||||
return rows.filter((persona) => {
|
||||
const haystack = [
|
||||
persona.name,
|
||||
persona.description ?? "",
|
||||
persona.gender ?? "",
|
||||
String(persona.id),
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return haystack.includes(q)
|
||||
})
|
||||
}, [personas, query, statusFilter])
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStatusFilter("all")
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||
const safePage = Math.min(page, totalPages)
|
||||
const startEntry = totalCount === 0 ? 0 : offset + 1
|
||||
const endEntry = Math.min(offset + personas.length, totalCount)
|
||||
|
||||
const handleToggleActive = async (persona: LmsPersona) => {
|
||||
if (!canUpdate) {
|
||||
toast.error("You do not have permission to update personas")
|
||||
return
|
||||
}
|
||||
|
||||
setTogglingId(persona.id)
|
||||
try {
|
||||
const res = await updatePersona(persona.id, { is_active: !persona.is_active })
|
||||
if (res.data) {
|
||||
setPersonas((prev) => prev.map((row) => (row.id === persona.id ? res.data! : row)))
|
||||
}
|
||||
toast.success(res.data?.is_active ? "Persona activated" : "Persona deactivated")
|
||||
if (statusFilter === "active" && res.data && !res.data.is_active) {
|
||||
void load()
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona status"))
|
||||
} finally {
|
||||
setTogglingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (!permissionsLoading && !canList) {
|
||||
return <PersonaAccessDenied />
|
||||
}
|
||||
|
||||
if (!permissionsLoading && permissionDenied) {
|
||||
return <PersonaAccessDenied apiForbidden />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Learning content</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">Personas</h1>
|
||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||
Manage coach and character profiles linked to practice shells in Learn English and
|
||||
exam-prep content.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" className="shrink-0" disabled={loading} onClick={() => void load()}>
|
||||
{loading ? <SpinnerIcon className="mr-2 h-4 w-4" /> : <RefreshCw className="mr-2 h-4 w-4" />}
|
||||
Refresh
|
||||
</Button>
|
||||
{canCreate ? (
|
||||
<Button
|
||||
className="shrink-0 bg-brand-500 text-white hover:bg-brand-600"
|
||||
onClick={() => setCreateOpen(true)}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New persona
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-soft">
|
||||
<CardContent className="space-y-5 pt-5">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
totalCount > 0
|
||||
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
||||
: "No personas"
|
||||
}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by name, description, gender, or ID…"
|
||||
className="pl-9"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<Select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as PersonaStatusFilter)}
|
||||
className="h-9 w-[11rem] rounded-md text-sm"
|
||||
aria-label="Filter by status"
|
||||
>
|
||||
<option value="all">All statuses</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="inactive">Inactive</option>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[72px]">Avatar</TableHead>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Gender</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Updated</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-12 text-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||
<span className="text-sm text-grayScale-400">Loading personas…</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : error ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-12 text-center text-sm text-grayScale-500">
|
||||
Failed to load personas. Try refreshing.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : filtered.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-12 text-center">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<UserCircle2 className="h-8 w-8 text-grayScale-200" />
|
||||
<p className="text-sm font-medium text-grayScale-500">
|
||||
{totalCount === 0 ? "No personas yet" : "No personas match your search"}
|
||||
</p>
|
||||
<p className="text-xs text-grayScale-400">
|
||||
{canCreate
|
||||
? "Create a persona to use in practice authoring."
|
||||
: "Ask an admin to create personas for your team."}
|
||||
</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filtered.map((persona) => (
|
||||
<TableRow key={persona.id}>
|
||||
<TableCell className="py-3.5">
|
||||
<img
|
||||
src={personaAvatarUrl(
|
||||
persona.profile_picture,
|
||||
persona.name,
|
||||
persona.id,
|
||||
)}
|
||||
alt=""
|
||||
className="h-10 w-10 rounded-full border border-grayScale-200 bg-grayScale-50 object-cover"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="py-3.5">
|
||||
<p className="text-sm font-semibold text-grayScale-700">{persona.name}</p>
|
||||
{persona.description ? (
|
||||
<p className="mt-0.5 line-clamp-2 text-xs text-grayScale-500">
|
||||
{persona.description}
|
||||
</p>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell className="hidden py-3.5 text-sm text-grayScale-500 md:table-cell">
|
||||
{personaGenderLabel(persona.gender)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3.5">
|
||||
{canUpdate ? (
|
||||
<ToggleSwitch
|
||||
checked={persona.is_active}
|
||||
disabled={togglingId === persona.id}
|
||||
aria-label={
|
||||
persona.is_active ? "Deactivate persona" : "Activate persona"
|
||||
}
|
||||
onCheckedChange={() => void handleToggleActive(persona)}
|
||||
/>
|
||||
) : (
|
||||
<Badge variant={persona.is_active ? "default" : "outline"}>
|
||||
{personaStatusLabel(persona.is_active)}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden py-3.5 text-sm text-grayScale-500 lg:table-cell">
|
||||
{formatPersonaDate(persona.updated_at ?? persona.created_at)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3.5">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{canUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2"
|
||||
onClick={() => setPersonaPendingEdit(persona)}
|
||||
>
|
||||
<Pencil className="mr-1 h-3.5 w-3.5" />
|
||||
Edit
|
||||
</Button>
|
||||
) : null}
|
||||
{canDelete ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-destructive hover:text-destructive"
|
||||
onClick={() => setPersonaPendingDelete(persona)}
|
||||
>
|
||||
<Trash2 className="mr-1 h-3.5 w-3.5" />
|
||||
Delete
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{totalCount > 0 ? (
|
||||
<div className="flex flex-col gap-3 border-t border-grayScale-100 pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||
<span>Rows per page</span>
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||
className="h-8 rounded-md border border-grayScale-200 bg-white px-2 text-sm"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={safePage <= 1 || loading}
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
Prev
|
||||
</Button>
|
||||
<span className="text-sm text-grayScale-500">
|
||||
Page {safePage} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={safePage >= totalPages || loading}
|
||||
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<CreatePersonaDialog
|
||||
open={createOpen}
|
||||
onOpenChange={setCreateOpen}
|
||||
onCreated={() => void load()}
|
||||
/>
|
||||
|
||||
<EditPersonaDialog
|
||||
persona={personaPendingEdit}
|
||||
open={personaPendingEdit != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPersonaPendingEdit(null)
|
||||
}}
|
||||
onUpdated={() => void load()}
|
||||
/>
|
||||
|
||||
<PersonaDeleteDialog
|
||||
persona={personaPendingDelete}
|
||||
open={personaPendingDelete != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPersonaPendingDelete(null)
|
||||
}}
|
||||
onDeleted={() => void load()}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
99
src/pages/personas/components/CreatePersonaDialog.tsx
Normal file
99
src/pages/personas/components/CreatePersonaDialog.tsx
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import { useEffect, useState } from "react"
|
||||
import { Plus } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { createPersona } from "../../../api/personas.api"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||
import {
|
||||
draftToCreatePayload,
|
||||
EMPTY_PERSONA_FORM_DRAFT,
|
||||
PersonaForm,
|
||||
PersonaFormActions,
|
||||
validatePersonaDraft,
|
||||
type PersonaFormDraft,
|
||||
} from "./PersonaForm"
|
||||
|
||||
type CreatePersonaDialogProps = {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onCreated?: () => void
|
||||
}
|
||||
|
||||
export function CreatePersonaDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: CreatePersonaDialogProps) {
|
||||
const [draft, setDraft] = useState<PersonaFormDraft>(EMPTY_PERSONA_FORM_DRAFT)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||
const busy = saving || uploadingPicture
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDraft(EMPTY_PERSONA_FORM_DRAFT)
|
||||
setUploadingPicture(false)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !busy) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
const validationError = validatePersonaDraft(draft)
|
||||
if (validationError) {
|
||||
toast.error(validationError)
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const response = await createPersona(draftToCreatePayload(draft))
|
||||
if (!response.data) throw new Error("Empty create response")
|
||||
toast.success(response.message ?? "Persona created successfully")
|
||||
onOpenChange(false)
|
||||
onCreated?.()
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to create persona"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto rounded-2xl border-grayScale-200 sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Plus className="h-5 w-5 text-brand-600" />
|
||||
New persona
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a coach/character profile for linking to practice shells.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<PersonaForm
|
||||
draft={draft}
|
||||
onChange={setDraft}
|
||||
disabled={busy}
|
||||
onUploadBusyChange={setUploadingPicture}
|
||||
/>
|
||||
<PersonaFormActions
|
||||
saving={busy}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
onSave={() => void handleCreate()}
|
||||
saveLabel="Create persona"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
142
src/pages/personas/components/EditPersonaDialog.tsx
Normal file
142
src/pages/personas/components/EditPersonaDialog.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Pencil } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getPersonaById, updatePersona } from "../../../api/personas.api"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||
import type { LmsPersona } from "../../../types/persona.types"
|
||||
import {
|
||||
draftToUpdatePayload,
|
||||
PersonaForm,
|
||||
PersonaFormActions,
|
||||
personaToDraft,
|
||||
validatePersonaDraft,
|
||||
type PersonaFormDraft,
|
||||
} from "./PersonaForm"
|
||||
|
||||
type EditPersonaDialogProps = {
|
||||
persona: LmsPersona | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onUpdated?: () => void
|
||||
}
|
||||
|
||||
export function EditPersonaDialog({
|
||||
persona,
|
||||
open,
|
||||
onOpenChange,
|
||||
onUpdated,
|
||||
}: EditPersonaDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [uploadingPicture, setUploadingPicture] = useState(false)
|
||||
const [draft, setDraft] = useState<PersonaFormDraft | null>(null)
|
||||
const busy = saving || uploadingPicture
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!persona) return
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await getPersonaById(persona.id)
|
||||
if (!res.data) throw new Error("Persona not found")
|
||||
setDraft(personaToDraft(res.data))
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
if (status === 404) {
|
||||
toast.error("Persona not found")
|
||||
} else {
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to load persona"))
|
||||
}
|
||||
onOpenChange(false)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [persona, onOpenChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (open && persona) {
|
||||
void load()
|
||||
} else if (!open) {
|
||||
setDraft(null)
|
||||
setLoading(false)
|
||||
setSaving(false)
|
||||
setUploadingPicture(false)
|
||||
}
|
||||
}, [open, persona, load])
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !busy && !loading) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!persona || !draft) return
|
||||
|
||||
const validationError = validatePersonaDraft(draft)
|
||||
if (validationError) {
|
||||
toast.error(validationError)
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await updatePersona(persona.id, draftToUpdatePayload(draft))
|
||||
if (!res.data) throw new Error("Empty update response")
|
||||
toast.success(res.message ?? "Persona updated successfully")
|
||||
onOpenChange(false)
|
||||
onUpdated?.()
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to update persona"))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto rounded-2xl border-grayScale-200 sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Pencil className="h-5 w-5 text-brand-600" />
|
||||
Edit persona
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{persona ? `Update coach profile #${persona.id}` : "Update persona details"}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{loading || !draft ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-12">
|
||||
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||
<p className="text-sm text-grayScale-500">Loading persona…</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<PersonaForm
|
||||
draft={draft}
|
||||
onChange={setDraft}
|
||||
disabled={busy}
|
||||
previewId={persona?.id}
|
||||
onUploadBusyChange={setUploadingPicture}
|
||||
/>
|
||||
<PersonaFormActions
|
||||
saving={busy}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
onSave={() => void handleSave()}
|
||||
saveLabel="Save changes"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
100
src/pages/personas/components/PersonaAccessDenied.tsx
Normal file
100
src/pages/personas/components/PersonaAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { LogOut, RefreshCw, UserCircle2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Card, CardContent } from "../../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { PERSONAS_FORBIDDEN_MESSAGE } from "../../../lib/personasErrors"
|
||||
import {
|
||||
getSessionTeamRole,
|
||||
hasPersonasRoleBypass,
|
||||
} from "../../../lib/personasPermissions"
|
||||
|
||||
type PersonaAccessDeniedProps = {
|
||||
apiForbidden?: boolean
|
||||
}
|
||||
|
||||
export function PersonaAccessDenied({ apiForbidden = false }: PersonaAccessDeniedProps) {
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const teamRole = getSessionTeamRole()
|
||||
const canSync = hasPersonasRoleBypass()
|
||||
|
||||
const handleSync = async () => {
|
||||
setSyncing(true)
|
||||
try {
|
||||
const res = await syncRbacPermissions()
|
||||
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg =
|
||||
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||
"Failed to sync RBAC permissions"
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||
<UserCircle2 className="h-10 w-10 text-grayScale-300" />
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||
{apiForbidden ? "Persona access denied" : "No permission to view personas"}
|
||||
</h2>
|
||||
<p className="text-sm text-grayScale-600">
|
||||
{apiForbidden
|
||||
? PERSONAS_FORBIDDEN_MESSAGE
|
||||
: "Your account does not have the personas.list permission."}
|
||||
</p>
|
||||
{teamRole ? (
|
||||
<p className="text-xs text-grayScale-500">
|
||||
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||
<li>Use ADMIN, SUPER_ADMIN, or INSTRUCTOR with personas.* permissions</li>
|
||||
<li>Ensure migrations 000063–000065 are applied on the API database</li>
|
||||
<li>Run RBAC sync, then sign out and sign in again</li>
|
||||
<li>SUPPORT has read-only access (list/get)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{canSync ? (
|
||||
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||
{syncing ? (
|
||||
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sync RBAC permissions
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="outline" asChild>
|
||||
<Link to="/roles">Manage roles</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
localStorage.clear()
|
||||
window.location.href = "/login"
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign in again
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
87
src/pages/personas/components/PersonaDeleteDialog.tsx
Normal file
87
src/pages/personas/components/PersonaDeleteDialog.tsx
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import { useState } from "react"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { deletePersona } from "../../../api/personas.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { getPersonaApiErrorMessage } from "../../../lib/personasErrors"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../../../components/ui/dialog"
|
||||
import type { LmsPersona } from "../../../types/persona.types"
|
||||
|
||||
type PersonaDeleteDialogProps = {
|
||||
persona: LmsPersona | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onDeleted?: () => void
|
||||
}
|
||||
|
||||
export function PersonaDeleteDialog({
|
||||
persona,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDeleted,
|
||||
}: PersonaDeleteDialogProps) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next && !deleting) onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!persona) return
|
||||
|
||||
setDeleting(true)
|
||||
try {
|
||||
const response = await deletePersona(persona.id)
|
||||
toast.success(response.message ?? "Persona deleted successfully")
|
||||
onOpenChange(false)
|
||||
onDeleted?.()
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
toast.error(getPersonaApiErrorMessage(e, "Failed to delete persona"))
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md rounded-2xl border-grayScale-200 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<Trash2 className="h-5 w-5 shrink-0 text-destructive" aria-hidden />
|
||||
Delete persona?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-left text-grayScale-600">
|
||||
This permanently removes the persona from the catalog. Practices that referenced it
|
||||
will have their persona assignment cleared automatically.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{persona ? (
|
||||
<div className="space-y-1 rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3">
|
||||
<p className="text-sm font-semibold text-grayScale-900">{persona.name}</p>
|
||||
<p className="text-xs text-grayScale-500">#{persona.id}</p>
|
||||
</div>
|
||||
) : null}
|
||||
<DialogFooter className="gap-2 sm:gap-2">
|
||||
<Button variant="outline" disabled={deleting} onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleting || !persona}
|
||||
onClick={() => void handleConfirm()}
|
||||
>
|
||||
{deleting ? "Deleting…" : "Delete persona"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
209
src/pages/personas/components/PersonaForm.tsx
Normal file
209
src/pages/personas/components/PersonaForm.tsx
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
import type {
|
||||
CreatePersonaInput,
|
||||
LmsPersona,
|
||||
UpdatePersonaInput,
|
||||
} from "../../../types/persona.types"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { Select } from "../../../components/ui/select"
|
||||
import { Textarea } from "../../../components/ui/textarea"
|
||||
import { personaAvatarUrl } from "../../../lib/personaDisplay"
|
||||
import { PersonaProfilePictureUploadField } from "./PersonaProfilePictureUploadField"
|
||||
|
||||
const PERSONA_GENDER_OPTIONS = [
|
||||
{ value: "female", label: "Female" },
|
||||
{ value: "male", label: "Male" },
|
||||
{ value: "neutral", label: "Neutral" },
|
||||
] as const
|
||||
|
||||
export type PersonaFormDraft = {
|
||||
name: string
|
||||
description: string
|
||||
profile_picture: string
|
||||
gender: string
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
export const EMPTY_PERSONA_FORM_DRAFT: PersonaFormDraft = {
|
||||
name: "",
|
||||
description: "",
|
||||
profile_picture: "",
|
||||
gender: "",
|
||||
is_active: true,
|
||||
}
|
||||
|
||||
export function validatePersonaDraft(draft: PersonaFormDraft): string | null {
|
||||
if (!draft.name.trim()) return "Name is required"
|
||||
return null
|
||||
}
|
||||
|
||||
export function draftToCreatePayload(draft: PersonaFormDraft): CreatePersonaInput {
|
||||
return {
|
||||
name: draft.name.trim(),
|
||||
description: draft.description.trim() || null,
|
||||
profile_picture: draft.profile_picture.trim() || null,
|
||||
gender: draft.gender.trim() || null,
|
||||
is_active: draft.is_active,
|
||||
}
|
||||
}
|
||||
|
||||
export function draftToUpdatePayload(draft: PersonaFormDraft): UpdatePersonaInput {
|
||||
return {
|
||||
name: draft.name.trim(),
|
||||
description: draft.description.trim(),
|
||||
profile_picture: draft.profile_picture.trim(),
|
||||
gender: draft.gender.trim(),
|
||||
is_active: draft.is_active,
|
||||
}
|
||||
}
|
||||
|
||||
export function personaToDraft(persona: LmsPersona): PersonaFormDraft {
|
||||
return {
|
||||
name: persona.name,
|
||||
description: persona.description ?? "",
|
||||
profile_picture: persona.profile_picture ?? "",
|
||||
gender: persona.gender ?? "",
|
||||
is_active: persona.is_active,
|
||||
}
|
||||
}
|
||||
|
||||
type PersonaFormProps = {
|
||||
draft: PersonaFormDraft
|
||||
onChange: (draft: PersonaFormDraft) => void
|
||||
disabled?: boolean
|
||||
previewId?: number
|
||||
onUploadBusyChange?: (busy: boolean) => void
|
||||
}
|
||||
|
||||
export function PersonaForm({
|
||||
draft,
|
||||
onChange,
|
||||
disabled = false,
|
||||
previewId,
|
||||
onUploadBusyChange,
|
||||
}: PersonaFormProps) {
|
||||
const previewUrl = personaAvatarUrl(
|
||||
draft.profile_picture.trim() || null,
|
||||
draft.name.trim() || "Persona",
|
||||
previewId,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt=""
|
||||
className="h-16 w-16 rounded-full border border-grayScale-200 bg-grayScale-50 object-cover"
|
||||
/>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
Upload an image from your computer, paste a URL, or leave empty for a generated
|
||||
placeholder.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="persona-name"
|
||||
value={draft.name}
|
||||
disabled={disabled}
|
||||
placeholder="Friendly Coach"
|
||||
onChange={(e) => onChange({ ...draft, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-description">
|
||||
Description
|
||||
</label>
|
||||
<Textarea
|
||||
id="persona-description"
|
||||
value={draft.description}
|
||||
disabled={disabled}
|
||||
placeholder="Warm, encouraging tutor for everyday conversational practice."
|
||||
rows={4}
|
||||
onChange={(e) => onChange({ ...draft, description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-profile-picture">
|
||||
Profile picture
|
||||
</label>
|
||||
<PersonaProfilePictureUploadField
|
||||
value={draft.profile_picture}
|
||||
onChange={(profile_picture) => onChange({ ...draft, profile_picture })}
|
||||
disabled={disabled}
|
||||
onUploadBusyChange={onUploadBusyChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700" htmlFor="persona-gender">
|
||||
Gender
|
||||
</label>
|
||||
<Select
|
||||
id="persona-gender"
|
||||
value={draft.gender}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange({ ...draft, gender: e.target.value })}
|
||||
>
|
||||
<option value="">Select gender</option>
|
||||
{PERSONA_GENDER_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
{draft.gender &&
|
||||
!PERSONA_GENDER_OPTIONS.some((option) => option.value === draft.gender) ? (
|
||||
<option value={draft.gender}>{draft.gender}</option>
|
||||
) : null}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 text-sm text-grayScale-700">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.is_active}
|
||||
disabled={disabled}
|
||||
className="h-4 w-4 rounded border-grayScale-300"
|
||||
onChange={(e) => onChange({ ...draft, is_active: e.target.checked })}
|
||||
/>
|
||||
Active (visible in practice persona picker)
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PersonaFormActionsProps = {
|
||||
saving: boolean
|
||||
onCancel: () => void
|
||||
onSave: () => void
|
||||
saveLabel?: string
|
||||
}
|
||||
|
||||
export function PersonaFormActions({
|
||||
saving,
|
||||
onCancel,
|
||||
onSave,
|
||||
saveLabel = "Save persona",
|
||||
}: PersonaFormActionsProps) {
|
||||
return (
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button type="button" variant="outline" disabled={saving} onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||
disabled={saving}
|
||||
onClick={onSave}
|
||||
>
|
||||
{saving ? "Saving…" : saveLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
import { useCallback, useRef, useState, type ChangeEvent, type DragEvent } from "react"
|
||||
import { CloudUpload } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { uploadImageFile } from "../../../api/files.api"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
import { cn } from "../../../lib/utils"
|
||||
|
||||
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp"])
|
||||
|
||||
function isAllowedImageFile(file: File): boolean {
|
||||
if (ALLOWED_IMAGE_TYPES.has(file.type)) return true
|
||||
const name = file.name.toLowerCase()
|
||||
return /\.(jpe?g|png|webp)$/.test(name)
|
||||
}
|
||||
|
||||
type PersonaProfilePictureUploadFieldProps = {
|
||||
value: string
|
||||
onChange: (url: string) => void
|
||||
disabled?: boolean
|
||||
onUploadBusyChange?: (busy: boolean) => void
|
||||
}
|
||||
|
||||
export function PersonaProfilePictureUploadField({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
onUploadBusyChange,
|
||||
}: PersonaProfilePictureUploadFieldProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [dragActive, setDragActive] = useState(false)
|
||||
|
||||
const setBusy = useCallback(
|
||||
(next: boolean) => {
|
||||
setUploading(next)
|
||||
onUploadBusyChange?.(next)
|
||||
},
|
||||
[onUploadBusyChange],
|
||||
)
|
||||
|
||||
const processFile = useCallback(
|
||||
async (file: File) => {
|
||||
if (disabled || uploading) return
|
||||
if (!isAllowedImageFile(file)) {
|
||||
toast.error("Please use a JPG, PNG, or WEBP image.")
|
||||
return
|
||||
}
|
||||
if (file.size > MAX_IMAGE_BYTES) {
|
||||
toast.error("Image is too large", {
|
||||
description: "Maximum size is 5 MB.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await uploadImageFile(file)
|
||||
const url = res.data?.data?.url?.trim()
|
||||
if (!url) throw new Error("Upload did not return a file URL")
|
||||
onChange(url)
|
||||
toast.success("Profile picture uploaded")
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg =
|
||||
(e as { response?: { data?: { message?: string } } })?.response?.data
|
||||
?.message ?? "Failed to upload profile picture"
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
},
|
||||
[disabled, uploading, onChange, setBusy],
|
||||
)
|
||||
|
||||
const handleFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ""
|
||||
if (file) void processFile(file)
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (!disabled && !uploading) setDragActive(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDragActive(false)
|
||||
}
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDragActive(false)
|
||||
if (disabled || uploading) return
|
||||
const file = e.dataTransfer.files?.[0]
|
||||
if (file) void processFile(file)
|
||||
}
|
||||
|
||||
const zoneDisabled = disabled || uploading
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
|
||||
className="sr-only"
|
||||
onChange={handleFileInputChange}
|
||||
disabled={zoneDisabled}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={zoneDisabled}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
className={cn(
|
||||
"flex w-full cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed border-brand-200 bg-white p-6 text-center transition-colors",
|
||||
"hover:border-brand-300 hover:bg-grayScale-50/40",
|
||||
dragActive && "border-brand-400 bg-brand-50/40",
|
||||
zoneDisabled && "cursor-not-allowed opacity-60",
|
||||
)}
|
||||
>
|
||||
{uploading ? (
|
||||
<p className="text-sm font-medium text-grayScale-600">Uploading…</p>
|
||||
) : (
|
||||
<>
|
||||
<CloudUpload
|
||||
className="mb-2 h-8 w-8 text-brand-600"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden
|
||||
/>
|
||||
<p className="text-sm">
|
||||
<span className="font-semibold text-brand-600">Click to upload</span>{" "}
|
||||
<span className="text-grayScale-500">or drag and drop</span>
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-grayScale-400">JPG, PNG, WEBP (max 5 MB)</p>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<Input
|
||||
id="persona-profile-picture"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="Or paste image URL (https://…)"
|
||||
disabled={zoneDisabled}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
395
src/pages/ratings/AppReviewsPage.tsx
Normal file
395
src/pages/ratings/AppReviewsPage.tsx
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Star,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { loadRatingsPage } from "../../api/ratings.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../components/ui/table"
|
||||
import { useRatingsPermissions } from "../../hooks/useRatingsPermissions"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import {
|
||||
fetchReviewerProfiles,
|
||||
type ReviewerProfile,
|
||||
} from "../../lib/ratingUserCache"
|
||||
import {
|
||||
formatAverageStars,
|
||||
formatRatingDate,
|
||||
reviewTextOrPlaceholder,
|
||||
} from "../../lib/ratingsDisplay"
|
||||
import {
|
||||
getRatingsApiErrorMessage,
|
||||
isRatingsForbiddenError,
|
||||
} from "../../lib/ratingsErrors"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { cn } from "../../lib/utils"
|
||||
import type { Rating, RatingSummary } from "../../types/ratings.types"
|
||||
import { RatingsAccessDenied } from "./components/RatingsAccessDenied"
|
||||
import { StarRating } from "./components/StarRating"
|
||||
|
||||
type StarsFilter = "all" | "1" | "2" | "3" | "4" | "5"
|
||||
|
||||
const APP_TARGET_TYPE = "app" as const
|
||||
const APP_TARGET_ID = 0
|
||||
|
||||
export function AppReviewsPage() {
|
||||
const { canList, loading: permissionsLoading } = useRatingsPermissions()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const [permissionDenied, setPermissionDenied] = useState(false)
|
||||
const [reviews, setReviews] = useState<Rating[]>([])
|
||||
const [summary, setSummary] = useState<RatingSummary>({ total_count: 0, average_stars: 0 })
|
||||
const [reviewerProfiles, setReviewerProfiles] = useState<Map<number, ReviewerProfile>>(new Map())
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [query, setQuery] = useState("")
|
||||
const [starsFilter, setStarsFilter] = useState<StarsFilter>("all")
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!canList) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setError(false)
|
||||
setPermissionDenied(false)
|
||||
|
||||
try {
|
||||
const data = await loadRatingsPage(APP_TARGET_TYPE, page, pageSize, APP_TARGET_ID)
|
||||
setSummary(data.summary)
|
||||
setReviews(data.reviews)
|
||||
|
||||
const profiles = await fetchReviewerProfiles(data.reviews.map((r) => r.user_id))
|
||||
setReviewerProfiles(profiles)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setError(true)
|
||||
setReviews([])
|
||||
setSummary({ total_count: 0, average_stars: 0 })
|
||||
setReviewerProfiles(new Map())
|
||||
if (isRatingsForbiddenError(e)) {
|
||||
setPermissionDenied(true)
|
||||
toast.error(getRatingsApiErrorMessage(e, "You do not have permission to view app reviews"))
|
||||
} else {
|
||||
toast.error(getRatingsApiErrorMessage(e, "Failed to load app reviews"))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [canList, page, pageSize])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1)
|
||||
}, [pageSize, starsFilter])
|
||||
|
||||
const filteredReviews = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
return reviews.filter((rating) => {
|
||||
if (starsFilter !== "all" && rating.stars !== Number(starsFilter)) return false
|
||||
if (!q) return true
|
||||
|
||||
const profile = reviewerProfiles.get(rating.user_id)
|
||||
const haystack = [
|
||||
rating.review ?? "",
|
||||
String(rating.user_id),
|
||||
profile?.name ?? "",
|
||||
profile?.email ?? "",
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return haystack.includes(q)
|
||||
})
|
||||
}, [reviews, query, starsFilter, reviewerProfiles])
|
||||
|
||||
const activeFilterCount = countActiveFilters([{ value: starsFilter, defaultValue: "all" }])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStarsFilter("all")
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const totalCount = summary.total_count
|
||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||
const safePage = Math.min(page, totalPages)
|
||||
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
|
||||
const endEntry = Math.min(safePage * pageSize, totalCount)
|
||||
|
||||
const writtenOnPage = reviews.filter((r) => r.review?.trim()).length
|
||||
|
||||
if (!permissionsLoading && !canList) {
|
||||
return <RatingsAccessDenied />
|
||||
}
|
||||
|
||||
if (permissionDenied) {
|
||||
return <RatingsAccessDenied apiForbidden />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-grayScale-600">App Reviews</h1>
|
||||
<p className="mt-1 text-sm text-grayScale-400">
|
||||
Monitor learner star ratings and written feedback submitted from the app.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
disabled={loading || !canList}
|
||||
onClick={() => void load()}
|
||||
>
|
||||
{loading ? <SpinnerIcon className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||
<div className="grid h-10 w-10 place-items-center rounded-lg bg-amber-100 text-amber-600">
|
||||
<Star className="h-5 w-5 fill-amber-500" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-2xl font-bold text-grayScale-600">
|
||||
{formatAverageStars(summary.average_stars)}
|
||||
</p>
|
||||
<StarRating stars={summary.average_stars} size="sm" />
|
||||
</div>
|
||||
<p className="text-xs text-grayScale-400">Average rating</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||
<div className="grid h-10 w-10 place-items-center rounded-lg bg-brand-100 text-brand-600">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold text-grayScale-600">{totalCount}</p>
|
||||
<p className="text-xs text-grayScale-400">Total reviews</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
|
||||
<div className="grid h-10 w-10 place-items-center rounded-lg bg-emerald-100 text-emerald-600">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold text-grayScale-600">{writtenOnPage}</p>
|
||||
<p className="text-xs text-grayScale-400">With written review (this page)</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-soft">
|
||||
<CardContent className="space-y-5 pt-5">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
footer="Star and text filters apply to the current page only. Server-side search is not available yet."
|
||||
summary={
|
||||
totalCount > 0
|
||||
? `Showing ${startEntry}–${endEntry} of ${totalCount}`
|
||||
: "No reviews"
|
||||
}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search review text, user name, email, or ID…"
|
||||
className="pl-9"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
<Select
|
||||
value={starsFilter}
|
||||
onChange={(e) => setStarsFilter(e.target.value as StarsFilter)}
|
||||
className="h-9 w-full min-w-[140px] sm:w-40"
|
||||
aria-label="Filter by stars"
|
||||
>
|
||||
<option value="all">All stars</option>
|
||||
<option value="5">5 stars</option>
|
||||
<option value="4">4 stars</option>
|
||||
<option value="3">3 stars</option>
|
||||
<option value="2">2 stars</option>
|
||||
<option value="1">1 star</option>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[120px]">Stars</TableHead>
|
||||
<TableHead>Review</TableHead>
|
||||
<TableHead className="w-[200px]">User</TableHead>
|
||||
<TableHead className="w-[140px]">Submitted</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-12 text-center">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<SpinnerIcon className="h-6 w-6 text-brand-500" />
|
||||
<span className="text-sm text-grayScale-400">Loading reviews…</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : error ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-12 text-center text-sm text-grayScale-500">
|
||||
Failed to load reviews. Try refreshing.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : filteredReviews.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="py-12 text-center">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Star className="h-8 w-8 text-grayScale-200" />
|
||||
<p className="text-sm font-medium text-grayScale-500">
|
||||
{totalCount === 0
|
||||
? "No reviews yet"
|
||||
: "No reviews match your filters on this page"}
|
||||
</p>
|
||||
<p className="text-xs text-grayScale-400">
|
||||
{totalCount === 0
|
||||
? "Learners can submit ratings from the mobile or web app."
|
||||
: "Try different filters or go to another page."}
|
||||
</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filteredReviews.map((rating) => {
|
||||
const profile = reviewerProfiles.get(rating.user_id)
|
||||
return (
|
||||
<TableRow key={rating.id}>
|
||||
<TableCell className="py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<StarRating stars={rating.stars} />
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{rating.stars}/5
|
||||
</Badge>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-md py-3.5">
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm",
|
||||
rating.review?.trim()
|
||||
? "text-grayScale-600"
|
||||
: "italic text-grayScale-400",
|
||||
)}
|
||||
>
|
||||
{reviewTextOrPlaceholder(rating.review)}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className="py-3.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-50 text-xs font-semibold text-brand-600">
|
||||
{(profile?.name ?? `U${rating.user_id}`).charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<Link
|
||||
to={`/users/${rating.user_id}`}
|
||||
className="inline-flex items-center gap-1 text-sm font-medium text-brand-600 hover:underline"
|
||||
>
|
||||
{profile?.name ?? `User #${rating.user_id}`}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</Link>
|
||||
{profile?.email ? (
|
||||
<p className="truncate text-xs text-grayScale-400">{profile.email}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="py-3.5 text-sm text-grayScale-500">
|
||||
{formatRatingDate(rating.created_at)}
|
||||
{rating.updated_at !== rating.created_at ? (
|
||||
<p className="text-xs text-grayScale-400">Updated</p>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{canList && totalCount > 0 ? (
|
||||
<div className="flex flex-col gap-3 border-t border-grayScale-100 pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2 text-sm text-grayScale-500">
|
||||
<span>Rows per page</span>
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => setPageSize(Number(e.target.value))}
|
||||
className="h-8 rounded-md border border-grayScale-200 bg-white px-2 text-sm"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={safePage <= 1 || loading}
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
Prev
|
||||
</Button>
|
||||
<span className="text-sm text-grayScale-500">
|
||||
Page {safePage} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={safePage >= totalPages || loading}
|
||||
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
97
src/pages/ratings/components/RatingsAccessDenied.tsx
Normal file
97
src/pages/ratings/components/RatingsAccessDenied.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { useState } from "react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { LogOut, RefreshCw, Star } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { syncRbacPermissions } from "../../../api/rbac.api"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Card, CardContent } from "../../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { getSessionTeamRole, hasRatingsRoleBypass } from "../../../lib/ratingsPermissions"
|
||||
import { RATINGS_FORBIDDEN_MESSAGE } from "../../../lib/ratingsErrors"
|
||||
|
||||
type RatingsAccessDeniedProps = {
|
||||
apiForbidden?: boolean
|
||||
}
|
||||
|
||||
export function RatingsAccessDenied({ apiForbidden = false }: RatingsAccessDeniedProps) {
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const teamRole = getSessionTeamRole()
|
||||
const canSync = hasRatingsRoleBypass()
|
||||
|
||||
const handleSync = async () => {
|
||||
setSyncing(true)
|
||||
try {
|
||||
const res = await syncRbacPermissions()
|
||||
toast.success(res.data?.message ?? "RBAC permissions synced. Please sign in again.")
|
||||
} catch (e: unknown) {
|
||||
console.error(e)
|
||||
const msg =
|
||||
(e as { response?: { data?: { message?: string } } })?.response?.data?.message ??
|
||||
"Failed to sync RBAC permissions"
|
||||
toast.error(msg)
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-2xl space-y-6">
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="flex flex-col items-center gap-4 px-6 py-16 text-center">
|
||||
<Star className="h-10 w-10 text-grayScale-300" />
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold text-grayScale-800">
|
||||
{apiForbidden ? "App reviews access denied" : "No permission to view app reviews"}
|
||||
</h2>
|
||||
<p className="text-sm text-grayScale-600">
|
||||
{apiForbidden
|
||||
? RATINGS_FORBIDDEN_MESSAGE
|
||||
: "Your account does not have the ratings.list_by_target permission."}
|
||||
</p>
|
||||
{teamRole ? (
|
||||
<p className="text-xs text-grayScale-500">
|
||||
Signed in as team role: <span className="font-medium">{teamRole}</span>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-md rounded-xl border border-grayScale-200 bg-grayScale-50 px-4 py-3 text-left text-xs text-grayScale-600">
|
||||
<p className="font-semibold text-grayScale-700">If you expect access:</p>
|
||||
<ul className="mt-2 list-disc space-y-1 pl-4">
|
||||
<li>Use a team account with ADMIN or SUPER_ADMIN, or explicit ratings permissions</li>
|
||||
<li>Ensure migration 000017_ratings is applied on the API database</li>
|
||||
<li>Run RBAC sync, then sign out and sign in again for a fresh token</li>
|
||||
<li>Custom roles need ratings.list_by_target and ratings.summary assigned</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{canSync ? (
|
||||
<Button variant="outline" disabled={syncing} onClick={() => void handleSync()}>
|
||||
{syncing ? (
|
||||
<SpinnerIcon className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Sync RBAC permissions
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="outline" asChild>
|
||||
<Link to="/roles">Manage roles</Link>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
localStorage.clear()
|
||||
window.location.href = "/login"
|
||||
}}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Sign in again
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
30
src/pages/ratings/components/StarRating.tsx
Normal file
30
src/pages/ratings/components/StarRating.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { Star } from "lucide-react"
|
||||
import { cn } from "../../../lib/utils"
|
||||
|
||||
type StarRatingProps = {
|
||||
stars: number
|
||||
max?: number
|
||||
size?: "sm" | "md"
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function StarRating({ stars, max = 5, size = "md", className }: StarRatingProps) {
|
||||
const iconClass = size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4"
|
||||
const safeStars = Math.max(0, Math.min(max, Math.round(stars)))
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-0.5", className)} aria-label={`${safeStars} out of ${max} stars`}>
|
||||
{Array.from({ length: max }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
className={cn(
|
||||
iconClass,
|
||||
i < safeStars
|
||||
? "fill-amber-400 text-amber-400"
|
||||
: "fill-grayScale-200 text-grayScale-200",
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -17,11 +17,13 @@ import {
|
|||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getAppVersions } from "../../api/app-versions.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import {
|
||||
|
|
@ -147,6 +149,16 @@ export function AppVersionsTab() {
|
|||
setTotalCount((c) => Math.max(0, c - 1))
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: platformFilter, defaultValue: "all" },
|
||||
{ value: statusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setPlatformFilter("all")
|
||||
setStatusFilter("all")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
|
|
@ -237,16 +249,21 @@ export function AppVersionsTab() {
|
|||
<CardTitle className="text-sm font-bold text-grayScale-900">Release history</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<div className="relative w-full min-w-0">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="w-full rounded-[6px] pl-9"
|
||||
placeholder="Search version, notes, platform…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
search={
|
||||
<div className="relative w-full min-w-0">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="w-full rounded-[6px] pl-9"
|
||||
placeholder="Search version, notes, platform…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex min-w-0 flex-wrap gap-2">
|
||||
{(
|
||||
[
|
||||
|
|
@ -294,7 +311,7 @@ export function AppVersionsTab() {
|
|||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||
|
|
|
|||
|
|
@ -12,11 +12,13 @@ import {
|
|||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { getSubscriptionPlans } from "../../api/subscription-plans.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import {
|
||||
formatPlanCategory,
|
||||
|
|
@ -91,6 +93,14 @@ export function SubscriptionPlansTab() {
|
|||
setPlans((prev) => prev.filter((p) => p.id !== id))
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter, defaultValue: "all" },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setStatusFilter("all")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="animate-in fade-in slide-in-from-bottom-2 min-w-0 w-full max-w-full space-y-6 duration-300">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
|
|
@ -168,16 +178,21 @@ export function SubscriptionPlansTab() {
|
|||
<CardTitle className="text-sm font-bold text-grayScale-900">All packages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="rounded-[6px] pl-9"
|
||||
placeholder="Search by name, description, or category…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
search={
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
className="rounded-[6px] pl-9"
|
||||
placeholder="Search by name, description, or category…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(
|
||||
[
|
||||
|
|
@ -201,7 +216,7 @@ export function SubscriptionPlansTab() {
|
|||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16">
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { Input } from "../../../components/ui/input"
|
|||
import { Select } from "../../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { Textarea } from "../../../components/ui/textarea"
|
||||
import { ToggleSwitch } from "../../../components/ui/toggle-switch"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import {
|
||||
SUBSCRIPTION_CURRENCIES,
|
||||
|
|
@ -257,23 +258,12 @@ export function CreateSubscriptionPlanDialog({
|
|||
Inactive plans stay in the catalog but are hidden from checkout
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={draft.is_active}
|
||||
onClick={() => setDraft((d) => ({ ...d, is_active: !d.is_active }))}
|
||||
className={cn(
|
||||
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors",
|
||||
draft.is_active ? "bg-brand-500" : "bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-transform",
|
||||
draft.is_active ? "translate-x-5" : "translate-x-0.5",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
<ToggleSwitch
|
||||
variant="plain"
|
||||
checked={draft.is_active}
|
||||
aria-label="Active package"
|
||||
onCheckedChange={() => setDraft((d) => ({ ...d, is_active: !d.is_active }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { Input } from "../../../components/ui/input"
|
|||
import { Select } from "../../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon"
|
||||
import { Textarea } from "../../../components/ui/textarea"
|
||||
import { ToggleSwitch } from "../../../components/ui/toggle-switch"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import {
|
||||
formatPlanCategory,
|
||||
|
|
@ -265,23 +266,12 @@ export function EditSubscriptionPlanDialog({
|
|||
Inactive plans stay in the catalog but are hidden from checkout
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={draft.is_active}
|
||||
onClick={() => setDraft((d) => d && { ...d, is_active: !d.is_active })}
|
||||
className={cn(
|
||||
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors",
|
||||
draft.is_active ? "bg-brand-500" : "bg-grayScale-200",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-transform",
|
||||
draft.is_active ? "translate-x-5" : "translate-x-0.5",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
<ToggleSwitch
|
||||
variant="plain"
|
||||
checked={draft.is_active}
|
||||
aria-label="Active package"
|
||||
onCheckedChange={() => setDraft((d) => d && { ...d, is_active: !d.is_active })}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import {
|
|||
ChevronRight,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import {
|
||||
|
|
@ -19,6 +20,8 @@ import {
|
|||
TableRow,
|
||||
} from "../../components/ui/table";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
||||
import { ToggleSwitch } from "../../components/ui/toggle-switch";
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||
import { getTeamMembers, updateTeamMemberStatus } from "../../api/team.api";
|
||||
|
|
@ -215,6 +218,16 @@ export function TeamManagementPage() {
|
|||
setConfirmDialog(null);
|
||||
};
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: roleFilter },
|
||||
{ value: statusFilter },
|
||||
]);
|
||||
|
||||
const clearFilters = () => {
|
||||
setRoleFilter("");
|
||||
setStatusFilter("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
|
|
@ -233,50 +246,54 @@ export function TeamManagementPage() {
|
|||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-lg border bg-white p-3">
|
||||
<div className="relative w-full sm:flex-1 sm:w-auto">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by name or email address..."
|
||||
className="pl-9"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by name or email address..."
|
||||
className="pl-9"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="relative">
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => setRoleFilter(e.target.value)}
|
||||
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">Role: All</option>
|
||||
<option value="super_admin">Super Admin</option>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="content_manager">Content Manager</option>
|
||||
<option value="instructor">Instructor</option>
|
||||
<option value="support_agent">Support Agent</option>
|
||||
<option value="finance">Finance</option>
|
||||
<option value="hr">HR</option>
|
||||
<option value="analyst">Analyst</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">Status: All</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="inactive">Inactive</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => setRoleFilter(e.target.value)}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Role: All</option>
|
||||
<option value="super_admin">Super Admin</option>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="content_manager">Content Manager</option>
|
||||
<option value="instructor">Instructor</option>
|
||||
<option value="support_agent">Support Agent</option>
|
||||
<option value="finance">Finance</option>
|
||||
<option value="hr">HR</option>
|
||||
<option value="analyst">Analyst</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Status: All</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="inactive">Inactive</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<Table>
|
||||
|
|
@ -371,24 +388,10 @@ export function TeamManagementPage() {
|
|||
)}
|
||||
</TableCell>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToggle(member.id)}
|
||||
className={cn(
|
||||
"relative inline-flex h-7 w-12 shrink-0 cursor-pointer items-center rounded-full border p-0.5 transition-all duration-200",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
||||
isActive
|
||||
? "border-brand-500 bg-brand-500 shadow-[0_6px_16px_rgba(168,85,247,0.35)]"
|
||||
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80"
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-out",
|
||||
isActive ? "translate-x-5" : "translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
<ToggleSwitch
|
||||
checked={isActive}
|
||||
onCheckedChange={() => handleToggle(member.id)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,112 +1,190 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { useEffect, useState } from "react"
|
||||
import { Link, useParams } from "react-router-dom"
|
||||
import {
|
||||
ArrowLeft,
|
||||
KeyRound,
|
||||
MessageCircle,
|
||||
BadgeCheck,
|
||||
Briefcase,
|
||||
Building2,
|
||||
CalendarDays,
|
||||
Clock3,
|
||||
Hash,
|
||||
Mail,
|
||||
Phone,
|
||||
Shield,
|
||||
User,
|
||||
} from "lucide-react";
|
||||
import { Badge } from "../../components/ui/badge";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { getTeamMemberById } from "../../api/team.api";
|
||||
import type { TeamMember } from "../../types/team.types";
|
||||
UserCircle2,
|
||||
} from "lucide-react"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Avatar, AvatarFallback } from "../../components/ui/avatar"
|
||||
import { Separator } from "../../components/ui/separator"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { getTeamMemberById } from "../../api/team.api"
|
||||
import type { TeamMemberDetail } from "../../types/team.types"
|
||||
|
||||
function formatRoleLabel(role: string): string {
|
||||
return role
|
||||
const value = role.trim()
|
||||
if (!value) return "—"
|
||||
return value
|
||||
.split("_")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ");
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
function formatEmploymentType(type: string): string {
|
||||
return type
|
||||
.split("_")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ");
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim()
|
||||
if (!value) return "—"
|
||||
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase()
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null | undefined): string {
|
||||
if (!dateStr?.trim()) return "—"
|
||||
const date = new Date(dateStr)
|
||||
if (Number.isNaN(date.getTime())) return dateStr
|
||||
return date.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr: string | null | undefined): string {
|
||||
if (!dateStr?.trim()) return "—"
|
||||
const date = new Date(dateStr)
|
||||
if (Number.isNaN(date.getTime())) return dateStr
|
||||
return date.toLocaleString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
function displayValue(value: string | null | undefined): string {
|
||||
const trimmed = value?.trim()
|
||||
return trimmed ? trimmed : "—"
|
||||
}
|
||||
|
||||
function getRoleBadgeClasses(role: string): string {
|
||||
switch (role) {
|
||||
const normalized = role.trim().toLowerCase()
|
||||
switch (normalized) {
|
||||
case "super_admin":
|
||||
return "bg-brand-500/15 text-brand-600 border border-brand-500/25";
|
||||
return "bg-brand-500/15 text-brand-600 border border-brand-500/25"
|
||||
case "admin":
|
||||
return "bg-brand-100 text-brand-600 border border-brand-200";
|
||||
return "bg-brand-100 text-brand-600 border border-brand-200"
|
||||
case "content_manager":
|
||||
return "bg-mint-100 text-mint-500 border border-mint-300/40";
|
||||
return "bg-mint-100 text-mint-500 border border-mint-300/40"
|
||||
case "instructor":
|
||||
return "bg-gold-100 text-gold-600 border border-gold-300/40";
|
||||
return "bg-gold-100 text-gold-600 border border-gold-300/40"
|
||||
case "support_agent":
|
||||
return "bg-orange-100 text-orange-600 border border-orange-200";
|
||||
return "bg-orange-100 text-orange-600 border border-orange-200"
|
||||
case "finance":
|
||||
return "bg-sky-100 text-sky-600 border border-sky-200";
|
||||
return "bg-sky-100 text-sky-600 border border-sky-200"
|
||||
case "hr":
|
||||
return "bg-pink-100 text-pink-600 border border-pink-200";
|
||||
return "bg-pink-100 text-pink-600 border border-pink-200"
|
||||
case "analyst":
|
||||
return "bg-violet-100 text-violet-600 border border-violet-200";
|
||||
return "bg-violet-100 text-violet-600 border border-violet-200"
|
||||
default:
|
||||
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200";
|
||||
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200"
|
||||
}
|
||||
}
|
||||
|
||||
function ReadOnlyField({ label, value }: { label: string; value: string }) {
|
||||
function DetailRow({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-grayScale-400">
|
||||
{label}
|
||||
</label>
|
||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2.5 text-sm text-grayScale-600">
|
||||
{value || "—"}
|
||||
<div className="flex items-start gap-3 py-3.5">
|
||||
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-50">
|
||||
<Icon className="h-4 w-4 text-grayScale-500" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">{label}</p>
|
||||
<p className="mt-0.5 break-words text-sm font-medium text-grayScale-800">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function StatTile({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-xl border border-grayScale-100 bg-white px-4 py-3.5 shadow-soft">
|
||||
<div className="flex items-center gap-2 text-grayScale-500">
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
<span className="text-xs font-medium">{label}</span>
|
||||
</div>
|
||||
<p className="mt-1.5 text-sm font-semibold text-grayScale-800">{value}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||
<div className="animate-pulse">
|
||||
<div className="rounded-2xl bg-grayScale-100 h-[200px]" />
|
||||
<div className="mt-6 grid gap-6 lg:grid-cols-3">
|
||||
<div className="lg:col-span-2 rounded-2xl bg-grayScale-100 h-96" />
|
||||
<div className="rounded-2xl bg-grayScale-100 h-96" />
|
||||
</div>
|
||||
<div className="h-8 w-56 animate-pulse rounded-lg bg-grayScale-100" />
|
||||
<div className="h-24 animate-pulse rounded-xl bg-grayScale-100" />
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{[1, 2, 3, 4].map((item) => (
|
||||
<div key={item} className="h-20 animate-pulse rounded-xl bg-grayScale-100" />
|
||||
))}
|
||||
</div>
|
||||
<div className="h-72 animate-pulse rounded-xl bg-grayScale-100" />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export function TeamMemberDetailPage() {
|
||||
const { id } = useParams();
|
||||
const [member, setMember] = useState<TeamMember | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { id } = useParams()
|
||||
const [member, setMember] = useState<TeamMemberDetail | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
const fetchMember = async () => {
|
||||
try {
|
||||
const res = await getTeamMemberById(Number(id));
|
||||
setMember(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch team member", err);
|
||||
setError("Team member not found.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchMember();
|
||||
}, [id]);
|
||||
const memberId = Number(id)
|
||||
if (!Number.isFinite(memberId) || memberId <= 0) {
|
||||
setError("Invalid team member ID.")
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (loading) return <LoadingSkeleton />;
|
||||
const fetchMember = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await getTeamMemberById(memberId)
|
||||
setMember(res.data.data)
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch team member", err)
|
||||
setMember(null)
|
||||
setError("Team member not found.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void fetchMember()
|
||||
}, [id])
|
||||
|
||||
if (loading) return <LoadingSkeleton />
|
||||
|
||||
if (error || !member) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||
<Link
|
||||
to="/team"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||
|
|
@ -116,23 +194,24 @@ export function TeamMemberDetailPage() {
|
|||
</Link>
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center gap-4 p-10">
|
||||
<div className="h-16 w-16 rounded-full bg-grayScale-100 flex items-center justify-center">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-grayScale-100">
|
||||
<User className="h-8 w-8 text-grayScale-300" />
|
||||
</div>
|
||||
<div className="text-lg font-semibold text-grayScale-600">
|
||||
<p className="text-lg font-semibold text-grayScale-600">
|
||||
{error || "Member not found"}
|
||||
</div>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
const fullName = `${member.first_name} ${member.last_name}`;
|
||||
const initials = `${member.first_name?.[0] ?? ""}${member.last_name?.[0] ?? ""}`.toUpperCase();
|
||||
const fullName = `${member.first_name} ${member.last_name}`.trim()
|
||||
const initials = `${member.first_name?.[0] ?? ""}${member.last_name?.[0] ?? ""}`.toUpperCase()
|
||||
const isActive = member.status.trim().toLowerCase() === "active"
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-full max-w-4xl space-y-5">
|
||||
<Link
|
||||
to="/team"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||
|
|
@ -141,178 +220,102 @@ export function TeamMemberDetailPage() {
|
|||
Back to Team
|
||||
</Link>
|
||||
|
||||
{/* Hero Banner */}
|
||||
<div className="relative overflow-hidden rounded-2xl bg-gradient-to-r from-[#1a1f4e] via-[#2d2b6b] to-[#3b3480] px-6 py-12 sm:px-10 sm:py-14">
|
||||
<div className="relative z-10 max-w-2xl">
|
||||
<h1 className="text-3xl font-bold text-white sm:text-4xl">
|
||||
Hello {member.first_name}
|
||||
</h1>
|
||||
<p className="mt-3 text-sm leading-relaxed text-white/70">
|
||||
This is the profile page. You can see the progress made with their
|
||||
work and manage their projects or assigned tasks
|
||||
</p>
|
||||
<Button className="mt-5 rounded-full bg-brand-600 px-6 hover:bg-brand-500">
|
||||
Edit profile
|
||||
</Button>
|
||||
</div>
|
||||
{/* Decorative circles */}
|
||||
<div className="pointer-events-none absolute -right-10 -top-10 h-52 w-52 rounded-full bg-white/5" />
|
||||
<div className="pointer-events-none absolute -bottom-16 right-20 h-40 w-40 rounded-full bg-white/5" />
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Team directory</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">{fullName}</h1>
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
Member #{member.id} · {displayValue(member.department)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Two-column layout */}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Left: My Account Card */}
|
||||
<Card className="lg:col-span-2">
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-lg">My account</CardTitle>
|
||||
<Button
|
||||
size="sm"
|
||||
className="rounded-full bg-brand-600 px-5 hover:bg-brand-500"
|
||||
<Card className="border-grayScale-100 shadow-soft">
|
||||
<CardContent className="flex flex-col gap-4 p-5 sm:flex-row sm:items-center">
|
||||
<Avatar className="h-14 w-14 shrink-0">
|
||||
<AvatarFallback className="bg-grayScale-100 text-base font-semibold text-grayScale-600">
|
||||
{initials || "?"}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-lg font-semibold text-grayScale-800">{fullName}</p>
|
||||
<p className="text-sm text-grayScale-500">{displayValue(member.job_title)}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 sm:justify-end">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium",
|
||||
getRoleBadgeClasses(member.team_role),
|
||||
)}
|
||||
>
|
||||
Settings
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* User Information */}
|
||||
<div>
|
||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
||||
User Information
|
||||
</h4>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<ReadOnlyField label="Username" value={member.email} />
|
||||
<ReadOnlyField label="Email address" value={member.email} />
|
||||
<ReadOnlyField label="First name" value={member.first_name} />
|
||||
<ReadOnlyField label="Last name" value={member.last_name} />
|
||||
<ReadOnlyField label="Job Title" value={member.job_title} />
|
||||
<ReadOnlyField label="Department" value={member.department} />
|
||||
</div>
|
||||
</div>
|
||||
<Shield className="mr-1 h-3 w-3" />
|
||||
{formatRoleLabel(member.team_role)}
|
||||
</span>
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{formatStatusLabel(member.status)}
|
||||
</Badge>
|
||||
<Badge variant={member.email_verified ? "default" : "outline"}>
|
||||
{member.email_verified ? "Verified" : "Unverified"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Contact Information */}
|
||||
<div>
|
||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
||||
Contact Information
|
||||
</h4>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<ReadOnlyField label="Phone" value={member.phone_number} />
|
||||
<ReadOnlyField
|
||||
label="Employment Type"
|
||||
value={formatEmploymentType(member.employment_type)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* About Me */}
|
||||
<div>
|
||||
<h4 className="mb-4 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
||||
About Me
|
||||
</h4>
|
||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-3 text-sm leading-relaxed text-grayScale-600">
|
||||
{member.bio || "—"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Permissions */}
|
||||
{member.permissions.length > 0 && (
|
||||
<div>
|
||||
<h4 className="mb-4 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
|
||||
<KeyRound className="h-3.5 w-3.5" />
|
||||
Permissions
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{member.permissions.map((perm) => (
|
||||
<Badge
|
||||
key={perm}
|
||||
className="bg-grayScale-100 text-grayScale-600 border border-grayScale-200 font-mono text-xs"
|
||||
>
|
||||
{perm}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Right: Profile Card */}
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center p-6">
|
||||
{/* Avatar with gradient ring */}
|
||||
<div className="relative mt-2">
|
||||
<div className="rounded-full bg-gradient-to-br from-brand-400 via-brand-600 to-mint-500 p-1">
|
||||
<Avatar className="h-28 w-28 ring-4 ring-white">
|
||||
<AvatarImage src={undefined} alt={fullName} />
|
||||
<AvatarFallback className="bg-brand-100 text-brand-600 text-3xl font-bold">
|
||||
{initials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="mt-4 text-lg font-bold text-grayScale-600">
|
||||
{fullName}
|
||||
</h3>
|
||||
<p className="text-sm text-grayScale-400">{member.job_title}</p>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="mt-5 flex w-full gap-3">
|
||||
<Button className="flex-1 rounded-full bg-mint-500 text-white hover:bg-mint-300">
|
||||
Connect
|
||||
</Button>
|
||||
<Button className="flex-1 rounded-full bg-grayScale-600 text-white hover:bg-grayScale-500">
|
||||
<MessageCircle className="h-4 w-4" />
|
||||
Message
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Stats row */}
|
||||
<div className="mt-6 grid w-full grid-cols-3 divide-x divide-grayScale-200 text-center">
|
||||
<div className="px-2">
|
||||
<p className="text-xs font-medium text-grayScale-400">Role</p>
|
||||
<p className="mt-1">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold",
|
||||
getRoleBadgeClasses(member.team_role)
|
||||
)}
|
||||
>
|
||||
<Shield className="h-3 w-3" />
|
||||
{formatRoleLabel(member.team_role)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="px-2">
|
||||
<p className="text-xs font-medium text-grayScale-400">Status</p>
|
||||
<p className="mt-1">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium",
|
||||
member.status === "active"
|
||||
? "bg-mint-100 text-mint-500"
|
||||
: "bg-destructive/10 text-destructive"
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"h-1.5 w-1.5 rounded-full",
|
||||
member.status === "active" ? "bg-mint-500" : "bg-destructive"
|
||||
)}
|
||||
/>
|
||||
{member.status === "active" ? "Active" : "Inactive"}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="px-2">
|
||||
<p className="text-xs font-medium text-grayScale-400">Type</p>
|
||||
<p className="mt-1 text-xs font-medium text-grayScale-600">
|
||||
{formatEmploymentType(member.employment_type)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<StatTile icon={CalendarDays} label="Joined" value={formatDate(member.created_at)} />
|
||||
<StatTile icon={Clock3} label="Last login" value={formatDateTime(member.last_login)} />
|
||||
<StatTile
|
||||
icon={BadgeCheck}
|
||||
label="Email status"
|
||||
value={member.email_verified ? "Verified" : "Not verified"}
|
||||
/>
|
||||
<StatTile icon={Clock3} label="Last updated" value={formatDateTime(member.updated_at)} />
|
||||
</div>
|
||||
|
||||
<Card className="border-grayScale-100 shadow-soft">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-base">Member record</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{member.bio ? (
|
||||
<div className="mb-4 rounded-lg border border-grayScale-100 bg-grayScale-50/60 px-4 py-3">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">Bio</p>
|
||||
<p className="mt-1 text-sm leading-relaxed text-grayScale-700">{member.bio}</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-0 md:grid-cols-2 md:gap-x-8">
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
Contact
|
||||
</p>
|
||||
<DetailRow icon={Mail} label="Email" value={displayValue(member.email)} />
|
||||
<Separator />
|
||||
<DetailRow icon={Phone} label="Phone" value={displayValue(member.phone_number)} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
Role & organization
|
||||
</p>
|
||||
<DetailRow icon={Shield} label="Team role" value={formatRoleLabel(member.team_role)} />
|
||||
<Separator />
|
||||
<DetailRow icon={Building2} label="Department" value={displayValue(member.department)} />
|
||||
<Separator />
|
||||
<DetailRow icon={Briefcase} label="Job title" value={displayValue(member.job_title)} />
|
||||
<Separator />
|
||||
<DetailRow icon={Hash} label="Member ID" value={String(member.id)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
<div className="flex items-center gap-2 text-xs text-grayScale-400">
|
||||
<UserCircle2 className="h-3.5 w-3.5" />
|
||||
<span>Read-only team directory record</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,10 +13,10 @@ import {
|
|||
Globe,
|
||||
Monitor,
|
||||
FileText,
|
||||
X,
|
||||
Info,
|
||||
Shield,
|
||||
} from "lucide-react";
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import {
|
||||
|
|
@ -35,6 +35,7 @@ import {
|
|||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "../../components/ui/dialog";
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||
import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api";
|
||||
|
|
@ -193,13 +194,18 @@ export function UserLogPage() {
|
|||
|
||||
const clearFilters = () => {
|
||||
setActionFilter("");
|
||||
setSearchQuery("");
|
||||
setDateAfter("");
|
||||
setDateBefore("");
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const hasActiveFilters = actionFilter || dateAfter || dateBefore;
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: actionFilter },
|
||||
{ value: dateAfter },
|
||||
{ value: dateBefore },
|
||||
]);
|
||||
|
||||
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim());
|
||||
|
||||
// Pagination
|
||||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||
|
|
@ -291,75 +297,66 @@ export function UserLogPage() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border bg-white p-4">
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by message, action, or role..."
|
||||
className="pl-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by message, action, or role..."
|
||||
className="pl-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="relative">
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => {
|
||||
setActionFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">Action: All</option>
|
||||
{ACTION_TYPES.map((action) => (
|
||||
<option key={action} value={action}>
|
||||
{formatActionLabel(action)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs font-medium text-grayScale-400">From</label>
|
||||
<input
|
||||
type="date"
|
||||
value={dateAfter}
|
||||
onChange={(e) => {
|
||||
setDateAfter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs font-medium text-grayScale-400">To</label>
|
||||
<input
|
||||
type="date"
|
||||
value={dateBefore}
|
||||
onChange={(e) => {
|
||||
setDateBefore(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => {
|
||||
setActionFilter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 appearance-none rounded-lg border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
>
|
||||
<option value="">Action: All</option>
|
||||
{ACTION_TYPES.map((action) => (
|
||||
<option key={action} value={action}>
|
||||
{formatActionLabel(action)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs font-medium text-grayScale-400">From</label>
|
||||
<input
|
||||
type="date"
|
||||
value={dateAfter}
|
||||
onChange={(e) => {
|
||||
setDateAfter(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 rounded-lg border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs font-medium text-grayScale-400">To</label>
|
||||
<input
|
||||
type="date"
|
||||
value={dateBefore}
|
||||
onChange={(e) => {
|
||||
setDateBefore(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-10 rounded-lg border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasActiveFilters && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={clearFilters}
|
||||
className="gap-1 text-grayScale-400 hover:text-grayScale-600"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-xl border bg-white">
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { CalendarDays, ChevronDown, ChevronLeft, ChevronRight, Search, SlidersHorizontal } from "lucide-react"
|
||||
import { CalendarDays, ChevronDown, ChevronLeft, ChevronRight, Search } from "lucide-react"
|
||||
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
|
|
@ -15,6 +16,7 @@ import {
|
|||
} from "../../components/ui/table"
|
||||
import { getDeletionRequests } from "../../api/users.api"
|
||||
import { getRoles } from "../../api/rbac.api"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import type {
|
||||
|
|
@ -236,6 +238,16 @@ export function DeletionRequestsPage() {
|
|||
setPage(1)
|
||||
}
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: role },
|
||||
{ value: status },
|
||||
{ value: state },
|
||||
{ value: requestedAfter },
|
||||
{ value: requestedBefore },
|
||||
{ value: scheduledAfter },
|
||||
{ value: scheduledBefore },
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
|
|
@ -245,28 +257,29 @@ export function DeletionRequestsPage() {
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="overflow-visible rounded-2xl border border-brand-100/70 bg-white shadow-soft">
|
||||
<CardHeader className="border-b border-brand-100/70 bg-gradient-to-r from-brand-100/50 via-white to-brand-100/25 pb-4">
|
||||
<CardTitle className="flex items-center gap-2 text-base font-semibold text-grayScale-700">
|
||||
<SlidersHorizontal className="h-4 w-4 text-brand-600" />
|
||||
Filters
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5 bg-gradient-to-b from-white to-brand-100/10 pt-5">
|
||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-4">
|
||||
<div className="relative lg:col-span-2">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
placeholder="Search name, email, phone..."
|
||||
className="h-11 rounded-xl border-grayScale-200 bg-white pl-10 shadow-sm transition focus-visible:border-brand-400 focus-visible:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative" ref={roleMenuRef}>
|
||||
<AdminFiltersPanel
|
||||
className="overflow-visible rounded-2xl border border-brand-100/70 shadow-soft"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={resetFilters}
|
||||
clearLabel="Clear filters"
|
||||
summary={`${total} request${total === 1 ? "" : "s"}`}
|
||||
search={
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-300" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
placeholder="Search name, email, phone..."
|
||||
className="h-11 rounded-xl border-grayScale-200 bg-white pl-10 shadow-sm transition focus-visible:border-brand-400 focus-visible:ring-brand-200"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
|
||||
<div className="relative" ref={roleMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-11 w-full items-center justify-between rounded-xl border border-grayScale-200 bg-white px-3 text-left text-sm text-grayScale-600 shadow-sm transition hover:bg-grayScale-50 focus:outline-none focus-visible:border-brand-400 focus-visible:ring-2 focus-visible:ring-brand-200"
|
||||
|
|
@ -478,18 +491,8 @@ export function DeletionRequestsPage() {
|
|||
}}
|
||||
placeholder={`Scheduled before (${DATE_PLACEHOLDER})`}
|
||||
/>
|
||||
<div className="flex justify-end lg:col-start-4 lg:col-span-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-11 rounded-xl border-brand-200 px-5 text-brand-700 hover:bg-brand-100/40"
|
||||
onClick={resetFilters}
|
||||
>
|
||||
Clear Filters
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="border-b border-grayScale-200 pb-4">
|
||||
|
|
|
|||
|
|
@ -1,18 +1,13 @@
|
|||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
BarChart3,
|
||||
BookOpen,
|
||||
Calendar,
|
||||
CheckCircle2,
|
||||
Globe,
|
||||
GraduationCap,
|
||||
Lock,
|
||||
Mail,
|
||||
MapPin,
|
||||
Phone,
|
||||
PlayCircle,
|
||||
RefreshCw,
|
||||
Target,
|
||||
UserPlus,
|
||||
} from "lucide-react";
|
||||
|
|
@ -23,26 +18,17 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/ca
|
|||
import { Separator } from "../../components/ui/separator";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useUsersStore } from "../../zustand/userStore";
|
||||
import { getUserById, getUserRecentActivity } from "../../api/users.api";
|
||||
import { getCourseCategories, getCoursesByCategory } from "../../api/courses.api";
|
||||
import {
|
||||
getAdminLearnerCourseProgress,
|
||||
getAdminLearnerCourseProgressSummary,
|
||||
} from "../../api/progress.api";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../components/ui/table";
|
||||
import { Select } from "../../components/ui/select";
|
||||
getUserById,
|
||||
getUserLearningActivity,
|
||||
getUserRecentActivity,
|
||||
getUserSubscriptions,
|
||||
} from "../../api/users.api";
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
||||
import type { LearnerCourseProgressItem, LearnerCourseProgressSummary } from "../../types/progress.types";
|
||||
import type { Course } from "../../types/course.types";
|
||||
import type { UserRecentActivityItem } from "../../types/user.types";
|
||||
import type { UserProfileData, UserRecentActivityItem } from "../../types/user.types";
|
||||
import type { UserLearningActivityData, UserSubscriptionsData } from "../../types/userAdmin.types";
|
||||
import { UserLearningActivitySection } from "./components/UserLearningActivitySection";
|
||||
import { UserSubscriptionsSection } from "./components/UserSubscriptionsSection";
|
||||
|
||||
const activityIcons = {
|
||||
completed: CheckCircle2,
|
||||
|
|
@ -59,7 +45,59 @@ function visualActivityKind(kind: string): keyof typeof activityIcons {
|
|||
return "default";
|
||||
}
|
||||
|
||||
/** Matches Recent Activity mock: "Today, 10:27 AM" / "Yesterday, 3:45 PM" / "Jan 10, 2025". */
|
||||
function displayValue(value: string | null | undefined): string {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : "—";
|
||||
}
|
||||
|
||||
function formatRoleLabel(role: string): string {
|
||||
const value = role.trim();
|
||||
if (!value) return "—";
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim();
|
||||
if (!value) return "—";
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function formatAgeGroup(ageGroup: string): string {
|
||||
const value = ageGroup.trim();
|
||||
if (!value) return "—";
|
||||
return value.replace(/_/g, "-");
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null | undefined): string {
|
||||
if (!dateStr?.trim()) return "—";
|
||||
const date = new Date(dateStr);
|
||||
if (Number.isNaN(date.getTime())) return dateStr;
|
||||
return date.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
function formatDateTime(value?: string | null): string {
|
||||
if (!value?.trim()) return "—";
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return "—";
|
||||
return parsed.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function formatActivityOccurredAt(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return "—";
|
||||
|
|
@ -69,7 +107,7 @@ function formatActivityOccurredAt(iso: string): string {
|
|||
const startThat = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const dayDiff = Math.round((startToday - startThat) / 86_400_000);
|
||||
|
||||
const timePart = d.toLocaleTimeString("en-US", {
|
||||
const timePart = d.toLocaleTimeString(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
hour12: true,
|
||||
|
|
@ -78,114 +116,131 @@ function formatActivityOccurredAt(iso: string): string {
|
|||
if (dayDiff === 0) return `Today, ${timePart}`;
|
||||
if (dayDiff === 1) return `Yesterday, ${timePart}`;
|
||||
|
||||
return d.toLocaleDateString("en-US", {
|
||||
return d.toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
type CourseOption = Course & { category_name: string };
|
||||
function getAccountStatusClasses(status: string): string {
|
||||
const normalized = status.trim().toUpperCase();
|
||||
if (normalized === "ACTIVE") {
|
||||
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
||||
}
|
||||
return "bg-destructive/15 text-destructive border border-destructive/25";
|
||||
}
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
|
||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||
<div className="space-y-6">
|
||||
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="h-64 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
<div className="h-72 animate-pulse rounded-2xl bg-grayScale-100" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UserDetailPage() {
|
||||
const { id } = useParams();
|
||||
const userProfile = useUsersStore((s) => s.userProfile);
|
||||
const setUserProfile = useUsersStore((s) => s.setUserProfile);
|
||||
const [courseOptions, setCourseOptions] = useState<CourseOption[]>([]);
|
||||
const [loadingCourseOptions, setLoadingCourseOptions] = useState(false);
|
||||
const [selectedProgressCourseId, setSelectedProgressCourseId] = useState<number | null>(null);
|
||||
const [progressItems, setProgressItems] = useState<LearnerCourseProgressItem[]>([]);
|
||||
const [progressSummary, setProgressSummary] = useState<LearnerCourseProgressSummary | null>(null);
|
||||
const [loadingProgress, setLoadingProgress] = useState(false);
|
||||
const [progressError, setProgressError] = useState<string | null>(null);
|
||||
const [user, setUser] = useState<UserProfileData | null>(null);
|
||||
const [loadingUser, setLoadingUser] = useState(true);
|
||||
const [userError, setUserError] = useState<string | null>(null);
|
||||
const [learningActivity, setLearningActivity] = useState<UserLearningActivityData | null>(null);
|
||||
const [learningActivityLoading, setLearningActivityLoading] = useState(false);
|
||||
const [learningActivityError, setLearningActivityError] = useState<string | null>(null);
|
||||
const [subscriptions, setSubscriptions] = useState<UserSubscriptionsData | null>(null);
|
||||
const [subscriptionsLoading, setSubscriptionsLoading] = useState(false);
|
||||
const [subscriptionsError, setSubscriptionsError] = useState<string | null>(null);
|
||||
const [recentActivityItems, setRecentActivityItems] = useState<UserRecentActivityItem[]>([]);
|
||||
const [recentActivityLoading, setRecentActivityLoading] = useState(false);
|
||||
const [recentActivityError, setRecentActivityError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userId = Number(id);
|
||||
if (!Number.isFinite(userId) || userId <= 0) {
|
||||
setUserError("Invalid user ID.");
|
||||
setLoadingUser(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchUser = async () => {
|
||||
setLoadingUser(true);
|
||||
setUserError(null);
|
||||
try {
|
||||
const res = await getUserById(userId);
|
||||
setUser(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch user profile", err);
|
||||
setUser(null);
|
||||
setUserError("User not found.");
|
||||
} finally {
|
||||
setLoadingUser(false);
|
||||
}
|
||||
};
|
||||
|
||||
void fetchUser();
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
const res = await getUserById(Number(id));
|
||||
setUserProfile(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch user profile", err);
|
||||
setUserProfile(null);
|
||||
}
|
||||
};
|
||||
fetchUser();
|
||||
}, [id, setUserProfile]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadCourseOptions = async () => {
|
||||
setLoadingCourseOptions(true);
|
||||
try {
|
||||
const categoriesRes = await getCourseCategories();
|
||||
const categories = categoriesRes.data?.data?.categories ?? [];
|
||||
const options: CourseOption[] = [];
|
||||
|
||||
for (const category of categories) {
|
||||
const coursesRes = await getCoursesByCategory(category.id);
|
||||
const courses = coursesRes.data?.data?.courses ?? [];
|
||||
options.push(
|
||||
...courses.map((course) => ({
|
||||
...course,
|
||||
category_name: category.name,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
setCourseOptions(options);
|
||||
if (options.length > 0 && !selectedProgressCourseId) {
|
||||
setSelectedProgressCourseId(options[0].id);
|
||||
}
|
||||
} catch {
|
||||
setCourseOptions([]);
|
||||
} finally {
|
||||
setLoadingCourseOptions(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadCourseOptions();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !selectedProgressCourseId) return;
|
||||
|
||||
const userId = Number(id);
|
||||
if (Number.isNaN(userId)) return;
|
||||
|
||||
const loadProgress = async () => {
|
||||
setLoadingProgress(true);
|
||||
setProgressError(null);
|
||||
const loadLearningActivity = async () => {
|
||||
setLearningActivityLoading(true);
|
||||
setLearningActivityError(null);
|
||||
try {
|
||||
const [summaryRes, detailRes] = await Promise.all([
|
||||
getAdminLearnerCourseProgressSummary(userId, selectedProgressCourseId),
|
||||
getAdminLearnerCourseProgress(userId, selectedProgressCourseId),
|
||||
]);
|
||||
|
||||
setProgressSummary(summaryRes.data?.data ?? null);
|
||||
const ordered = [...(detailRes.data?.data ?? [])].sort(
|
||||
(a, b) => a.display_order - b.display_order || a.sub_course_id - b.sub_course_id,
|
||||
);
|
||||
setProgressItems(ordered);
|
||||
} catch (err: any) {
|
||||
setProgressSummary(null);
|
||||
setProgressItems([]);
|
||||
const status = err?.response?.status;
|
||||
if (status === 403) {
|
||||
setProgressError("Missing permission: progress.get_any_user");
|
||||
} else if (status === 400) {
|
||||
setProgressError("Invalid learner or course selection.");
|
||||
} else {
|
||||
setProgressError(err?.response?.data?.message || "Failed to load learner progress.");
|
||||
}
|
||||
const res = await getUserLearningActivity(userId);
|
||||
setLearningActivity(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load learning activity", err);
|
||||
setLearningActivity(null);
|
||||
const message =
|
||||
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||
"Failed to load learning activity.";
|
||||
setLearningActivityError(message);
|
||||
} finally {
|
||||
setLoadingProgress(false);
|
||||
setLearningActivityLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProgress();
|
||||
}, [id, selectedProgressCourseId]);
|
||||
void loadLearningActivity();
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
const userId = Number(id);
|
||||
if (Number.isNaN(userId)) return;
|
||||
|
||||
const loadSubscriptions = async () => {
|
||||
setSubscriptionsLoading(true);
|
||||
setSubscriptionsError(null);
|
||||
try {
|
||||
const res = await getUserSubscriptions(userId);
|
||||
setSubscriptions(res.data.data);
|
||||
} catch (err) {
|
||||
console.error("Failed to load subscriptions", err);
|
||||
setSubscriptions(null);
|
||||
const message =
|
||||
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||
"Failed to load subscriptions.";
|
||||
setSubscriptionsError(message);
|
||||
} finally {
|
||||
setSubscriptionsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
void loadSubscriptions();
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
|
|
@ -194,57 +249,46 @@ export function UserDetailPage() {
|
|||
|
||||
const loadRecent = async () => {
|
||||
setRecentActivityLoading(true);
|
||||
setRecentActivityError(null);
|
||||
try {
|
||||
const res = await getUserRecentActivity(userId);
|
||||
const items = res.data?.data?.items ?? [];
|
||||
const items = [...(res.data.data.items ?? [])].sort(
|
||||
(a, b) => new Date(b.occurred_at).getTime() - new Date(a.occurred_at).getTime(),
|
||||
);
|
||||
setRecentActivityItems(items);
|
||||
} catch (err) {
|
||||
console.error("Failed to load recent activity", err);
|
||||
setRecentActivityItems([]);
|
||||
const message =
|
||||
(err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
|
||||
"Failed to load recent activity.";
|
||||
setRecentActivityError(message);
|
||||
} finally {
|
||||
setRecentActivityLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadRecent();
|
||||
void loadRecent();
|
||||
}, [id]);
|
||||
|
||||
const progressMetrics = useMemo(() => {
|
||||
if (progressSummary) {
|
||||
return {
|
||||
total: progressSummary.total_sub_courses ?? 0,
|
||||
completed: progressSummary.completed_sub_courses ?? 0,
|
||||
inProgress: progressSummary.in_progress_sub_courses ?? 0,
|
||||
locked: progressSummary.locked_sub_courses ?? 0,
|
||||
averageProgress: Math.round(progressSummary.overall_progress_percentage ?? 0),
|
||||
};
|
||||
}
|
||||
if (loadingUser) return <LoadingSkeleton />;
|
||||
|
||||
const total = progressItems.length;
|
||||
const completed = progressItems.filter((item) => item.progress_status === "COMPLETED").length;
|
||||
const inProgress = progressItems.filter((item) => item.progress_status === "IN_PROGRESS").length;
|
||||
const locked = progressItems.filter((item) => item.is_locked).length;
|
||||
const averageProgress =
|
||||
total === 0
|
||||
? 0
|
||||
: Math.round(
|
||||
progressItems.reduce((sum, item) => sum + Number(item.progress_percentage || 0), 0) / total,
|
||||
);
|
||||
|
||||
return { total, completed, inProgress, locked, averageProgress };
|
||||
}, [progressItems, progressSummary]);
|
||||
|
||||
if (!userProfile) {
|
||||
if (userError || !user) {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-3xl space-y-4 py-12">
|
||||
<Link
|
||||
to="/users/list"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Users
|
||||
</Link>
|
||||
<Card className="shadow-soft">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-10">
|
||||
<div className="h-16 w-16 rounded-full bg-grayScale-100 flex items-center justify-center">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-grayScale-100">
|
||||
<Target className="h-8 w-8 text-grayScale-300" />
|
||||
</div>
|
||||
<div className="text-lg font-semibold text-grayScale-600">
|
||||
User not found
|
||||
</div>
|
||||
<p className="text-lg font-semibold text-grayScale-600">{userError || "User not found"}</p>
|
||||
<Button asChild variant="outline" className="mt-2">
|
||||
<Link to="/users/list">Back to Users</Link>
|
||||
</Button>
|
||||
|
|
@ -254,92 +298,74 @@ export function UserDetailPage() {
|
|||
);
|
||||
}
|
||||
|
||||
const user = userProfile;
|
||||
const fullName = `${user.first_name} ${user.last_name}`;
|
||||
const fullName = `${user.first_name} ${user.last_name}`.trim();
|
||||
const initials = `${user.first_name?.[0] ?? ""}${user.last_name?.[0] ?? ""}`.toUpperCase();
|
||||
const profilePicture = user.profile_picture_url?.trim() || undefined;
|
||||
|
||||
const infoFields = [
|
||||
{ icon: Phone, label: "Phone", value: user.phone_number },
|
||||
{ icon: Mail, label: "Email", value: user.email },
|
||||
{ icon: Globe, label: "Country", value: user.country || "Ethiopia" },
|
||||
{ icon: MapPin, label: "Region", value: user.region },
|
||||
const contactFields = [
|
||||
{ icon: Mail, label: "Email", value: displayValue(user.email) },
|
||||
{ icon: Globe, label: "Country", value: displayValue(user.country) },
|
||||
{ icon: MapPin, label: "Region", value: displayValue(user.region) },
|
||||
];
|
||||
|
||||
const statusVariant = (status: LearnerCourseProgressItem["progress_status"]) => {
|
||||
if (status === "COMPLETED") return "success" as const;
|
||||
if (status === "IN_PROGRESS") return "warning" as const;
|
||||
return "secondary" as const;
|
||||
};
|
||||
|
||||
const formatDateTime = (value?: string | null) => {
|
||||
if (!value) return "—";
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return "—";
|
||||
return parsed.toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Link
|
||||
to="/users/list"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/users/list"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to Users
|
||||
</Link>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Learners</p>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">{fullName}</h1>
|
||||
<p className="mt-1 text-sm text-grayScale-500">
|
||||
User #{user.id} · {formatRoleLabel(user.role)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
|
||||
{/* ── Left column ── */}
|
||||
<div className="space-y-6">
|
||||
{/* Profile card */}
|
||||
<Card className="overflow-hidden">
|
||||
<div className="h-24 bg-gradient-to-br from-brand-600 via-brand-500 to-brand-400" />
|
||||
<CardContent className="-mt-12 space-y-5 px-4 sm:px-6 pb-6 pt-0">
|
||||
<div className="flex flex-col items-center text-center">
|
||||
<Avatar className="h-20 w-20 ring-4 ring-white shadow-soft">
|
||||
<AvatarImage src={user.profile_picture_url ?? undefined} alt={fullName} />
|
||||
<AvatarFallback className="bg-brand-100 text-brand-600 text-xl">
|
||||
{initials}
|
||||
<Card className="overflow-hidden shadow-soft">
|
||||
<CardContent className="space-y-5 p-5">
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar className="h-16 w-16 shrink-0">
|
||||
{profilePicture ? <AvatarImage src={profilePicture} alt={fullName} /> : null}
|
||||
<AvatarFallback className="bg-brand-100 text-lg font-semibold text-brand-600">
|
||||
{initials || "?"}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<h2 className="mt-3 text-lg font-semibold text-grayScale-600">
|
||||
{fullName}
|
||||
</h2>
|
||||
<Badge
|
||||
className={cn(
|
||||
"mt-1.5",
|
||||
user.status === "ACTIVE"
|
||||
? "bg-mint-500/15 text-mint-500 border border-mint-500/25"
|
||||
: "bg-destructive/15 text-destructive border border-destructive/25"
|
||||
)}
|
||||
>
|
||||
{user.status === "ACTIVE" ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
<div className="min-w-0">
|
||||
<h2 className="truncate text-lg font-semibold text-grayScale-800">{fullName}</h2>
|
||||
{user.nick_name.trim() ? (
|
||||
<p className="text-sm text-grayScale-500">@{user.nick_name.trim()}</p>
|
||||
) : null}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
<Badge className={cn(getAccountStatusClasses(user.status))}>
|
||||
{formatStatusLabel(user.status)}
|
||||
</Badge>
|
||||
<Badge variant={user.email_verified ? "default" : "outline"}>
|
||||
{user.email_verified ? "Email verified" : "Email unverified"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-3">
|
||||
{infoFields.map(({ icon: Icon, label, value }) => (
|
||||
{contactFields.map(({ icon: Icon, label, value }) => (
|
||||
<div key={label} className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
|
||||
<Icon className="h-4 w-4 text-grayScale-400" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
{label}
|
||||
</div>
|
||||
<div className="truncate text-sm text-grayScale-600">
|
||||
{value || "—"}
|
||||
</div>
|
||||
</p>
|
||||
<p className="truncate text-sm text-grayScale-700">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
|
@ -347,275 +373,96 @@ export function UserDetailPage() {
|
|||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
|
||||
<Calendar className="h-4 w-4 text-grayScale-400" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Joined
|
||||
</div>
|
||||
<div className="text-sm text-grayScale-600">
|
||||
{user.created_at
|
||||
? new Date(user.created_at).toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
})
|
||||
: "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-3 text-sm">
|
||||
<InfoRow label="Joined" value={formatDate(user.created_at)} />
|
||||
<InfoRow label="Last login" value={formatDateTime(user.last_login)} />
|
||||
<InfoRow label="Gender" value={displayValue(user.gender)} />
|
||||
<InfoRow label="Birthday" value={formatDate(user.birth_day)} />
|
||||
<InfoRow label="Occupation" value={displayValue(user.occupation)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Subscription card */}
|
||||
<Card>
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Subscription</CardTitle>
|
||||
<Badge
|
||||
className={cn(
|
||||
user.status === "ACTIVE"
|
||||
? "bg-mint-500/15 text-mint-500 border border-mint-500/25"
|
||||
: "bg-destructive/15 text-destructive border border-destructive/25"
|
||||
)}
|
||||
>
|
||||
{user.status === "ACTIVE" ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
</div>
|
||||
<CardTitle className="text-base">Account</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="rounded-xl bg-grayScale-100 p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Plan
|
||||
</span>
|
||||
<span className="text-sm font-semibold text-grayScale-600">6-Month</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex flex-wrap items-center justify-between gap-1">
|
||||
<span className="text-xs font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Expires
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-grayScale-600">Nov 13, 2025</span>
|
||||
<Badge className="bg-gold-100 text-gold-600 text-[10px] border border-gold-300">
|
||||
3 days left
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button className="w-full bg-brand-600 hover:bg-brand-500 text-white transition-colors">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Extend Subscription
|
||||
</Button>
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<Button variant="outline" className="w-full text-sm">
|
||||
Mark as Paid
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full text-sm text-destructive border-destructive/40 hover:bg-destructive/5"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
<InfoRow
|
||||
label="Phone verified"
|
||||
value={user.phone_verified ? "Verified" : "Not verified"}
|
||||
/>
|
||||
<InfoRow
|
||||
label="Profile completed"
|
||||
value={user.profile_completed ? "Yes" : "No"}
|
||||
/>
|
||||
<InfoRow
|
||||
label="Profile completion"
|
||||
value={`${user.profile_completion_percentage}%`}
|
||||
/>
|
||||
<InfoRow
|
||||
label="Preferred language"
|
||||
value={displayValue(user.preferred_language)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<UserSubscriptionsSection
|
||||
subscriptions={subscriptions}
|
||||
loading={subscriptionsLoading}
|
||||
error={subscriptionsError}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Right column ── */}
|
||||
<div className="space-y-6">
|
||||
{/* Learning profile */}
|
||||
<Card>
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
|
||||
<GraduationCap className="h-4 w-4 text-brand-600" />
|
||||
</div>
|
||||
<CardTitle>Learning Profile</CardTitle>
|
||||
<CardTitle className="text-base">Learning profile</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
|
||||
<InfoItem
|
||||
label="Education Level"
|
||||
value={user.education_level || "Undergraduate"}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Age Group"
|
||||
value={user.age ? `${user.age} years` : "25-34"}
|
||||
/>
|
||||
<div>
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
||||
Proficiency
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-grayScale-600">Intermediate</span>
|
||||
<span className="inline-flex h-5 items-center rounded-md bg-brand-100/60 px-1.5 text-[11px] font-semibold text-brand-600">
|
||||
B1
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<InfoItem
|
||||
label="Preferred Topic"
|
||||
value={user.favoutite_topic || "Business"}
|
||||
/>
|
||||
<TagItem label="Learning Path" value={user.learning_goal || "Business English"} />
|
||||
<TagItem label="Challenge" value={user.language_challange || "Speaking"} />
|
||||
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
||||
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
||||
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
||||
<InfoItem label="Language goal" value={displayValue(user.language_goal)} />
|
||||
<InfoItem label="Challenge" value={displayValue(user.language_challange)} />
|
||||
<InfoItem label="Role" value={formatRoleLabel(user.role)} />
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-2">
|
||||
Primary Goal
|
||||
</div>
|
||||
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-600">
|
||||
{user.learning_goal ||
|
||||
"Improve business communication skills for professional advancement"}
|
||||
</div>
|
||||
</div>
|
||||
{user.learning_goal.trim() ? (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Learning goal
|
||||
</p>
|
||||
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-700">
|
||||
{user.learning_goal.trim()}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Learner course progress */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-100/70">
|
||||
<BarChart3 className="h-4 w-4 text-sky-600" />
|
||||
</div>
|
||||
<CardTitle>Learner Course Progress</CardTitle>
|
||||
</div>
|
||||
<div className="w-full sm:w-72">
|
||||
<Select
|
||||
value={selectedProgressCourseId ? String(selectedProgressCourseId) : ""}
|
||||
onChange={(e) =>
|
||||
setSelectedProgressCourseId(e.target.value ? Number(e.target.value) : null)
|
||||
}
|
||||
disabled={loadingCourseOptions || courseOptions.length === 0}
|
||||
>
|
||||
<option value="">
|
||||
{loadingCourseOptions ? "Loading course sub-categories..." : "Select course sub-category..."}
|
||||
</option>
|
||||
{courseOptions.map((course) => (
|
||||
<option key={course.id} value={course.id}>
|
||||
{course.title} ({course.category_name})
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
|
||||
<Metric label="Total Sub-courses" value={progressMetrics.total} />
|
||||
<Metric label="Completed" value={progressMetrics.completed} />
|
||||
<Metric label="In Progress" value={progressMetrics.inProgress} />
|
||||
<Metric label="Locked" value={progressMetrics.locked} />
|
||||
<Metric label="Avg Progress" value={`${progressMetrics.averageProgress}%`} />
|
||||
</div>
|
||||
<UserLearningActivitySection
|
||||
activity={learningActivity}
|
||||
loading={learningActivityLoading}
|
||||
error={learningActivityError}
|
||||
/>
|
||||
|
||||
{progressError && (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive">
|
||||
{progressError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!progressError && loadingProgress && (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-100 px-3 py-2 text-xs text-grayScale-500">
|
||||
<SpinnerIcon className="h-3.5 w-3.5" />
|
||||
Loading learner progress...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!progressError && !loadingProgress && selectedProgressCourseId && progressItems.length === 0 && (
|
||||
<div className="rounded-lg border border-dashed border-grayScale-200 px-3 py-5 text-center text-xs text-grayScale-400">
|
||||
No learner progress records found for this course sub-category.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!progressError && !loadingProgress && progressItems.length > 0 && (
|
||||
<div className="overflow-x-auto rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Course</TableHead>
|
||||
<TableHead>Level</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Progress</TableHead>
|
||||
<TableHead>Started</TableHead>
|
||||
<TableHead>Completed</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{progressItems.map((item) => (
|
||||
<TableRow key={item.sub_course_id}>
|
||||
<TableCell className="min-w-[220px]">
|
||||
<div className="flex items-start gap-2">
|
||||
{item.is_locked && <Lock className="mt-0.5 h-3.5 w-3.5 text-gold-600" />}
|
||||
<div>
|
||||
<p className="text-sm font-medium text-grayScale-700">{item.title}</p>
|
||||
{item.description && (
|
||||
<p className="mt-0.5 line-clamp-1 text-xs text-grayScale-400">{item.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">{item.level}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={statusVariant(item.progress_status)}>{item.progress_status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="min-w-[170px]">
|
||||
<div className="space-y-1">
|
||||
<div className="h-2 w-full rounded-full bg-grayScale-200">
|
||||
<div
|
||||
className={cn(
|
||||
"h-2 rounded-full transition-all",
|
||||
item.progress_status === "COMPLETED"
|
||||
? "bg-mint-500"
|
||||
: item.progress_status === "IN_PROGRESS"
|
||||
? "bg-gold-600"
|
||||
: "bg-grayScale-300",
|
||||
)}
|
||||
style={{
|
||||
width: `${Math.min(100, Math.max(0, item.progress_percentage || 0))}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-[11px] text-grayScale-500">{item.progress_percentage}%</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatDateTime(item.started_at)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatDateTime(item.completed_at)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent activity */}
|
||||
<Card>
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gold-100/60">
|
||||
<BookOpen className="h-4 w-4 text-gold-600" />
|
||||
</div>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
<CardTitle className="text-base">Recent activity</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
|
@ -624,6 +471,8 @@ export function UserDetailPage() {
|
|||
<SpinnerIcon className="h-5 w-5" />
|
||||
Loading activity…
|
||||
</div>
|
||||
) : recentActivityError ? (
|
||||
<p className="py-8 text-center text-sm text-destructive">{recentActivityError}</p>
|
||||
) : recentActivityItems.length === 0 ? (
|
||||
<p className="py-8 text-center text-sm text-grayScale-400">No recent activity yet.</p>
|
||||
) : (
|
||||
|
|
@ -634,9 +483,9 @@ export function UserDetailPage() {
|
|||
const isLast = index === recentActivityItems.length - 1;
|
||||
return (
|
||||
<div key={item.id} className="relative flex gap-4 pb-5 last:pb-0">
|
||||
{!isLast && (
|
||||
{!isLast ? (
|
||||
<div className="absolute bottom-0 left-[15px] top-8 w-px bg-grayScale-200" />
|
||||
)}
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
|
||||
|
|
@ -652,10 +501,10 @@ export function UserDetailPage() {
|
|||
<Icon className="h-4 w-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 pt-1">
|
||||
<div className="text-sm font-medium text-grayScale-600">{item.headline}</div>
|
||||
<div className="mt-0.5 text-xs text-grayScale-400">
|
||||
<p className="text-sm font-medium text-grayScale-700">{item.headline}</p>
|
||||
<p className="mt-0.5 text-xs text-grayScale-400">
|
||||
{formatActivityOccurredAt(item.occurred_at)}
|
||||
</div>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -673,32 +522,17 @@ export function UserDetailPage() {
|
|||
function InfoItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
||||
{label}
|
||||
</div>
|
||||
<div className="text-sm text-grayScale-600">{value}</div>
|
||||
<p className="mb-1 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">{label}</p>
|
||||
<p className="text-sm text-grayScale-700">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ label, value }: { label: string; value: string | number }) {
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2">
|
||||
<div className="text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">{label}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-grayScale-700">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TagItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400 mb-1">
|
||||
{label}
|
||||
</div>
|
||||
<span className="inline-block rounded-lg border border-grayScale-200 bg-grayScale-100 px-2.5 py-1 text-xs font-medium text-grayScale-600">
|
||||
{value}
|
||||
</span>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm text-grayScale-500">{label}</span>
|
||||
<span className="text-sm font-medium text-grayScale-700">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,15 @@ import { ChevronDown, ChevronLeft, ChevronRight, Search, TrendingUp, UserCheck,
|
|||
import { useEffect, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import { ToggleSwitch } from "../../components/ui/toggle-switch"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"
|
||||
import { getDashboard } from "../../api/analytics.api"
|
||||
|
|
@ -310,7 +313,19 @@ export function UsersListPage() {
|
|||
navigate(`/users/${userId}`)
|
||||
}
|
||||
|
||||
const clearExtraFilters = () => {
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: roleFilter },
|
||||
{ value: statusFilter },
|
||||
{ value: createdAfterLocal },
|
||||
{ value: createdBeforeLocal },
|
||||
{ value: countryFilter },
|
||||
{ value: regionFilter },
|
||||
{ value: subscriptionStatusFilter },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setRoleFilter("")
|
||||
setStatusFilter("")
|
||||
setCreatedAfterLocal("")
|
||||
setCreatedBeforeLocal("")
|
||||
setCountryFilter("")
|
||||
|
|
@ -405,10 +420,13 @@ export function UsersListPage() {
|
|||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border">
|
||||
{/* Search & Filters */}
|
||||
<div className="p-4 border-b">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<div className="relative w-full md:max-w-sm">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 border-b rounded-none shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
footer="Dates are sent as RFC3339 (UTC). Country and region filters use the lists above; the API matches case-insensitively."
|
||||
search={
|
||||
<div className="relative w-full">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
placeholder="Search by name, phone number"
|
||||
|
|
@ -417,46 +435,44 @@ export function UsersListPage() {
|
|||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => {
|
||||
setRoleFilter(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="h-9 w-full sm:w-auto appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">All roles</option>
|
||||
<option value="STUDENT">Student</option>
|
||||
<option value="TEACHER">Teacher</option>
|
||||
<option value="ADMIN">Admin</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="h-9 w-full sm:w-auto appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">All statuses</option>
|
||||
<option value="ACTIVE">Active</option>
|
||||
<option value="DEACTIVATED">Deactivated</option>
|
||||
<option value="SUSPENDED">Suspended</option>
|
||||
<option value="PENDING">Pending</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => {
|
||||
setRoleFilter(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="h-9 w-full sm:w-auto appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">All roles</option>
|
||||
<option value="STUDENT">Student</option>
|
||||
<option value="TEACHER">Teacher</option>
|
||||
<option value="ADMIN">Admin</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => {
|
||||
setStatusFilter(e.target.value)
|
||||
setPage(1)
|
||||
}}
|
||||
className="h-9 w-full sm:w-auto appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
|
||||
>
|
||||
<option value="">All statuses</option>
|
||||
<option value="ACTIVE">Active</option>
|
||||
<option value="DEACTIVATED">Deactivated</option>
|
||||
<option value="SUSPENDED">Suspended</option>
|
||||
<option value="PENDING">Pending</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-3 border-t border-grayScale-100 pt-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500">
|
||||
Created on or after
|
||||
|
|
@ -532,20 +548,7 @@ export function UsersListPage() {
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="text-xs text-grayScale-400">
|
||||
Dates are sent as RFC3339 (UTC). Country and region filters use the lists above; the API matches
|
||||
case-insensitively.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearExtraFilters}
|
||||
className="shrink-0 text-sm font-medium text-brand-600 hover:text-brand-700"
|
||||
>
|
||||
Clear date, location & subscription filters
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
{/* Table */}
|
||||
<Table>
|
||||
|
|
@ -642,26 +645,11 @@ export function UsersListPage() {
|
|||
</span>
|
||||
</TableCell>
|
||||
<TableCell onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToggle(u.id)}
|
||||
<ToggleSwitch
|
||||
checked={isActive}
|
||||
disabled={isUpdatingStatus}
|
||||
className={cn(
|
||||
"relative inline-flex h-7 w-12 shrink-0 cursor-pointer items-center rounded-full border p-0.5 transition-all duration-200",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-1",
|
||||
isActive
|
||||
? "border-brand-500 bg-brand-500 shadow-[0_6px_16px_rgba(168,85,247,0.35)]"
|
||||
: "border-grayScale-300 bg-grayScale-200 hover:bg-grayScale-300/80",
|
||||
isUpdatingStatus && "cursor-not-allowed opacity-60",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-md ring-0 transition-transform duration-200 ease-out",
|
||||
isActive ? "translate-x-5" : "translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
onCheckedChange={() => handleToggle(u.id)}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,401 @@
|
|||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BarChart3, CheckCircle2, ChevronDown, ChevronRight, Lock } from "lucide-react";
|
||||
import { Badge } from "../../../components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
||||
import { Select } from "../../../components/ui/select";
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
||||
import { cn } from "../../../lib/utils";
|
||||
import type {
|
||||
LearningActivityAccess,
|
||||
LearningActivityCourse,
|
||||
LearningActivityLesson,
|
||||
LearningActivityModule,
|
||||
LearningActivityProgram,
|
||||
LearningActivityUnit,
|
||||
UserLearningActivityData,
|
||||
} from "../../../types/userAdmin.types";
|
||||
|
||||
type Track = "lms" | "exam_prep";
|
||||
|
||||
function ProgressBar({ access }: { access: LearningActivityAccess }) {
|
||||
const percent = Math.min(100, Math.max(0, access.progress_percent));
|
||||
return (
|
||||
<div className="flex min-w-[120px] items-center gap-2">
|
||||
<div className="h-1.5 flex-1 rounded-full bg-grayScale-200">
|
||||
<div
|
||||
className={cn(
|
||||
"h-1.5 rounded-full transition-all",
|
||||
access.is_completed ? "bg-mint-500" : access.is_accessible ? "bg-brand-500" : "bg-grayScale-300",
|
||||
)}
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="w-8 text-right text-[11px] text-grayScale-500">{percent}%</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AccessStatusBadge({ access }: { access: LearningActivityAccess }) {
|
||||
if (access.is_completed) {
|
||||
return (
|
||||
<Badge className="bg-mint-500/15 text-mint-600 border border-mint-500/25">
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" />
|
||||
Completed
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (!access.is_accessible) {
|
||||
return (
|
||||
<Badge variant="secondary">
|
||||
<Lock className="mr-1 h-3 w-3" />
|
||||
Locked
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return <Badge variant="warning">Accessible</Badge>;
|
||||
}
|
||||
|
||||
function AccessMeta({ access }: { access: LearningActivityAccess }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<AccessStatusBadge access={access} />
|
||||
<span className="text-xs text-grayScale-500">
|
||||
{access.completed_count}/{access.total_count} completed
|
||||
</span>
|
||||
<ProgressBar access={access} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LessonRow({ lesson }: { lesson: LearningActivityLesson }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-grayScale-100 bg-white px-3 py-2.5">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p className="text-sm text-grayScale-700">{lesson.title || `Lesson #${lesson.id}`}</p>
|
||||
<AccessMeta access={lesson.access} />
|
||||
</div>
|
||||
{!lesson.access.is_accessible && lesson.access.reason ? (
|
||||
<p className="mt-1.5 text-xs text-grayScale-400">{lesson.access.reason}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ModuleBlock({ module }: { module: LearningActivityModule }) {
|
||||
const [open, setOpen] = useState(module.access.is_accessible || module.access.is_completed);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-grayScale-100 bg-grayScale-50/60">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-start justify-between gap-3 px-3 py-3 text-left"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-grayScale-800">{module.name || `Module #${module.id}`}</p>
|
||||
<div className="mt-2">
|
||||
<AccessMeta access={module.access} />
|
||||
</div>
|
||||
{!module.access.is_accessible && module.access.reason ? (
|
||||
<p className="mt-1.5 text-xs text-grayScale-400">{module.access.reason}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{open ? (
|
||||
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
) : (
|
||||
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
)}
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="space-y-2 border-t border-grayScale-100 px-3 py-3">
|
||||
{module.lessons.length === 0 ? (
|
||||
<p className="text-xs text-grayScale-400">No lessons in this module.</p>
|
||||
) : (
|
||||
module.lessons.map((lesson) => <LessonRow key={lesson.id} lesson={lesson} />)
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UnitBlock({ unit }: { unit: LearningActivityUnit }) {
|
||||
const [open, setOpen] = useState(unit.access.is_accessible || unit.access.is_completed);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-grayScale-100">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-start justify-between gap-3 px-3 py-3 text-left"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-grayScale-800">{unit.name || `Unit #${unit.id}`}</p>
|
||||
<div className="mt-2">
|
||||
<AccessMeta access={unit.access} />
|
||||
</div>
|
||||
</div>
|
||||
{open ? (
|
||||
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
) : (
|
||||
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
)}
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="space-y-3 border-t border-grayScale-100 px-3 py-3">
|
||||
{unit.modules.length === 0 ? (
|
||||
<p className="text-xs text-grayScale-400">No modules in this unit.</p>
|
||||
) : (
|
||||
unit.modules.map((module) => <ModuleBlock key={module.id} module={module} />)
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CourseBlock({ course, examPrep }: { course: LearningActivityCourse; examPrep?: boolean }) {
|
||||
const [open, setOpen] = useState(course.access.is_accessible || course.access.is_completed);
|
||||
const children = examPrep ? (course.units ?? []) : (course.modules ?? []);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-grayScale-200 bg-white">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-start justify-between gap-3 px-4 py-3 text-left"
|
||||
onClick={() => setOpen((prev) => !prev)}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-semibold text-grayScale-800">{course.name || `Course #${course.id}`}</p>
|
||||
<div className="mt-2">
|
||||
<AccessMeta access={course.access} />
|
||||
</div>
|
||||
{!course.access.is_accessible && course.access.reason ? (
|
||||
<p className="mt-1.5 text-xs text-grayScale-400">{course.access.reason}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{open ? (
|
||||
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
) : (
|
||||
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
)}
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="space-y-3 border-t border-grayScale-100 px-4 py-3">
|
||||
{children.length === 0 ? (
|
||||
<p className="text-xs text-grayScale-400">No content available.</p>
|
||||
) : examPrep ? (
|
||||
(course.units ?? []).map((unit) => <UnitBlock key={unit.id} unit={unit} />)
|
||||
) : (
|
||||
(course.modules ?? []).map((module) => <ModuleBlock key={module.id} module={module} />)
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ label, value }: { label: string; value: string | number }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-grayScale-200 bg-grayScale-50 px-3 py-2">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">{label}</p>
|
||||
<p className="mt-1 text-sm font-semibold text-grayScale-700">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UserLearningActivitySection({
|
||||
activity,
|
||||
loading,
|
||||
error,
|
||||
}: {
|
||||
activity: UserLearningActivityData | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}) {
|
||||
const [track, setTrack] = useState<Track>("lms");
|
||||
const programs = activity?.lms.progress.programs ?? [];
|
||||
const catalogCourses = activity?.exam_prep.progress.catalog_courses ?? [];
|
||||
|
||||
const [selectedProgramId, setSelectedProgramId] = useState<number | null>(null);
|
||||
const [selectedCatalogCourseId, setSelectedCatalogCourseId] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (programs.length === 0) {
|
||||
setSelectedProgramId(null);
|
||||
return;
|
||||
}
|
||||
if (!selectedProgramId || !programs.some((program) => program.id === selectedProgramId)) {
|
||||
setSelectedProgramId(programs[0].id);
|
||||
}
|
||||
}, [programs, selectedProgramId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (catalogCourses.length === 0) {
|
||||
setSelectedCatalogCourseId(null);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!selectedCatalogCourseId ||
|
||||
!catalogCourses.some((course) => course.id === selectedCatalogCourseId)
|
||||
) {
|
||||
setSelectedCatalogCourseId(catalogCourses[0].id);
|
||||
}
|
||||
}, [catalogCourses, selectedCatalogCourseId]);
|
||||
|
||||
const selectedProgram = useMemo(
|
||||
() => programs.find((program) => program.id === selectedProgramId) ?? null,
|
||||
[programs, selectedProgramId],
|
||||
);
|
||||
|
||||
const selectedCatalogCourse = useMemo(
|
||||
() => catalogCourses.find((course) => course.id === selectedCatalogCourseId) ?? null,
|
||||
[catalogCourses, selectedCatalogCourseId],
|
||||
);
|
||||
|
||||
const completedIds = activity?.lms.completed_ids;
|
||||
|
||||
return (
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-100/70">
|
||||
<BarChart3 className="h-4 w-4 text-sky-600" />
|
||||
</div>
|
||||
<CardTitle className="text-base">Learning activity</CardTitle>
|
||||
</div>
|
||||
<div className="flex rounded-lg border border-grayScale-200 p-1">
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||
track === "lms" ? "bg-brand-500 text-white" : "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
onClick={() => setTrack("lms")}
|
||||
>
|
||||
Learn English
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||
track === "exam_prep"
|
||||
? "bg-brand-500 text-white"
|
||||
: "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
onClick={() => setTrack("exam_prep")}
|
||||
>
|
||||
Exam prep
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-100 px-3 py-2 text-xs text-grayScale-500">
|
||||
<SpinnerIcon className="h-3.5 w-3.5" />
|
||||
Loading learning activity...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && activity && track === "lms" ? (
|
||||
<>
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Metric label="Programs" value={programs.length} />
|
||||
<Metric label="Completed programs" value={completedIds?.program_ids.length ?? 0} />
|
||||
<Metric label="Completed courses" value={completedIds?.course_ids.length ?? 0} />
|
||||
<Metric label="Completed lessons" value={completedIds?.lesson_ids.length ?? 0} />
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:max-w-sm">
|
||||
<Select
|
||||
value={selectedProgramId ? String(selectedProgramId) : ""}
|
||||
onChange={(e) => setSelectedProgramId(e.target.value ? Number(e.target.value) : null)}
|
||||
disabled={programs.length === 0}
|
||||
>
|
||||
<option value="">{programs.length === 0 ? "No programs available" : "Select program..."}</option>
|
||||
{programs.map((program: LearningActivityProgram) => (
|
||||
<option key={program.id} value={program.id}>
|
||||
{program.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProgram ? (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-xl border border-brand-100 bg-brand-50/40 px-4 py-3">
|
||||
<p className="text-sm font-semibold text-grayScale-800">{selectedProgram.name}</p>
|
||||
<div className="mt-2">
|
||||
<AccessMeta access={selectedProgram.access} />
|
||||
</div>
|
||||
</div>
|
||||
{selectedProgram.courses.length === 0 ? (
|
||||
<p className="py-6 text-center text-sm text-grayScale-400">No courses in this program.</p>
|
||||
) : (
|
||||
selectedProgram.courses.map((course) => (
|
||||
<CourseBlock key={course.id} course={course} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-grayScale-400">No LMS learning activity yet.</p>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && activity && track === "exam_prep" ? (
|
||||
<>
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Metric label="Exam prep courses" value={catalogCourses.length} />
|
||||
<Metric
|
||||
label="Accessible courses"
|
||||
value={catalogCourses.filter((course) => course.access.is_accessible).length}
|
||||
/>
|
||||
<Metric
|
||||
label="Completed courses"
|
||||
value={catalogCourses.filter((course) => course.access.is_completed).length}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:max-w-sm">
|
||||
<Select
|
||||
value={selectedCatalogCourseId ? String(selectedCatalogCourseId) : ""}
|
||||
onChange={(e) =>
|
||||
setSelectedCatalogCourseId(e.target.value ? Number(e.target.value) : null)
|
||||
}
|
||||
disabled={catalogCourses.length === 0}
|
||||
>
|
||||
<option value="">
|
||||
{catalogCourses.length === 0 ? "No exam prep courses" : "Select exam prep course..."}
|
||||
</option>
|
||||
{catalogCourses.map((course) => (
|
||||
<option key={course.id} value={course.id}>
|
||||
{course.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedCatalogCourse ? (
|
||||
<CourseBlock course={selectedCatalogCourse} examPrep />
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-grayScale-400">No exam prep activity yet.</p>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && !activity ? (
|
||||
<p className="py-6 text-center text-sm text-grayScale-400">No learning activity available.</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,255 @@
|
|||
import { CreditCard, RefreshCw } from "lucide-react";
|
||||
import { Badge } from "../../../components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
|
||||
import { Separator } from "../../../components/ui/separator";
|
||||
import { SpinnerIcon } from "../../../components/ui/spinner-icon";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "../../../components/ui/table";
|
||||
import { cn } from "../../../lib/utils";
|
||||
import type { UserSubscriptionsData } from "../../../types/userAdmin.types";
|
||||
|
||||
function formatStatusLabel(status: string): string {
|
||||
const value = status.trim();
|
||||
if (!value) return "—";
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function formatCategoryLabel(value: string): string {
|
||||
return value
|
||||
.split("_")
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function formatDateTime(value?: string | null): string {
|
||||
if (!value?.trim()) return "—";
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return "—";
|
||||
return parsed.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function getSubscriptionStatusClasses(status: string): string {
|
||||
const normalized = status.trim().toUpperCase();
|
||||
if (normalized === "ACTIVE" || normalized === "SUCCESS") {
|
||||
return "bg-mint-500/15 text-mint-500 border border-mint-500/25";
|
||||
}
|
||||
if (normalized === "PENDING") {
|
||||
return "bg-gold-100 text-gold-600 border border-gold-300/40";
|
||||
}
|
||||
if (normalized === "FAILED" || normalized === "EXPIRED") {
|
||||
return "bg-destructive/15 text-destructive border border-destructive/25";
|
||||
}
|
||||
return "bg-grayScale-100 text-grayScale-600 border border-grayScale-200";
|
||||
}
|
||||
|
||||
function formatDuration(value: number, unit: string): string {
|
||||
if (!value) return "—";
|
||||
const label = unit.trim().toLowerCase();
|
||||
const plural = value === 1 ? label.replace(/s$/, "") : label.endsWith("s") ? label : `${label}s`;
|
||||
return `${value} ${plural}`;
|
||||
}
|
||||
|
||||
function formatMoney(amount: number, currency: string): string {
|
||||
if (!Number.isFinite(amount)) return "—";
|
||||
const code = currency.trim() || "ETB";
|
||||
return `${amount.toLocaleString()} ${code}`;
|
||||
}
|
||||
|
||||
export function UserSubscriptionsSection({
|
||||
subscriptions,
|
||||
loading,
|
||||
error,
|
||||
}: {
|
||||
subscriptions: UserSubscriptionsData | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}) {
|
||||
const recentPayments = subscriptions?.payments.slice(0, 8) ?? [];
|
||||
|
||||
return (
|
||||
<Card className="shadow-soft">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
|
||||
<CreditCard className="h-4 w-4 text-brand-600" />
|
||||
</div>
|
||||
<CardTitle className="text-base">Subscriptions</CardTitle>
|
||||
</div>
|
||||
{subscriptions ? (
|
||||
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
|
||||
{formatStatusLabel(subscriptions.display_status)}
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-grayScale-400">
|
||||
<SpinnerIcon className="h-4 w-4" />
|
||||
Loading subscriptions...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
|
||||
{!loading && !error && subscriptions ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between gap-3 text-sm">
|
||||
<span className="text-grayScale-500">Active subscription</span>
|
||||
<span className="font-medium text-grayScale-700">
|
||||
{subscriptions.has_active_subscription ? "Yes" : "No"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{Object.keys(subscriptions.active_by_category).length > 0 ? (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Access by category
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(subscriptions.active_by_category).map(([category, active]) => (
|
||||
<Badge
|
||||
key={category}
|
||||
variant={active ? "default" : "outline"}
|
||||
className={cn(!active && "text-grayScale-500")}
|
||||
>
|
||||
{formatCategoryLabel(category)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Active plans
|
||||
</p>
|
||||
{subscriptions.active_subscriptions.length === 0 ? (
|
||||
<p className="text-sm text-grayScale-400">No active subscriptions.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{subscriptions.active_subscriptions.map((subscription) => (
|
||||
<div
|
||||
key={subscription.id}
|
||||
className="rounded-xl border border-grayScale-100 bg-grayScale-50/60 p-3"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-800">{subscription.plan_name}</p>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{formatCategoryLabel(subscription.plan_category)}
|
||||
</p>
|
||||
</div>
|
||||
<Badge className={cn(getSubscriptionStatusClasses(subscription.status))}>
|
||||
{formatStatusLabel(subscription.status)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-3 grid gap-2 text-xs text-grayScale-600 sm:grid-cols-2">
|
||||
<p>
|
||||
<span className="text-grayScale-400">Price: </span>
|
||||
{formatMoney(subscription.price, subscription.currency)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Duration: </span>
|
||||
{formatDuration(subscription.duration_value, subscription.duration_unit)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Starts: </span>
|
||||
{formatDateTime(subscription.starts_at)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Expires: </span>
|
||||
{formatDateTime(subscription.expires_at)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-grayScale-400">Payment: </span>
|
||||
{subscription.payment_method || "—"}
|
||||
</p>
|
||||
<p className="inline-flex items-center gap-1">
|
||||
<RefreshCw className="h-3 w-3 text-grayScale-400" />
|
||||
Auto-renew: {subscription.auto_renew ? "On" : "Off"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{recentPayments.length > 0 ? (
|
||||
<>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
|
||||
Recent payments
|
||||
</p>
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Plan</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Method</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{recentPayments.map((payment) => (
|
||||
<TableRow key={payment.id}>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{payment.plan_name || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-grayScale-700">
|
||||
{formatMoney(payment.amount, payment.currency)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge className={cn(getSubscriptionStatusClasses(payment.status))}>
|
||||
{formatStatusLabel(payment.status)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{payment.payment_method || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-grayScale-500">
|
||||
{formatDateTime(payment.paid_at || payment.created_at)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{!loading && !error && !subscriptions ? (
|
||||
<p className="text-sm text-grayScale-400">No subscription data available.</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -1814,6 +1814,14 @@ export interface VimeoSampleVideo {
|
|||
transcode_status: string
|
||||
}
|
||||
|
||||
export interface GetVimeoVideoResponse {
|
||||
message: string
|
||||
data: VimeoSampleVideo
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: unknown
|
||||
}
|
||||
|
||||
export interface GetVimeoSampleResponse {
|
||||
message: string
|
||||
data: {
|
||||
|
|
|
|||
80
src/types/faq.types.ts
Normal file
80
src/types/faq.types.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
export type FAQStatus = "ACTIVE" | "INACTIVE"
|
||||
|
||||
export interface FAQ {
|
||||
id: number
|
||||
question: string
|
||||
answer: string
|
||||
category?: string | null
|
||||
display_order: number
|
||||
status: FAQStatus
|
||||
created_at: string
|
||||
updated_at?: string | null
|
||||
}
|
||||
|
||||
export interface FAQListData {
|
||||
faqs: FAQ[]
|
||||
total_count: number
|
||||
}
|
||||
|
||||
export interface GetFAQsResponse {
|
||||
message: string
|
||||
data: FAQListData
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface GetFAQResponse {
|
||||
message: string
|
||||
data: FAQ
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface CreateFAQRequest {
|
||||
question: string
|
||||
answer: string
|
||||
category?: string | null
|
||||
display_order?: number
|
||||
status?: FAQStatus
|
||||
}
|
||||
|
||||
export interface UpdateFAQRequest {
|
||||
question?: string
|
||||
answer?: string
|
||||
category?: string | null
|
||||
display_order?: number
|
||||
status?: FAQStatus
|
||||
}
|
||||
|
||||
export interface CreateFAQResponse {
|
||||
message: string
|
||||
data: FAQ
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface UpdateFAQResponse {
|
||||
message: string
|
||||
data: FAQ
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface DeleteFAQResponse {
|
||||
message: string
|
||||
data?: { id: number }
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface FAQFilters {
|
||||
status?: FAQStatus
|
||||
category?: string
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
|
@ -1,26 +1,73 @@
|
|||
export interface PersonaListItem {
|
||||
export interface LmsPersona {
|
||||
id: number
|
||||
name: string
|
||||
description: string
|
||||
description: string | null
|
||||
profile_picture: string | null
|
||||
gender: string | null
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface GetPersonasParams {
|
||||
/** @deprecated Use LmsPersona — kept for practice picker compatibility */
|
||||
export type PersonaListItem = LmsPersona
|
||||
|
||||
export interface PersonaListData {
|
||||
personas: LmsPersona[]
|
||||
total_count: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface ListPersonasParams {
|
||||
active_only?: boolean
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface CreatePersonaInput {
|
||||
name: string
|
||||
description?: string | null
|
||||
profile_picture?: string | null
|
||||
gender?: string | null
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface UpdatePersonaInput {
|
||||
name?: string
|
||||
description?: string | null
|
||||
profile_picture?: string | null
|
||||
gender?: string | null
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface GetPersonasResponse {
|
||||
message: string
|
||||
data: {
|
||||
personas: PersonaListItem[]
|
||||
total_count: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: unknown | null
|
||||
data: PersonaListData
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown | null
|
||||
}
|
||||
|
||||
export interface GetPersonaResponse {
|
||||
message: string
|
||||
data: LmsPersona
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
}
|
||||
|
||||
export interface MutatePersonaResponse {
|
||||
message: string
|
||||
data: LmsPersona
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
}
|
||||
|
||||
export interface DeletePersonaResponse {
|
||||
message: string
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
}
|
||||
|
||||
/** @deprecated Use ListPersonasParams */
|
||||
export type GetPersonasParams = ListPersonasParams
|
||||
|
|
|
|||
48
src/types/ratings.types.ts
Normal file
48
src/types/ratings.types.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
export type RatingTargetType = "app" | "course" | "sub_course"
|
||||
|
||||
export interface Rating {
|
||||
id: number
|
||||
user_id: number
|
||||
target_type: RatingTargetType
|
||||
target_id: number
|
||||
stars: number
|
||||
review: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface RatingSummary {
|
||||
total_count: number
|
||||
average_stars: number
|
||||
}
|
||||
|
||||
export interface ListRatingsParams {
|
||||
target_type: RatingTargetType
|
||||
target_id?: number
|
||||
limit?: number
|
||||
offset?: number
|
||||
}
|
||||
|
||||
export interface RatingSummaryParams {
|
||||
target_type: RatingTargetType
|
||||
target_id?: number
|
||||
}
|
||||
|
||||
export interface GetRatingsResponse {
|
||||
message: string
|
||||
data: Rating[]
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
}
|
||||
|
||||
export interface GetRatingSummaryResponse {
|
||||
message: string
|
||||
data: RatingSummary
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
}
|
||||
|
||||
export interface AppReviewsPageData {
|
||||
summary: RatingSummary
|
||||
reviews: Rating[]
|
||||
}
|
||||
|
|
@ -7,16 +7,74 @@ export interface TeamMember {
|
|||
team_role: string
|
||||
department: string
|
||||
job_title: string
|
||||
employment_type: string
|
||||
hire_date: string
|
||||
bio: string
|
||||
employment_type?: string
|
||||
hire_date?: string
|
||||
bio?: string
|
||||
status: string
|
||||
email_verified: boolean
|
||||
permissions: string[]
|
||||
permissions?: string[]
|
||||
last_login?: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/** GET /team/members/:id — single team member detail */
|
||||
export interface TeamMemberDetail {
|
||||
id: number
|
||||
first_name: string
|
||||
last_name: string
|
||||
email: string
|
||||
phone_number: string
|
||||
team_role: string
|
||||
department: string
|
||||
job_title: string
|
||||
bio: string | null
|
||||
status: string
|
||||
email_verified: boolean
|
||||
last_login: string | null
|
||||
created_at: string
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
/** GET /team/me — signed-in team member profile */
|
||||
export interface TeamMeProfile {
|
||||
id: number
|
||||
first_name: string
|
||||
last_name: string
|
||||
email: string
|
||||
phone_number: string
|
||||
team_role: string
|
||||
department: string
|
||||
job_title: string
|
||||
status: string
|
||||
email_verified: boolean
|
||||
last_login: string | null
|
||||
created_at: string
|
||||
updated_at: string | null
|
||||
profile_picture_url?: string | null
|
||||
bio?: string | null
|
||||
work_phone?: string | null
|
||||
}
|
||||
|
||||
export interface GetTeamMeResponse {
|
||||
message: string
|
||||
data: TeamMeProfile
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: unknown | null
|
||||
}
|
||||
|
||||
/** PUT /team/me — update signed-in team member profile */
|
||||
export interface UpdateTeamMeRequest {
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
phone_number?: string
|
||||
department?: string
|
||||
job_title?: string
|
||||
profile_picture_url?: string
|
||||
bio?: string
|
||||
work_phone?: string
|
||||
}
|
||||
|
||||
export interface CreateTeamMemberRequest {
|
||||
first_name: string
|
||||
last_name: string
|
||||
|
|
@ -63,7 +121,7 @@ export interface GetTeamMembersResponse {
|
|||
|
||||
export interface GetTeamMemberResponse {
|
||||
message: string
|
||||
data: TeamMember
|
||||
data: TeamMemberDetail
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: null
|
||||
|
|
|
|||
|
|
@ -81,41 +81,35 @@ export const mapUserApiToUser = (u: UserApiDTO): User => ({
|
|||
createdAt: u.created_at ?? "",
|
||||
})
|
||||
|
||||
/** GET /user/single/:id — single learner profile */
|
||||
export interface UserProfileData {
|
||||
id: number
|
||||
first_name: string
|
||||
last_name: string
|
||||
gender: string
|
||||
birth_day: string | null
|
||||
|
||||
email: string
|
||||
phone_number: string
|
||||
role: string
|
||||
age: number
|
||||
age_group: string
|
||||
education_level: string
|
||||
country: string
|
||||
region: string
|
||||
|
||||
nick_name: string
|
||||
occupation: string
|
||||
learning_goal: string
|
||||
language_goal: string
|
||||
language_challange: string
|
||||
favoutite_topic: string
|
||||
|
||||
email_verified: boolean
|
||||
phone_verified: boolean
|
||||
status: string
|
||||
|
||||
last_login: string | null
|
||||
profile_completed: boolean
|
||||
preferred_language: string
|
||||
profile_completion_percentage: number
|
||||
profile_picture_url: string
|
||||
|
||||
preferred_language: string
|
||||
created_at: string
|
||||
updated_at?: string | null // optional
|
||||
age_group?: string
|
||||
profile_completion_percentage?: number
|
||||
subscription_status: string
|
||||
}
|
||||
|
||||
export interface UserProfileResponse {
|
||||
|
|
@ -139,11 +133,11 @@ export interface UserRecentActivityData {
|
|||
}
|
||||
|
||||
export interface UserRecentActivityResponse {
|
||||
message?: string
|
||||
data?: UserRecentActivityData
|
||||
success?: boolean
|
||||
status_code?: number
|
||||
metadata?: unknown
|
||||
message: string
|
||||
data: UserRecentActivityData
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: null
|
||||
}
|
||||
|
||||
export interface UserSummary {
|
||||
|
|
|
|||
145
src/types/userAdmin.types.ts
Normal file
145
src/types/userAdmin.types.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import type { UserRecentActivityData } from "./user.types"
|
||||
|
||||
/** Shared access/progress block in learning-activity tree nodes */
|
||||
export interface LearningActivityAccess {
|
||||
is_accessible: boolean
|
||||
is_completed: boolean
|
||||
reason?: string
|
||||
completed_count: number
|
||||
total_count: number
|
||||
progress_percent: number
|
||||
progress_percent_precise: number
|
||||
}
|
||||
|
||||
export interface LearningActivityLesson {
|
||||
id: number
|
||||
module_id: number
|
||||
title: string
|
||||
access: LearningActivityAccess
|
||||
}
|
||||
|
||||
export interface LearningActivityModule {
|
||||
id: number
|
||||
program_id?: number
|
||||
course_id?: number
|
||||
unit_id?: number
|
||||
name: string
|
||||
access: LearningActivityAccess
|
||||
lessons: LearningActivityLesson[]
|
||||
}
|
||||
|
||||
export interface LearningActivityUnit {
|
||||
id: number
|
||||
catalog_course_id: number
|
||||
name: string
|
||||
access: LearningActivityAccess
|
||||
modules: LearningActivityModule[]
|
||||
}
|
||||
|
||||
export interface LearningActivityCourse {
|
||||
id: number
|
||||
program_id?: number
|
||||
catalog_course_id?: number
|
||||
name: string
|
||||
access: LearningActivityAccess
|
||||
modules?: LearningActivityModule[]
|
||||
units?: LearningActivityUnit[]
|
||||
}
|
||||
|
||||
export interface LearningActivityProgram {
|
||||
id: number
|
||||
name: string
|
||||
access: LearningActivityAccess
|
||||
courses: LearningActivityCourse[]
|
||||
}
|
||||
|
||||
export interface LearningActivityCompletedIds {
|
||||
lesson_ids: number[]
|
||||
module_ids: number[]
|
||||
course_ids: number[]
|
||||
program_ids: number[]
|
||||
}
|
||||
|
||||
export interface UserLearningActivityData {
|
||||
user_id: number
|
||||
lms: {
|
||||
completed_ids: LearningActivityCompletedIds
|
||||
progress: {
|
||||
programs: LearningActivityProgram[]
|
||||
}
|
||||
completions: {
|
||||
user_id: number
|
||||
programs: unknown[]
|
||||
}
|
||||
}
|
||||
exam_prep: {
|
||||
progress: {
|
||||
catalog_courses: LearningActivityCourse[]
|
||||
}
|
||||
completions: {
|
||||
user_id: number
|
||||
catalog_courses: unknown[]
|
||||
}
|
||||
}
|
||||
recent_activity?: UserRecentActivityData
|
||||
}
|
||||
|
||||
export interface UserLearningActivityResponse {
|
||||
message: string
|
||||
data: UserLearningActivityData
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: null
|
||||
}
|
||||
|
||||
export interface UserSubscriptionRecord {
|
||||
id: number
|
||||
user_id: number
|
||||
plan_id: number
|
||||
plan_name: string
|
||||
plan_category: string
|
||||
starts_at: string
|
||||
expires_at: string
|
||||
status: string
|
||||
payment_reference: string
|
||||
payment_method: string
|
||||
auto_renew: boolean
|
||||
created_at: string
|
||||
duration_value: number
|
||||
duration_unit: string
|
||||
price: number
|
||||
currency: string
|
||||
is_currently_active: boolean
|
||||
}
|
||||
|
||||
export interface UserSubscriptionPayment {
|
||||
id: number
|
||||
plan_id?: number
|
||||
plan_name?: string
|
||||
subscription_id?: number
|
||||
amount: number
|
||||
currency: string
|
||||
payment_method?: string
|
||||
status: string
|
||||
paid_at?: string | null
|
||||
expires_at?: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface UserSubscriptionsData {
|
||||
user_id: number
|
||||
display_status: string
|
||||
has_active_subscription: boolean
|
||||
active_by_category: Record<string, boolean>
|
||||
active_subscriptions: UserSubscriptionRecord[]
|
||||
subscriptions: UserSubscriptionRecord[]
|
||||
payments: UserSubscriptionPayment[]
|
||||
}
|
||||
|
||||
export interface UserSubscriptionsResponse {
|
||||
message: string
|
||||
data: UserSubscriptionsData
|
||||
success: boolean
|
||||
status_code: number
|
||||
metadata: null
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user