diff --git a/package-lock.json b/package-lock.json index bc82fa9..69fe4a9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 8cfbe32..e37556c 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/api/courses.api.ts b/src/api/courses.api.ts index 0c58c59..9fa1620 100644 --- a/src/api/courses.api.ts +++ b/src/api/courses.api.ts @@ -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("/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("/vimeo/sample", { params: { video_id: videoId, width, height }, }) + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value) +} + +function readString(raw: Record, ...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 { + const res = await http.get( + `/vimeo/videos/${encodeURIComponent(videoId.trim())}`, + ) + return normalizeVimeoVideoDetails(res.data.data) +} diff --git a/src/api/faq.api.ts b/src/api/faq.api.ts new file mode 100644 index 0000000..4206489 --- /dev/null +++ b/src/api/faq.api.ts @@ -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 { + 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 { + const params: Record = {} + 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("/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(`/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("/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(`/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(`/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(`/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 = {}) => + http + .get("/faqs", { params: buildFAQQuery(filters) }) + .then((res) => { + const parsed = parseFAQsList(res.data) + return { + ...res, + data: parsed, + message: isRecord(res.data) ? String(res.data.message ?? "") : undefined, + } + }) diff --git a/src/api/notifications.api.ts b/src/api/notifications.api.ts index 6b0074c..ecce8ff 100644 --- a/src/api/notifications.api.ts +++ b/src/api/notifications.api.ts @@ -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(`/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 } diff --git a/src/api/personas.api.ts b/src/api/personas.api.ts index b356c20..1a78257 100644 --- a/src/api/personas.api.ts +++ b/src/api/personas.api.ts @@ -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("/personas", { params }) +function isRecord(value: unknown): value is Record { + 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 { + 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("/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("/personas", { params: buildPersonasQuery(params ?? {}) }) + +/** GET /personas/:id */ +export function getPersonaById(id: number) { + return http.get(`/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("/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(`/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(`/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 { + const res = await listPersonas({ active_only: true, limit, offset: 0 }) + return res.data.personas +} diff --git a/src/api/ratings.api.ts b/src/api/ratings.api.ts new file mode 100644 index 0000000..0fe99b2 --- /dev/null +++ b/src/api/ratings.api.ts @@ -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 { + 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 { + 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("/ratings/summary", { + params: { target_type: params.target_type, target_id: targetId }, + }) + .then((res) => parseRatingSummary(res.data)) +} + +export function listRatingsByTarget(params: ListRatingsParams) { + return http + .get("/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 { + 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, + }, + })) +} diff --git a/src/api/rbac.api.ts b/src/api/rbac.api.ts index 832f14b..2fc88ef 100644 --- a/src/api/rbac.api.ts +++ b/src/api/rbac.api.ts @@ -30,6 +30,10 @@ export const setRolePermissions = (roleId: number, data: SetRolePermissionsReque export const getAllPermissions = () => http.get("/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(`/rbac/roles/${roleId}`) diff --git a/src/api/team.api.ts b/src/api/team.api.ts index 93a9d31..2bae36d 100644 --- a/src/api/team.api.ts +++ b/src/api/team.api.ts @@ -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 { + 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("/team/members", { params: { @@ -24,7 +91,27 @@ export const getTeamMembers = (page?: number, pageSize?: number) => }) export const getTeamMemberById = (id: number) => - http.get(`/team/members/${id}`) + http.get(`/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("/team/me") + +/** PUT /team/me — update signed-in team member profile */ +export const updateTeamMe = (data: UpdateTeamMeRequest) => + http.put("/team/me", data) export const createTeamMember = (data: CreateTeamMemberRequest) => http.post("/team/register", data) diff --git a/src/api/users.api.ts b/src/api/users.api.ts index 691bf61..3fc3aab 100644 --- a/src/api/users.api.ts +++ b/src/api/users.api.ts @@ -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 { + 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 = {}; + 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(`/user/single/${id}`); + http.get(`/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(`/admin/users/${userId}/recent-activity`); + http.get(`/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(`/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(`/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("/team/me"); + http.get("/team/me"); // Best-guess API for creating a new user (admin-side). // Adjust payload shape or endpoint if backend differs. diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index 5aee9fb..ba80b5b 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -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() { } /> } /> } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> diff --git a/src/components/filters/AdminFiltersPanel.tsx b/src/components/filters/AdminFiltersPanel.tsx new file mode 100644 index 0000000..7174e9f --- /dev/null +++ b/src/components/filters/AdminFiltersPanel.tsx @@ -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 ( +
+
+ {search ?
{search}
: null} + {inlineActions ? ( +
{actions}
+ ) : ( + + )} + {activeFilterCount > 0 && onClearFilters ? ( + + ) : null} + {summary ?
{summary}
: null} +
+ {inlineActions ? ( + footer ? ( +
+ {footer} +
+ ) : null + ) : open ? ( +
+ {children} + {footer ?
{footer}
: null} +
+ ) : null} +
+ ) +} diff --git a/src/components/notifications/NotificationDeleteDialog.tsx b/src/components/notifications/NotificationDeleteDialog.tsx new file mode 100644 index 0000000..034cade --- /dev/null +++ b/src/components/notifications/NotificationDeleteDialog.tsx @@ -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 ( + + + + + + Delete notification? + + + This permanently removes the notification from your inbox. + + + {notification ? ( +
+

+ {getNotificationTitle(notification) || "Notification"} +

+

#{notification.id}

+
+ ) : null} + + + + +
+
+ ) +} diff --git a/src/components/notifications/NotificationDetailDialog.tsx b/src/components/notifications/NotificationDetailDialog.tsx index 5b36fd7..8f33e22 100644 --- a/src/components/notifications/NotificationDetailDialog.tsx +++ b/src/components/notifications/NotificationDetailDialog.tsx @@ -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({ ) : null} + + {onDelete ? ( + + + + ) : null} ) : null} diff --git a/src/components/profile/ProfileAvatarUpload.tsx b/src/components/profile/ProfileAvatarUpload.tsx new file mode 100644 index 0000000..f35691e --- /dev/null +++ b/src/components/profile/ProfileAvatarUpload.tsx @@ -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(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) => { + const file = e.target.files?.[0] + e.target.value = "" + if (file) void processFile(file) + } + + const trimmedUrl = avatarUrl?.trim() + + return ( + <> + + + + ) +} diff --git a/src/components/sidebar/Sidebar.tsx b/src/components/sidebar/Sidebar.tsx index 781e2d0..c36ba88 100644 --- a/src/components/sidebar/Sidebar.tsx +++ b/src/components/sidebar/Sidebar.tsx @@ -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 ( diff --git a/src/components/topbar/NotificationDropdown.tsx b/src/components/topbar/NotificationDropdown.tsx index 7a3cadf..ce2de19 100644 --- a/src/components/topbar/NotificationDropdown.tsx +++ b/src/components/topbar/NotificationDropdown.tsx @@ -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({ )} + ) } @@ -97,6 +111,7 @@ export function NotificationDropdown() { const [detailError, setDetailError] = useState(false) const [selectedNotification, setSelectedNotification] = useState(null) const [selectedNotificationId, setSelectedNotificationId] = useState(null) + const [notificationPendingDelete, setNotificationPendingDelete] = useState(null) const containerRef = useRef(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) + }} /> ))} @@ -246,6 +276,20 @@ export function NotificationDropdown() { ? () => void loadNotificationDetail(selectedNotificationId, false) : undefined } + onDelete={ + selectedNotification + ? () => setNotificationPendingDelete(selectedNotification) + : undefined + } + /> + + { + if (!open) setNotificationPendingDelete(null) + }} + onDeleted={handleNotificationDeleted} /> ) diff --git a/src/components/ui/toggle-switch.tsx b/src/components/ui/toggle-switch.tsx new file mode 100644 index 0000000..17a2961 --- /dev/null +++ b/src/components/ui/toggle-switch.tsx @@ -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 ( + + ) +} diff --git a/src/hooks/useActivePersonas.ts b/src/hooks/useActivePersonas.ts index 2893e43..b7db317 100644 --- a/src/hooks/useActivePersonas.ts +++ b/src/hooks/useActivePersonas.ts @@ -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([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(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() diff --git a/src/hooks/useFaqPermissions.ts b/src/hooks/useFaqPermissions.ts new file mode 100644 index 0000000..2b6b9d9 --- /dev/null +++ b/src/hooks/useFaqPermissions.ts @@ -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, + } +} diff --git a/src/hooks/useNotifications.ts b/src/hooks/useNotifications.ts index e0b42d6..f8044b4 100644 --- a/src/hooks/useNotifications.ts +++ b/src/hooks/useNotifications.ts @@ -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, } } diff --git a/src/hooks/usePersonaPermissions.ts b/src/hooks/usePersonaPermissions.ts new file mode 100644 index 0000000..2a13214 --- /dev/null +++ b/src/hooks/usePersonaPermissions.ts @@ -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, + } +} diff --git a/src/hooks/useRatingsPermissions.ts b/src/hooks/useRatingsPermissions.ts new file mode 100644 index 0000000..7f983d7 --- /dev/null +++ b/src/hooks/useRatingsPermissions.ts @@ -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, + } +} diff --git a/src/hooks/useTeamPermissions.ts b/src/hooks/useTeamPermissions.ts new file mode 100644 index 0000000..a387e8a --- /dev/null +++ b/src/hooks/useTeamPermissions.ts @@ -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([]) + 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 } +} diff --git a/src/lib/activityLogActor.ts b/src/lib/activityLogActor.ts index 837d2e0..fabf1b9 100644 --- a/src/lib/activityLogActor.ts +++ b/src/lib/activityLogActor.ts @@ -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, diff --git a/src/lib/adminFilterUtils.ts b/src/lib/adminFilterUtils.ts new file mode 100644 index 0000000..43e4278 --- /dev/null +++ b/src/lib/adminFilterUtils.ts @@ -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 +} diff --git a/src/lib/faqDisplay.ts b/src/lib/faqDisplay.ts new file mode 100644 index 0000000..6bed16c --- /dev/null +++ b/src/lib/faqDisplay.ts @@ -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 +} diff --git a/src/lib/faqErrors.ts b/src/lib/faqErrors.ts new file mode 100644 index 0000000..dd2fe72 --- /dev/null +++ b/src/lib/faqErrors.ts @@ -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" diff --git a/src/lib/faqPermissions.ts b/src/lib/faqPermissions.ts new file mode 100644 index 0000000..73076f2 --- /dev/null +++ b/src/lib/faqPermissions.ts @@ -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) +} diff --git a/src/lib/personaDisplay.ts b/src/lib/personaDisplay.ts index be0ca8e..449fb0c 100644 --- a/src/lib/personaDisplay.ts +++ b/src/lib/personaDisplay.ts @@ -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[] { diff --git a/src/lib/personasErrors.ts b/src/lib/personasErrors.ts new file mode 100644 index 0000000..bb835d5 --- /dev/null +++ b/src/lib/personasErrors.ts @@ -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" diff --git a/src/lib/personasPermissions.ts b/src/lib/personasPermissions.ts new file mode 100644 index 0000000..48cda49 --- /dev/null +++ b/src/lib/personasPermissions.ts @@ -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) +} diff --git a/src/lib/ratingUserCache.ts b/src/lib/ratingUserCache.ts new file mode 100644 index 0000000..1999818 --- /dev/null +++ b/src/lib/ratingUserCache.ts @@ -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() + +export async function fetchReviewerProfile(userId: number): Promise { + 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> { + const unique = Array.from(new Set(userIds.filter((id) => Number.isFinite(id)))) + const result = new Map() + + 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() +} diff --git a/src/lib/ratingsDisplay.ts b/src/lib/ratingsDisplay.ts new file mode 100644 index 0000000..f2fa85f --- /dev/null +++ b/src/lib/ratingsDisplay.ts @@ -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" +} diff --git a/src/lib/ratingsErrors.ts b/src/lib/ratingsErrors.ts new file mode 100644 index 0000000..2f19719 --- /dev/null +++ b/src/lib/ratingsErrors.ts @@ -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" diff --git a/src/lib/ratingsPermissions.ts b/src/lib/ratingsPermissions.ts new file mode 100644 index 0000000..47f119d --- /dev/null +++ b/src/lib/ratingsPermissions.ts @@ -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) +} diff --git a/src/lib/videoPreview.ts b/src/lib/videoPreview.ts index 086ea63..edddaf7 100644 --- a/src/lib/videoPreview.ts +++ b/src/lib/videoPreview.ts @@ -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 // instead of ?h=. 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()); diff --git a/src/lib/vimeoVideoCache.ts b/src/lib/vimeoVideoCache.ts new file mode 100644 index 0000000..4333c2d --- /dev/null +++ b/src/lib/vimeoVideoCache.ts @@ -0,0 +1,38 @@ +import { getVimeoVideo } from "../api/courses.api" + +const durationCache = new Map() +const inflight = new Map>() + +export function fetchVimeoDurationSeconds(vimeoId: string): Promise { + 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 +} diff --git a/src/pages/DashboardPage.tsx b/src/pages/DashboardPage.tsx index a45f74a..de7349c 100644 --- a/src/pages/DashboardPage.tsx +++ b/src/pages/DashboardPage.tsx @@ -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([]) + const [appRatingsSummary, setAppRatingsSummary] = useState({ + total_count: 0, + average_stars: 0, + }) const [appRatingsLoading, setAppRatingsLoading] = useState(true) const [filters, setFilters] = useState(DEFAULT_FILTERS) const [subscriptionPlans, setSubscriptionPlans] = useState([]) @@ -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 */} -
- - Recent App Reviews +
+
+ + Recent App Reviews +
+ + View all +
@@ -506,7 +524,7 @@ export function DashboardPage() {
- ) : appRatings.length === 0 ? ( + ) : appRatingsSummary.total_count === 0 ? (
No app reviews yet
@@ -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() { ))}
- {(appRatings.reduce((sum, r) => sum + r.stars, 0) / appRatings.length).toFixed(1)} + {formatAverageStars(appRatingsSummary.average_stars)} - ({appRatings.length} {appRatings.length === 1 ? "review" : "reviews"}) + ({appRatingsSummary.total_count}{" "} + {appRatingsSummary.total_count === 1 ? "review" : "reviews"}) diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx index e651a10..9fb9059 100644 --- a/src/pages/ProfilePage.tsx +++ b/src/pages/ProfilePage.tsx @@ -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 ( +
+

{label}

+

{value}

+
+ ) } function LoadingSkeleton() { return ( -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {[1, 2, 3].map((i) => ( -
-
-
- {[1, 2, 3, 4].map((j) => ( -
-
-
-
- ))} -
-
- ))} -
+
+
+
+
+ {[1, 2].map((item) => ( +
+ ))}
- ); + ) +} + +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(null); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [editing, setEditing] = useState(false); - const [saving, setSaving] = useState(false); - const [profilePictureFile, setProfilePictureFile] = useState(null); - const [editForm, setEditForm] = useState({ + const [profile, setProfile] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const [editing, setEditing] = useState(false) + const [saving, setSaving] = useState(false) + const [uploadingPicture, setUploadingPicture] = useState(false) + const [editForm, setEditForm] = useState({ 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 ; + if (loading) return if (error || !profile) { return ( -
+
-

+

{error || "Profile not available"}

-

+

Please check your connection and try again.

+ +
+
+
+ ) + } + + 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 ( +
+
+
+

Account

+

My profile

+

+ Your team account details from the admin directory. +

+
+ +
+ + +
+ +
+
+ +
+

{fullName}

+

{displayValue(profile.job_title)}

+
+
+
+ + {formatStatusLabel(profile.status)} + + + {profile.email_verified ? "Email verified" : "Email not verified"} + +
+
+ {profile.bio?.trim() ? ( +

{profile.bio.trim()}

+ ) : null} +
+ + +
+ + + Work details + + + + + + + + + + + + Contact + + +
+ + {displayValue(profile.email)} +
+
+ + {displayValue(profile.phone_number)} +
+ {profile.work_phone?.trim() ? ( +
+ + + Work: + {profile.work_phone.trim()} + +
+ ) : null} +
+
+ + + + Account activity + + +
+ + +
+
+ + +
+
+ + +
+
+ + +
- ); - } - const fullName = `${profile.first_name} ${profile.last_name}`; - const initials = `${profile.first_name?.[0] ?? ""}${profile.last_name?.[0] ?? ""}`.toUpperCase(); - - return ( -
-
-
- -
- - -
-
- - -
-

Summary

- -
-
-
{profile.job_title || "Role-focused work item"}
-
{profile.team_role || "Team responsibility"}
-
{profile.email}
-
{profile.phone_number || "No phone number"}
-
-
-
- - - -

Employment

-
-

{profile.department || "Department not set"}

-

Employment type: {profile.employment_type || "—"}

-
-
-
- - - -

More about me

-
- Status {profile.status} - Email {profile.email_verified ? "verified" : "not verified"} - Joined {formatDate(profile.created_at)} - Last login {formatDateTime(profile.last_login)} -
-
-
- - - -
-

First Name

-

{profile.first_name}

-
-
-

Last Name

-

{profile.last_name}

-
-
-

Department

-

{profile.department || "—"}

-
-
-

Team Role

-

{profile.team_role || "—"}

-
-
-

Job Title

-

{profile.job_title || "—"}

-
-
-

Hire Date

-

{formatDate(profile.hire_date) || "—"}

-
-
-

Phone Number

-

{profile.phone_number || "—"}

-
-
-
-
-
-
-
- !saving && setEditing(open)}> - + !busy && setEditing(open)}> + - Edit profile + Edit profile -
-
-

First Name

- updateField("first_name", e.target.value)} /> +
+
+ + + setEditForm((prev) => ({ ...prev, first_name: e.target.value })) + } + />
-
-

Last Name

- updateField("last_name", e.target.value)} /> +
+ + + setEditForm((prev) => ({ ...prev, last_name: e.target.value })) + } + />
-
-

Phone Number

- updateField("phone_number", e.target.value)} /> +
+ + + setEditForm((prev) => ({ ...prev, phone_number: e.target.value })) + } + />
-
-

Profile Picture

-
- - updateField("profile_picture_url", e.target.value)} - placeholder="Or paste image URL (https://...)" - /> -
+
+ + + setEditForm((prev) => ({ ...prev, work_phone: e.target.value })) + } + />
-
-

Bio

+
+ + + setEditForm((prev) => ({ ...prev, department: e.target.value })) + } + /> +
+
+ + + setEditForm((prev) => ({ ...prev, job_title: e.target.value })) + } + /> +
+
+ + +

Email is managed by your administrator.

+
+
+ + + setEditForm((prev) => ({ ...prev, profile_picture_url })) + } + /> +
+
+