diff --git a/src/App.tsx b/src/App.tsx index 1b52c1b..9c036fe 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,6 +2,7 @@ import { useEffect } from 'react' import { Toaster } from 'sonner' import { AppRoutes } from './app/AppRoutes' import { useTheme } from './contexts/ThemeContext' +import { clearTeamSession } from './lib/teamAuthStorage' const SESSION_KEY = 'yimaru_session_active' @@ -27,10 +28,7 @@ function AppToaster() { export default function App() { useEffect(() => { if (!sessionStorage.getItem(SESSION_KEY)) { - localStorage.removeItem('access_token') - localStorage.removeItem('refresh_token') - localStorage.removeItem('member_id') - localStorage.removeItem('role') + clearTeamSession() sessionStorage.setItem(SESSION_KEY, '1') } }, []) diff --git a/src/api/auth.api.ts b/src/api/auth.api.ts index 1b26acd..6b269f6 100644 --- a/src/api/auth.api.ts +++ b/src/api/auth.api.ts @@ -1,5 +1,6 @@ import http from "./http" -import type { LoginRequest, LoginResponse, LoginResponseData } from "../types/auth.types" +import type { LoginRequest, LoginResponse } from "../types/auth.types" +import { TeamAuthError } from "../types/auth.types" export interface LoginResult { accessToken: string @@ -8,11 +9,7 @@ export interface LoginResult { memberId: number } -export const login = async (payload: LoginRequest): Promise => { - const res = await http.post("/team/login", payload) - - const data: LoginResponseData = res.data.data - +function mapLoginResult(data: LoginResponse["data"]): LoginResult { return { accessToken: data.access_token, refreshToken: data.refresh_token, @@ -21,17 +18,22 @@ export const login = async (payload: LoginRequest): Promise => { } } +export const login = async (payload: LoginRequest): Promise => { + const res = await http.post("/team/login", payload) + if (!res.data?.data?.access_token || !res.data?.data?.refresh_token) { + throw new TeamAuthError("Login failed", "Missing tokens in response", res.status) + } + return mapLoginResult(res.data.data) +} + export const loginWithGoogle = async (credential: string): Promise => { const res = await http.post("/team/google-login", { token: credential, }) - - const data: LoginResponseData = res.data.data - - return { - accessToken: data.access_token, - refreshToken: data.refresh_token, - role: data.team_role, - memberId: data.member_id, + if (!res.data?.data?.access_token || !res.data?.data?.refresh_token) { + throw new TeamAuthError("Google sign-in failed", "Missing tokens in response", res.status) } + return mapLoginResult(res.data.data) } + +export { TeamAuthError } from "../types/auth.types" diff --git a/src/api/http.ts b/src/api/http.ts index ff0dcf0..fea7cea 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -1,9 +1,15 @@ import axios, { type AxiosInstance, type AxiosError, type InternalAxiosRequestConfig } from "axios"; +import { teamRefresh } from "./teamRefresh.api"; +import { TeamAuthError } from "../types/auth.types"; +import { + clearTeamSession, + getAccessToken, + getRefreshToken, + saveTeamSession, +} from "../lib/teamAuthStorage"; const http: AxiosInstance = axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL, - // Do not force a Content-Type globally. - // Axios will set the correct header based on the request body (JSON vs multipart FormData). headers: {}, }); @@ -12,7 +18,7 @@ let failedQueue: Array<{ resolve: (token: string) => void; reject: (error: Error) => void; }> = []; -const TOKEN_REFRESH_BUFFER_SECONDS = 120; +const TOKEN_REFRESH_BUFFER_SECONDS = 60; const processQueue = (error: Error | null, token: string | null = null) => { failedQueue.forEach((prom) => { @@ -25,12 +31,10 @@ const processQueue = (error: Error | null, token: string | null = null) => { failedQueue = []; }; -const clearAuthAndRedirect = () => { - localStorage.removeItem("access_token"); - localStorage.removeItem("refresh_token"); - localStorage.removeItem("member_id"); - localStorage.removeItem("role"); - window.location.href = "/login"; +const clearAuthAndRedirect = (reason?: "inactive") => { + clearTeamSession(); + const suffix = reason === "inactive" ? "?account_inactive=1" : ""; + window.location.href = `/login${suffix}`; }; const decodeJwtPayload = (token: string): Record | null => { @@ -86,35 +90,38 @@ const shouldAttachApiAuth = (url?: string): boolean => { return requestOrigin === API_BASE_ORIGIN; }; -const refreshAccessToken = async (): Promise => { - const refreshToken = localStorage.getItem("refresh_token"); +function readErrorMessage(data: unknown): string { + if (typeof data === "string") return data; + if (data && typeof data === "object") { + const record = data as Record; + if (typeof record.error === "string") return record.error; + if (typeof record.message === "string") return record.message; + } + return ""; +} +function isRefreshableAccessTokenError(error: AxiosError): boolean { + if (error.response?.status !== 401) return false; + const message = readErrorMessage(error.response.data).toLowerCase(); + return ( + message.includes("access token expired") || + message.includes("invalid access token") + ); +} + +const refreshAccessToken = async (): Promise => { + const refreshToken = getRefreshToken(); if (!refreshToken) { throw new Error("No refresh token available"); } - const response = await axios.post( - `${import.meta.env.VITE_API_BASE_URL}/team/refresh`, - { - refresh_token: refreshToken, - } - ); - - const newAccessToken = response.data?.data?.access_token; - const newRefreshToken = response.data?.data?.refresh_token; - - if (newAccessToken) { - localStorage.setItem("access_token", newAccessToken); - } - if (newRefreshToken) { - localStorage.setItem("refresh_token", newRefreshToken); - } - - return newAccessToken; + const session = await teamRefresh(refreshToken); + saveTeamSession(session); + return session.access_token; }; const getValidAccessToken = async (forceRefresh = false): Promise => { - const currentToken = localStorage.getItem("access_token"); + const currentToken = getAccessToken(); if (!forceRefresh && currentToken && !isAccessTokenExpiringSoon(currentToken)) { return currentToken; } @@ -128,18 +135,30 @@ const getValidAccessToken = async (forceRefresh = false): Promise => { isRefreshing = true; try { const newToken = await refreshAccessToken(); + if (!newToken) { + throw new Error("Refresh response did not include an access token"); + } processQueue(null, newToken); return newToken; } catch (refreshError) { processQueue(refreshError as Error, null); - clearAuthAndRedirect(); + const status = + refreshError instanceof TeamAuthError + ? refreshError.status + : axios.isAxiosError(refreshError) + ? refreshError.response?.status + : undefined; + if (status === 403) { + clearAuthAndRedirect("inactive"); + } else { + clearAuthAndRedirect(); + } throw refreshError; } finally { isRefreshing = false; } }; -// Attach access token to every request http.interceptors.request.use(async (config) => { if (!shouldAttachApiAuth(config.url)) { return config; @@ -149,7 +168,7 @@ http.interceptors.request.use(async (config) => { return config; } - let token = localStorage.getItem("access_token"); + let token = getAccessToken(); if (token && isAccessTokenExpiringSoon(token)) { token = await getValidAccessToken(); } @@ -160,7 +179,6 @@ http.interceptors.request.use(async (config) => { return config; }); -// Handle 401 globally with token refresh http.interceptors.response.use( (response) => response, async (error: AxiosError) => { @@ -170,7 +188,8 @@ http.interceptors.response.use( error.response?.status === 401 && !originalRequest._retry && shouldAttachApiAuth(originalRequest.url) && - !isAuthEndpointRequest(originalRequest.url) + !isAuthEndpointRequest(originalRequest.url) && + isRefreshableAccessTokenError(error) ) { originalRequest._retry = true; @@ -183,14 +202,8 @@ http.interceptors.response.use( } } - // Backend is down (network error, timeout, connection refused) - if (!error.response && shouldAttachApiAuth(originalRequest.url)) { - clearAuthAndRedirect(); - return Promise.reject(error); - } - return Promise.reject(error); - } + }, ); export default http; diff --git a/src/api/notifications.api.ts b/src/api/notifications.api.ts index 3f07961..3256db3 100644 --- a/src/api/notifications.api.ts +++ b/src/api/notifications.api.ts @@ -3,14 +3,18 @@ import type { BulkInAppRequest, BulkSendResult, BulkSmsRequest, + GetAllNotificationsParams, GetNotificationsResponse, GetScheduledNotificationsParams, + ListAllNotificationsResponse, ListScheduledNotificationsResponse, Notification, ScheduledNotification, UnreadCountResponse, } from "../types/notification.types" +import { isNumericNotificationId } from "../types/notification.types" import { isScheduledNotification, parseBulkResponseData } from "../lib/notificationBulk" +import { DEFAULT_TABLE_PAGE_SIZE } from "../lib/tablePagination" function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value) @@ -24,30 +28,118 @@ function unwrapEnvelopeData(body: unknown): unknown { return body } -function normalizePayload(raw: unknown): Notification["payload"] { - if (!isRecord(raw)) { - return { tags: null } +function pickNotificationText(...values: unknown[]): string | undefined { + for (const value of values) { + if (value != null && String(value).trim()) return String(value) } - const tags = Array.isArray(raw.tags) - ? raw.tags.filter((tag): tag is string => typeof tag === "string" && tag.length > 0) - : null + return undefined +} + +function normalizePayload( + raw: unknown, + fallback?: Record, +): Notification["payload"] { + if (typeof raw === "string") { + const trimmed = raw.trim() + if (trimmed.startsWith("{") || trimmed.startsWith("[")) { + try { + return normalizePayload(JSON.parse(trimmed), fallback) + } catch { + return { tags: null } + } + } + return { message: trimmed, tags: null } + } + + const record = isRecord(raw) ? raw : {} + const content = isRecord(record.content) ? record.content : record + const fb = fallback ?? {} + const fbContent = isRecord(fb.content) ? fb.content : fb + + const tags = Array.isArray(content.tags) + ? content.tags.filter((tag): tag is string => typeof tag === "string" && tag.length > 0) + : Array.isArray(fb.tags) + ? fb.tags.filter((tag): tag is string => typeof tag === "string" && tag.length > 0) + : null + return { - headline: raw.headline != null ? String(raw.headline) : undefined, - title: raw.title != null ? String(raw.title) : undefined, - message: raw.message != null ? String(raw.message) : undefined, - body: raw.body != null ? String(raw.body) : undefined, + headline: pickNotificationText( + content.headline, + content.title, + fb.headline, + fb.title, + fbContent.headline, + fbContent.title, + ), + title: pickNotificationText( + content.title, + content.headline, + fb.title, + fb.headline, + fbContent.title, + fbContent.headline, + ), + message: pickNotificationText( + content.message, + content.body, + content.text, + fb.message, + fb.body, + fb.text, + fbContent.message, + fbContent.body, + fbContent.text, + ), + body: pickNotificationText( + content.body, + content.message, + fb.body, + fb.message, + fbContent.body, + fbContent.message, + ), tags, } } +export function unwrapRealtimeNotification(raw: unknown): unknown { + if (!isRecord(raw)) return raw + + // Already a notification row (list API or inner CREATED_NOTIFICATION payload). + if (raw.id != null || raw.notification_id != null) { + return raw + } + + if ("notification" in raw && isRecord(raw.notification)) { + return raw.notification + } + + const envelopeType = String(raw.type ?? raw.event ?? "") + const isCreatedEvent = + envelopeType === "CREATED_NOTIFICATION" || + envelopeType === "NOTIFICATION_CREATED" || + envelopeType === "notification" + + // Backend WS broadcast: { type: "CREATED_NOTIFICATION", payload: { id, ... } } + if (isCreatedEvent && isRecord(raw.payload)) { + return raw.payload + } + + if (isRecord(raw.data)) { + return raw.data + } + + return raw +} + export function normalizeNotification(raw: unknown): Notification | null { if (!isRecord(raw)) return null - const id = String(raw.id ?? "") + const id = String(raw.id ?? raw.notification_id ?? "") if (!id) return null return { id, - recipient_id: Number(raw.recipient_id ?? 0), + recipient_id: Number(raw.recipient_id ?? raw.user_id ?? 0), receiver_type: raw.receiver_type != null ? String(raw.receiver_type) : undefined, type: String(raw.type ?? ""), level: String(raw.level ?? ""), @@ -56,13 +148,49 @@ export function normalizeNotification(raw: unknown): Notification | null { is_read: Boolean(raw.is_read), delivery_status: String(raw.delivery_status ?? ""), delivery_channel: String(raw.delivery_channel ?? ""), - payload: normalizePayload(raw.payload), - timestamp: String(raw.timestamp ?? ""), + payload: normalizePayload(raw.payload, raw), + timestamp: String(raw.timestamp ?? raw.created_at ?? ""), expires: String(raw.expires ?? ""), image: String(raw.image ?? ""), } } +/** Parse a WebSocket payload into a notification, with fallbacks for partial events. */ +export function parseRealtimeNotification(raw: unknown): Notification | null { + const unwrapped = unwrapRealtimeNotification(raw) + const normalized = normalizeNotification(unwrapped) + if (normalized) return normalized + if (!isRecord(unwrapped)) return null + + const payload = normalizePayload(unwrapped.payload, unwrapped) + const hasContent = Boolean( + payload.title || payload.headline || payload.message || payload.body, + ) + if (!hasContent && unwrapped.id == null && unwrapped.notification_id == null) { + return null + } + + return { + id: String(unwrapped.id ?? unwrapped.notification_id ?? crypto.randomUUID()), + recipient_id: Number(unwrapped.recipient_id ?? 0), + receiver_type: + unwrapped.receiver_type != null ? String(unwrapped.receiver_type) : undefined, + type: String(unwrapped.type ?? ""), + level: String(unwrapped.level ?? ""), + error_severity: String(unwrapped.error_severity ?? ""), + reciever: String(unwrapped.reciever ?? ""), + is_read: Boolean(unwrapped.is_read), + delivery_status: String(unwrapped.delivery_status ?? ""), + delivery_channel: String(unwrapped.delivery_channel ?? "in_app"), + payload, + timestamp: String( + unwrapped.timestamp ?? unwrapped.created_at ?? new Date().toISOString(), + ), + expires: String(unwrapped.expires ?? ""), + image: String(unwrapped.image ?? ""), + } +} + function parseNotificationsListData(body: unknown, limit: number, offset: number): GetNotificationsResponse { const inner = unwrapEnvelopeData(body) if (!isRecord(inner)) { @@ -88,18 +216,87 @@ function parseUnreadCount(body: unknown): UnreadCountResponse { return { unread: Number(inner.unread ?? 0) } } +function extractNotificationsPagePayload(body: unknown): Record | null { + const candidates: unknown[] = [body] + if (isRecord(body)) { + if ("data" in body || "Data" in body) { + candidates.push(body.data ?? body.Data) + } + } + + for (const candidate of candidates) { + if (!isRecord(candidate)) continue + if (Array.isArray(candidate.notifications)) return candidate + if (isRecord(candidate.data) && Array.isArray(candidate.data.notifications)) { + return candidate.data + } + } + + return null +} + +function parseAllNotificationsListData( + body: unknown, + page: number, + limit: number, +): ListAllNotificationsResponse { + const inner = extractNotificationsPagePayload(body) + if (!inner) { + return { notifications: [], total_count: 0, page, limit } + } + + const rows = inner.notifications as unknown[] + const notifications = rows + .map(normalizeNotification) + .filter((n): n is Notification => n !== null) + + return { + notifications, + total_count: Number(inner.total_count ?? notifications.length), + page: Number(inner.page ?? page), + limit: Number(inner.limit ?? limit), + } +} + export const getNotifications = (limit = 10, offset = 0) => http.get("/notifications", { params: { limit, offset } }).then((res) => ({ ...res, data: parseNotificationsListData(res.data, limit, offset), })) +export const getAllNotifications = (params: GetAllNotificationsParams = {}) => { + const page = params.page ?? 1 + const limit = params.limit ?? DEFAULT_TABLE_PAGE_SIZE + const query: Record = { page, limit } + if (params.channel) query.channel = params.channel + if (params.type?.trim()) query.type = params.type.trim() + if (params.user_id != null && Number.isFinite(params.user_id)) query.user_id = params.user_id + if (params.is_read != null) query.is_read = params.is_read + if (params.after) query.after = params.after + if (params.before) query.before = params.before + + return http.get("/notifications/all", { params: query }).then((res) => ({ + ...res, + data: parseAllNotificationsListData(res.data, page, limit), + })) +} + export const getNotificationById = (id: string) => http.get(`/notifications/${id}`).then((res) => ({ ...res, data: normalizeNotification(unwrapEnvelopeData(res.data)), })) +export async function resolveNotificationDetail( + notification: Notification, +): Promise { + if (!isNumericNotificationId(notification.id)) { + return notification + } + const res = await getNotificationById(notification.id) + return res.data ?? notification +} + export const getUnreadCount = () => http.get("/notifications/unread").then((res) => ({ ...res, @@ -197,6 +394,19 @@ function normalizeScheduledNotification(raw: unknown): ScheduledNotification | n ? raw.target_user_ids.map((v) => Number(v)) : undefined, target_role: raw.target_role != null ? String(raw.target_role) : undefined, + target_team_member_ids: Array.isArray(raw.target_team_member_ids) + ? raw.target_team_member_ids.map((v) => Number(v)) + : Array.isArray(raw.target_raw?.team_member_ids) + ? (raw.target_raw as { team_member_ids: unknown[] }).team_member_ids.map((v) => + Number(v), + ) + : undefined, + target_team_role: + raw.target_team_role != null + ? String(raw.target_team_role) + : raw.target_raw?.team_role != null + ? String((raw.target_raw as { team_role: unknown }).team_role) + : undefined, target_raw: isRecord(raw.target_raw) ? { phones: Array.isArray(raw.target_raw.phones) @@ -207,6 +417,11 @@ function normalizeScheduledNotification(raw: unknown): ScheduledNotification | n : undefined, type: raw.target_raw.type != null ? String(raw.target_raw.type) : undefined, level: raw.target_raw.level != null ? String(raw.target_raw.level) : undefined, + team_member_ids: Array.isArray(raw.target_raw.team_member_ids) + ? raw.target_raw.team_member_ids.map((v) => Number(v)) + : undefined, + team_role: + raw.target_raw.team_role != null ? String(raw.target_raw.team_role) : undefined, } : undefined, attempt_count: raw.attempt_count != null ? Number(raw.attempt_count) : undefined, diff --git a/src/api/teamRefresh.api.ts b/src/api/teamRefresh.api.ts new file mode 100644 index 0000000..66b3403 --- /dev/null +++ b/src/api/teamRefresh.api.ts @@ -0,0 +1,48 @@ +import axios from "axios" +import type { + ApiErrorResponse, + LoginResponse, + LoginResponseData, + TeamMemberRefreshRequest, + TeamMemberSession, +} from "../types/auth.types" +import { TeamAuthError } from "../types/auth.types" + +function mapSessionData(data: LoginResponseData): TeamMemberSession { + return { + access_token: data.access_token, + refresh_token: data.refresh_token, + member_id: data.member_id, + team_role: data.team_role, + } +} + +function parseAuthError(body: unknown, status: number): TeamAuthError { + const record = body && typeof body === "object" ? (body as ApiErrorResponse) : null + const message = record?.message || "Authentication failed" + return new TeamAuthError(message, record?.error, status) +} + +/** POST /team/refresh — raw axios only (no http interceptors). */ +export async function teamRefresh(refreshToken: string): Promise { + const payload: TeamMemberRefreshRequest = { refresh_token: refreshToken } + try { + const res = await axios.post( + `${import.meta.env.VITE_API_BASE_URL}/team/refresh`, + payload, + ) + + if (!res.data?.data?.access_token || !res.data?.data?.refresh_token) { + throw parseAuthError(res.data, res.status) + } + + return mapSessionData(res.data.data) + } catch (err) { + if (axios.isAxiosError(err) && err.response) { + throw parseAuthError(err.response.data, err.response.status) + } + throw err + } +} + +export { TeamAuthError } from "../types/auth.types" diff --git a/src/app/AppRoutes.tsx b/src/app/AppRoutes.tsx index 25055b0..5f2fdb1 100644 --- a/src/app/AppRoutes.tsx +++ b/src/app/AppRoutes.tsx @@ -37,6 +37,7 @@ import { NotFoundPage } from "../pages/NotFoundPage"; import { NotificationsPage } from "../pages/notifications/NotificationsPage"; import { CreateNotificationPage } from "../pages/notifications/CreateNotificationPage"; import { ScheduledNotificationsPage } from "../pages/notifications/ScheduledNotificationsPage"; +import { AllNotificationsPage } from "../pages/notifications/AllNotificationsPage"; import { EmailTemplatesPage } from "../pages/notifications/EmailTemplatesPage"; import { EmailTemplateDetailPage } from "../pages/notifications/EmailTemplateDetailPage"; import { CreateEmailTemplatePage } from "../pages/notifications/CreateEmailTemplatePage"; @@ -314,6 +315,7 @@ export function AppRoutes() { path="/notifications/scheduled" element={} /> + } /> } /> } /> } /> diff --git a/src/components/admin/AdminPageHeader.tsx b/src/components/admin/AdminPageHeader.tsx new file mode 100644 index 0000000..f734581 --- /dev/null +++ b/src/components/admin/AdminPageHeader.tsx @@ -0,0 +1,37 @@ +import type { ReactNode } from "react" +import { cn } from "../../lib/utils" + +type AdminPageHeaderProps = { + eyebrow?: string + title: ReactNode + description?: ReactNode + actions?: ReactNode + className?: string +} + +export function AdminPageHeader({ + eyebrow, + title, + description, + actions, + className, +}: AdminPageHeaderProps) { + return ( +
+
+ {eyebrow ? ( +

{eyebrow}

+ ) : null} +
{title}
+ {description ? ( +

{description}

+ ) : null} +
+ {actions ? ( +
+ {actions} +
+ ) : null} +
+ ) +} diff --git a/src/components/admin/AdminTableContainer.tsx b/src/components/admin/AdminTableContainer.tsx new file mode 100644 index 0000000..98d0dc8 --- /dev/null +++ b/src/components/admin/AdminTableContainer.tsx @@ -0,0 +1,22 @@ +import type { ReactNode } from "react" +import { cn } from "../../lib/utils" + +type AdminTableContainerProps = { + children: ReactNode + className?: string + minWidth?: number +} + +export function AdminTableContainer({ + children, + className, + minWidth, +}: AdminTableContainerProps) { + return ( +
+
+ {children} +
+
+ ) +} diff --git a/src/components/admin/TablePagination.tsx b/src/components/admin/TablePagination.tsx new file mode 100644 index 0000000..bb9bac1 --- /dev/null +++ b/src/components/admin/TablePagination.tsx @@ -0,0 +1,130 @@ +import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react" +import { cn } from "../../lib/utils" +import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" + +type TablePaginationProps = { + startEntry: number + endEntry: number + totalCount: number + pageSize: number + onPageSizeChange: (size: number) => void + currentPage: number + totalPages: number + onPageChange: (page: number) => void + disabled?: boolean + className?: string +} + +function getPageNumbers(currentPage: number, totalPages: number): (number | string)[] { + const pages: (number | string)[] = [] + if (totalPages <= 7) { + for (let i = 1; i <= totalPages; i++) pages.push(i) + } else { + pages.push(1, 2, 3) + if (currentPage > 4) pages.push("...") + if (currentPage > 3 && currentPage < totalPages - 2) pages.push(currentPage) + if (currentPage < totalPages - 3) pages.push("...") + pages.push(totalPages) + } + return pages +} + +export function TablePagination({ + startEntry, + endEntry, + totalCount, + pageSize, + onPageSizeChange, + currentPage, + totalPages, + onPageChange, + disabled = false, + className, +}: TablePaginationProps) { + if (totalCount <= 0) return null + + return ( +
+
+ Showing + + {startEntry}-{endEntry} + + of + {totalCount} + entries + Rows per page + · +
+ + +
+
+
+ + {getPageNumbers(currentPage, totalPages).map((n, idx) => + typeof n === "string" ? ( + + ... + + ) : ( + + ), + )} + +
+
+ ) +} diff --git a/src/components/content-management/DynamicSchemaSlotField.tsx b/src/components/content-management/DynamicSchemaSlotField.tsx index 5acd187..319f6d7 100644 --- a/src/components/content-management/DynamicSchemaSlotField.tsx +++ b/src/components/content-management/DynamicSchemaSlotField.tsx @@ -38,6 +38,7 @@ import { DynamicSelectMissingWordsAnswerSlot, DynamicSelectMissingWordsStimulusSlot, } from "./DynamicSelectMissingWordsSlotField" +import { DynamicSequenceOrderSlot } from "./DynamicSequenceOrderSlotField" import { findSelectMissingWordsStimulusInFieldValues, type SelectMissingWordsStimulusValue, @@ -53,6 +54,7 @@ export interface DynamicSchemaSlotRow { kind: string label?: string required?: boolean + config?: Record } function isMultipleChoiceKind(kind: string): boolean { @@ -72,6 +74,10 @@ function isSelectMissingWordsKind(kind: string): boolean { return kind.trim().toUpperCase() === "SELECT_MISSING_WORDS" } +function isSequenceOrderKind(kind: string): boolean { + return kind.trim().toUpperCase() === "SEQUENCE_ORDER" +} + function slotMediaMode( kind: string, side: "stimulus" | "response", @@ -86,7 +92,8 @@ function slotMediaMode( | "matching_inputs" | "matching_answer" | "select_missing_words_stimulus" - | "select_missing_words_answer" { + | "select_missing_words_answer" + | "sequence_order" { const u = kind.trim().toUpperCase() if (u === "IMAGE") return "image" if (u === "TABLE") return "table" @@ -98,6 +105,7 @@ function slotMediaMode( ? "select_missing_words_answer" : "select_missing_words_stimulus" } + if (isSequenceOrderKind(kind)) return "sequence_order" if (u === "PDF_ATTACHMENT" || u === "PDF_UPLOAD") return "pdf" if (u === "PREP_TIME" || u === "ANSWER_TIMER") return "seconds" if (u === "AUDIO_PROMPT" || u === "AUDIO_CLIP" || u === "AUDIO_RESPONSE") return "audio" @@ -953,6 +961,18 @@ export function DynamicSchemaSlotField({ ) } + if (mode === "sequence_order") { + return ( + + ) + } + if (mode === "text") { return (
diff --git a/src/components/content-management/DynamicSelectMissingWordsSlotField.tsx b/src/components/content-management/DynamicSelectMissingWordsSlotField.tsx index c1aac47..52884ae 100644 --- a/src/components/content-management/DynamicSelectMissingWordsSlotField.tsx +++ b/src/components/content-management/DynamicSelectMissingWordsSlotField.tsx @@ -241,8 +241,8 @@ export function DynamicSelectMissingWordsAnswerSlot({ key={`blank-answer-${blank.blank_id}`} className="flex flex-wrap items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-50/50 p-3" > - - {blank.blank_id} + + Blank {blank.blank_id} onTextChange(e.target.value)} + placeholder={`Item ${index + 1}`} + className="h-10 min-w-0 flex-1 rounded-lg border-grayScale-200 bg-white" + disabled={disabled} + /> + +
+ ) +} + +export function DynamicSequenceOrderSlot({ + value, + onChange, + disabled, + slotLabel, + config, +}: { + value: string + onChange: (next: string) => void + disabled: boolean + slotLabel: string + config?: Record +}) { + const parsed = parseSequenceOrderSlotValue(value) + const { minItems, maxItems } = limitsFromSchemaConfig(config) + const canAdd = parsed.items.length < maxItems + const canRemove = parsed.items.length > minItems + + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates, + }), + ) + + const updateValue = (next: SequenceOrderSlotValue) => { + onChange(serializeSequenceOrderSlotValue(next)) + } + + const handleDragEnd = (event: DragEndEvent) => { + const { active, over } = event + if (!over || active.id === over.id) return + const oldIndex = parsed.items.findIndex((item) => item.id === active.id) + const newIndex = parsed.items.findIndex((item) => item.id === over.id) + if (oldIndex < 0 || newIndex < 0) return + const reordered = arrayMove(parsed.items, oldIndex, newIndex) + updateValue({ + items: reordered, + correct_order: reordered.map((item) => item.id), + }) + } + + const sortableIds = parsed.items.map((item) => item.id) + + return ( +
+
+ + +
+ + + +
+ {parsed.items.map((item, index) => ( + + updateValue(updateSequenceOrderItemText(parsed, index, text)) + } + onRemove={() => + updateValue(removeSequenceOrderItem(parsed, index)) + } + /> + ))} +
+
+
+ +

+ Minimum {minItems} items (max {maxItems}). Drag to set the correct order. + Whitespace in text is preserved. +

+
+ ) +} diff --git a/src/components/sidebar/Sidebar.tsx b/src/components/sidebar/Sidebar.tsx index 989e5f5..973a220 100644 --- a/src/components/sidebar/Sidebar.tsx +++ b/src/components/sidebar/Sidebar.tsx @@ -101,6 +101,7 @@ const navEntries: NavEntry[] = [ icon: Bell, children: [ { label: "Inbox", to: "/notifications", end: true }, + { label: "All notifications", to: "/notifications/all" }, { label: "Email templates", to: "/notifications/email-templates" }, { label: "Send notification", to: "/notifications/create" }, { label: "Scheduled", to: "/notifications/scheduled" }, diff --git a/src/components/topbar/NotificationDropdown.tsx b/src/components/topbar/NotificationDropdown.tsx index ce2de19..5a419cf 100644 --- a/src/components/topbar/NotificationDropdown.tsx +++ b/src/components/topbar/NotificationDropdown.tsx @@ -1,29 +1,43 @@ -import { useCallback, useEffect, useRef, useState } from "react" +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react" import { useNavigate } from "react-router-dom" import { Bell, BellOff, CheckCheck, Mail, MailOpen, Trash2 } from "lucide-react" import { toast } from "sonner" import { Badge } from "../ui/badge" import { cn } from "../../lib/utils" import { SpinnerIcon } from "../ui/spinner-icon" -import { getNotificationById } from "../../api/notifications.api" +import { resolveNotificationDetail } 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, NOTIFICATION_TYPE_CONFIG, } from "../../lib/notificationDisplay" -import { getNotificationMessage, getNotificationTitle, type Notification } from "../../types/notification.types" +import { + getNotificationMessage, + getNotificationTitle, + hasNotificationContent, + type Notification, +} from "../../types/notification.types" + +const SLIDE_OUT_MS = 360 +const DELETE_UNDO_MS = 5000 + +type PendingDelete = { + notification: Notification + timeoutId: ReturnType +} function NotificationItem({ notification, + isDismissing, onOpen, onMarkRead, onMarkUnread, onDelete, }: { notification: Notification + isDismissing: boolean onOpen: (notification: Notification) => void onMarkRead: (id: string) => void onMarkUnread: (id: string) => void @@ -31,76 +45,103 @@ function NotificationItem({ }) { const cfg = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG const Icon = cfg.icon + const slideRef = useRef(null) + const [slideOut, setSlideOut] = useState(false) + + useLayoutEffect(() => { + if (!isDismissing) { + setSlideOut(false) + return + } + + const el = slideRef.current + if (!el) return + + setSlideOut(false) + void el.offsetHeight + const frame = requestAnimationFrame(() => setSlideOut(true)) + return () => cancelAnimationFrame(frame) + }, [isDismissing]) return ( - - - + + + + +
+

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

+

+ {getNotificationMessage(notification) || "No preview text available."} +

+

+ {formatNotificationTimestamp(notification.timestamp)} +

+
+ + + + + + ) } @@ -111,7 +152,11 @@ export function NotificationDropdown() { const [detailError, setDetailError] = useState(false) const [selectedNotification, setSelectedNotification] = useState(null) const [selectedNotificationId, setSelectedNotificationId] = useState(null) - const [notificationPendingDelete, setNotificationPendingDelete] = useState(null) + const [dismissingIds, setDismissingIds] = useState>(() => new Set()) + const [hiddenIds, setHiddenIds] = useState>(() => new Set()) + const [pendingDelete, setPendingDelete] = useState(null) + const slideTimersRef = useRef>>(new Map()) + const pendingDeleteRef = useRef(null) const containerRef = useRef(null) const navigate = useNavigate() const { @@ -121,53 +166,139 @@ export function NotificationDropdown() { markOneRead, markOneUnread, markAllAsRead, - refresh, + commitDeleteNotification, } = useNotifications() - const loadNotificationDetail = useCallback(async (id: string, markReadIfNeeded: boolean) => { - setDetailLoading(true) - setDetailError(false) - setSelectedNotification(null) - setSelectedNotificationId(id) - setDetailOpen(true) + const clearPendingDelete = useCallback((restore = false) => { + const current = pendingDeleteRef.current + if (!current) return + clearTimeout(current.timeoutId) + pendingDeleteRef.current = null + setPendingDelete(null) + if (restore) { + setHiddenIds((prev) => { + const next = new Set(prev) + next.delete(current.notification.id) + return next + }) + } + }, []) + const commitPendingDelete = useCallback(async (pending: PendingDelete) => { + if (pendingDeleteRef.current?.timeoutId === pending.timeoutId) { + pendingDeleteRef.current = null + setPendingDelete(null) + } try { - const res = await getNotificationById(id) - if (!res.data) { - setDetailError(true) - toast.error("Notification not found") - return - } - setSelectedNotification(res.data) - if (markReadIfNeeded && !res.data.is_read) { - void markOneRead(id) + await commitDeleteNotification(pending.notification) + setHiddenIds((prev) => { + const next = new Set(prev) + next.delete(pending.notification.id) + return next + }) + if (selectedNotificationId === pending.notification.id) { + setDetailOpen(false) + setSelectedNotification(null) + setSelectedNotificationId(null) } } catch { - setDetailError(true) - toast.error("Failed to load notification details") - } finally { - setDetailLoading(false) + setHiddenIds((prev) => { + const next = new Set(prev) + next.delete(pending.notification.id) + return next + }) + toast.error("Failed to delete notification") } - }, [markOneRead]) + }, [commitDeleteNotification, selectedNotificationId]) + + const flushPendingDelete = useCallback(() => { + const current = pendingDeleteRef.current + if (!current) return + clearTimeout(current.timeoutId) + pendingDeleteRef.current = null + setPendingDelete(null) + void commitPendingDelete(current) + }, [commitPendingDelete]) + + const beginDeleteWithUndo = useCallback( + (notification: Notification) => { + if (dismissingIds.has(notification.id) || hiddenIds.has(notification.id)) return + + flushPendingDelete() + + setDismissingIds((prev) => new Set(prev).add(notification.id)) + + const slideTimer = setTimeout(() => { + slideTimersRef.current.delete(notification.id) + setDismissingIds((prev) => { + const next = new Set(prev) + next.delete(notification.id) + return next + }) + setHiddenIds((prev) => new Set(prev).add(notification.id)) + + const timeoutId = setTimeout(() => { + void commitPendingDelete({ notification, timeoutId }) + }, DELETE_UNDO_MS) + + const pending = { notification, timeoutId } + pendingDeleteRef.current = pending + setPendingDelete(pending) + }, SLIDE_OUT_MS) + + slideTimersRef.current.set(notification.id, slideTimer) + }, + [commitPendingDelete, dismissingIds, flushPendingDelete, hiddenIds], + ) + + const handleUndoDelete = useCallback(() => { + clearPendingDelete(true) + }, [clearPendingDelete]) + + const loadNotificationDetail = useCallback( + async (notification: Notification, markReadIfNeeded: boolean) => { + setDetailLoading(true) + setDetailError(false) + setSelectedNotification(notification) + setSelectedNotificationId(notification.id) + setDetailOpen(true) + + try { + const resolved = await resolveNotificationDetail(notification) + if (!hasNotificationContent(resolved)) { + setDetailError(true) + toast.error("Notification not found") + return + } + setSelectedNotification(resolved) + if (markReadIfNeeded && !resolved.is_read) { + void markOneRead(resolved.id) + } + } catch { + if (hasNotificationContent(notification)) { + setSelectedNotification(notification) + if (markReadIfNeeded && !notification.is_read) { + void markOneRead(notification.id) + } + } else { + setDetailError(true) + toast.error("Failed to load notification details") + } + } finally { + setDetailLoading(false) + } + }, + [markOneRead], + ) const handleOpenNotification = useCallback( (notification: Notification) => { setOpen(false) - void loadNotificationDetail(notification.id, !notification.is_read) + void loadNotificationDetail(notification, !notification.is_read) }, [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)) { @@ -180,6 +311,18 @@ export function NotificationDropdown() { return () => document.removeEventListener("mousedown", handleMouseDown) }, [open]) + useEffect(() => { + return () => { + slideTimersRef.current.forEach((timer) => clearTimeout(timer)) + slideTimersRef.current.clear() + const current = pendingDeleteRef.current + if (current) clearTimeout(current.timeoutId) + pendingDeleteRef.current = null + } + }, []) + + const visibleNotifications = notifications.filter((n) => !hiddenIds.has(n.id)) + return ( <>
@@ -198,7 +341,7 @@ export function NotificationDropdown() { {open && ( -
+

Notifications

@@ -225,30 +368,43 @@ export function NotificationDropdown() {
- ) : notifications.length === 0 ? ( + ) : visibleNotifications.length === 0 && !pendingDelete ? (

No notifications

) : (
- {notifications.map((n) => ( + {visibleNotifications.map((n) => ( { - setOpen(false) - setNotificationPendingDelete(notification) - }} + onDelete={beginDeleteWithUndo} /> ))}
)}
+ {pendingDelete ? ( +
+
+ Notification deleted + +
+
+ ) : null} +
- - {getPageNumbers().map((n, idx) => - typeof n === "string" ? ( - - ... - - ) : ( - - ) - )} - - -
-
+ { + setPageSize(size); + setPage(1); + }} + currentPage={safePage} + totalPages={pageCount} + onPageChange={setPage} + />
{/* Detail Dialog */} @@ -779,7 +698,7 @@ export function IssuesPage() {
{/* Detail grid */} -
+
} label="Reporter" diff --git a/src/pages/notifications/AllNotificationsPage.tsx b/src/pages/notifications/AllNotificationsPage.tsx new file mode 100644 index 0000000..f5f9a82 --- /dev/null +++ b/src/pages/notifications/AllNotificationsPage.tsx @@ -0,0 +1,429 @@ +import { useCallback, useEffect, useMemo, useState } from "react" +import { Link } from "react-router-dom" +import { Bell, List, RefreshCw } from "lucide-react" +import { TablePagination } from "../../components/admin/TablePagination" +import { toast } from "sonner" +import { getAllNotifications, resolveNotificationDetail } from "../../api/notifications.api" +import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel" +import { NotificationDetailDialog } from "../../components/notifications/NotificationDetailDialog" +import { Badge } from "../../components/ui/badge" +import { Button } from "../../components/ui/button" +import { Card, CardContent } from "../../components/ui/card" +import { Input } from "../../components/ui/input" +import { Select } from "../../components/ui/select" +import { SpinnerIcon } from "../../components/ui/spinner-icon" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "../../components/ui/table" +import { countActiveFilters } from "../../lib/adminFilterUtils" +import { channelLabel, IN_APP_TYPES } from "../../lib/notificationBulk" +import { + formatNotificationTimestamp, + formatNotificationTypeLabel, + getNotificationLevelBadge, +} from "../../lib/notificationDisplay" +import { cn } from "../../lib/utils" +import { + DEFAULT_TABLE_PAGE_SIZE, +} from "../../lib/tablePagination" +import { + getNotificationMessage, + getNotificationTitle, + hasNotificationContent, + type Notification, + type NotificationChannel, +} from "../../types/notification.types" + +const CHANNEL_OPTIONS: Array<{ value: "" | NotificationChannel; label: string }> = [ + { value: "", label: "All channels" }, + { value: "email", label: "Email" }, + { value: "sms", label: "SMS" }, + { value: "push", label: "Push" }, + { value: "in_app", label: "In-app" }, +] + +const READ_OPTIONS = [ + { value: "", label: "All read states" }, + { value: "false", label: "Unread only" }, + { value: "true", label: "Read only" }, +] as const + +function toRfc3339FromDatetimeLocal(value: string): string | undefined { + if (!value.trim()) return undefined + const date = new Date(value) + if (Number.isNaN(date.getTime())) return undefined + return date.toISOString() +} + +function recipientLabel(notification: Notification): string { + const parts: string[] = [] + if (notification.recipient_id > 0) { + parts.push(`User #${notification.recipient_id}`) + } + if (notification.receiver_type) { + parts.push(notification.receiver_type) + } + if (notification.reciever) { + parts.push(notification.reciever) + } + return parts.length > 0 ? parts.join(" · ") : "—" +} + +export function AllNotificationsPage() { + const [loading, setLoading] = useState(true) + const [error, setError] = useState(false) + const [rows, setRows] = useState([]) + const [totalCount, setTotalCount] = useState(0) + const [page, setPage] = useState(1) + const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) + + const [channelFilter, setChannelFilter] = useState<"" | NotificationChannel>("") + const [typeFilter, setTypeFilter] = useState("") + const [userIdFilter, setUserIdFilter] = useState("") + const [readFilter, setReadFilter] = useState<"" | "true" | "false">("") + const [afterFilter, setAfterFilter] = useState("") + const [beforeFilter, setBeforeFilter] = useState("") + + const [detailOpen, setDetailOpen] = useState(false) + const [detailLoading, setDetailLoading] = useState(false) + const [detailError, setDetailError] = useState(false) + const [selectedNotification, setSelectedNotification] = useState(null) + + const totalPages = useMemo( + () => Math.max(1, Math.ceil(totalCount / pageSize)), + [totalCount, pageSize], + ) + const currentPage = page + + const parsedUserId = useMemo(() => { + const trimmed = userIdFilter.trim() + if (!trimmed) return undefined + const id = Number(trimmed) + return Number.isFinite(id) && id > 0 ? id : undefined + }, [userIdFilter]) + + const load = useCallback(async () => { + setLoading(true) + setError(false) + try { + const res = await getAllNotifications({ + page, + limit: pageSize, + ...(channelFilter ? { channel: channelFilter } : {}), + ...(typeFilter.trim() ? { type: typeFilter.trim() } : {}), + ...(parsedUserId != null ? { user_id: parsedUserId } : {}), + ...(readFilter === "true" ? { is_read: true } : {}), + ...(readFilter === "false" ? { is_read: false } : {}), + ...(toRfc3339FromDatetimeLocal(afterFilter) + ? { after: toRfc3339FromDatetimeLocal(afterFilter) } + : {}), + ...(toRfc3339FromDatetimeLocal(beforeFilter) + ? { before: toRfc3339FromDatetimeLocal(beforeFilter) } + : {}), + }) + setRows(res.data.notifications) + setTotalCount(res.data.total_count) + } catch { + setError(true) + setRows([]) + setTotalCount(0) + toast.error("Failed to load notifications") + } finally { + setLoading(false) + } + }, [ + page, + pageSize, + channelFilter, + typeFilter, + parsedUserId, + readFilter, + afterFilter, + beforeFilter, + ]) + + useEffect(() => { + void load() + }, [load]) + + useEffect(() => { + setPage(1) + }, [channelFilter, typeFilter, userIdFilter, readFilter, afterFilter, beforeFilter, pageSize]) + + const activeFilterCount = countActiveFilters([ + { value: channelFilter }, + { value: typeFilter }, + { value: userIdFilter }, + { value: readFilter }, + { value: afterFilter }, + { value: beforeFilter }, + ]) + + const clearFilters = () => { + setChannelFilter("") + setTypeFilter("") + setUserIdFilter("") + setReadFilter("") + setAfterFilter("") + setBeforeFilter("") + } + + const openDetail = useCallback(async (notification: Notification) => { + setDetailLoading(true) + setDetailError(false) + setSelectedNotification(notification) + setDetailOpen(true) + + try { + const resolved = await resolveNotificationDetail(notification) + if (!hasNotificationContent(resolved)) { + setDetailError(true) + toast.error("Notification not found") + return + } + setSelectedNotification(resolved) + } catch { + if (hasNotificationContent(notification)) { + setSelectedNotification(notification) + } else { + setDetailError(true) + toast.error("Failed to load notification details") + } + } finally { + setDetailLoading(false) + } + }, []) + + const startEntry = totalCount === 0 ? 0 : (page - 1) * pageSize + 1 + const endEntry = Math.min((page - 1) * pageSize + rows.length, totalCount) + + return ( +
+
+
+

Notifications

+

+ + All notifications +

+

+ Browse every notification sent across the platform. Filter by channel, type, recipient, + read state, or date range. +

+
+
+ + +
+
+ + +
+ + + + + + + setUserIdFilter(e.target.value)} + /> + + setAfterFilter(e.target.value)} + aria-label="Created after" + /> + + setBeforeFilter(e.target.value)} + aria-label="Created before" + /> +
+
+ + + + {loading && ( +
+ + Loading notifications… +
+ )} + + {!loading && error && ( +
+ Could not load notifications. + +
+ )} + + {!loading && !error && rows.length === 0 && ( +
+ +

No notifications found

+

+ Try adjusting your filters or send a notification from the composer. +

+ +
+ )} + + {!loading && !error && rows.length > 0 && ( + <> +
+ + + + Recipient + Title / message + Channel + Type + Level + Read + Delivery + Sent + + + + {rows.map((notification) => ( + void openDetail(notification)} + > + +

{recipientLabel(notification)}

+

+ {notification.id} +

+
+ +

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

+

+ {getNotificationMessage(notification) || "—"} +

+
+ + {channelLabel(notification.delivery_channel) || "—"} + + + {formatNotificationTypeLabel(notification.type)} + + + + {notification.level || "—"} + + + + + {notification.is_read ? "Read" : "Unread"} + + + + {notification.delivery_status || "—"} + + + {formatNotificationTimestamp(notification.timestamp)} + +
+ ))} +
+
+
+ + )} +
+ + {!loading && !error && totalCount > 0 && ( + { + setPageSize(size) + setPage(1) + }} + currentPage={currentPage} + totalPages={totalPages} + onPageChange={setPage} + disabled={loading} + /> + )} +
+ + void openDetail(selectedNotification) + : undefined + } + /> +
+ ) +} diff --git a/src/pages/notifications/CreateNotificationPage.tsx b/src/pages/notifications/CreateNotificationPage.tsx index 0e11395..2258ac6 100644 --- a/src/pages/notifications/CreateNotificationPage.tsx +++ b/src/pages/notifications/CreateNotificationPage.tsx @@ -30,21 +30,31 @@ import { import { extractApiErrorMessage, fetchAllPlatformUsers, + fetchAllTeamMembers, formatScheduledAtLabel, IN_APP_LEVELS, IN_APP_TYPES, + isAudienceModeValidForChannel, parseDirectRecipients, PLATFORM_ROLES, + TEAM_ROLES, + type NotificationAudienceMode, } from "../../lib/notificationBulk" +import { formatTeamRoleLabel } from "../../lib/teamRoles" +import { + BulkSendSummaryPanel, + type BulkSendSummary, +} from "./components/BulkSendSummaryPanel" import type { InAppNotificationLevel, NotificationChannel, PlatformRole, + TeamRole, } from "../../types/notification.types" import type { EmailTemplate } from "../../types/emailTemplate.types" import type { UserApiDTO } from "../../types/user.types" +import type { TeamMember } from "../../types/team.types" -type AudienceMode = "role" | "selected" | "direct" type SendMode = "now" | "schedule" const CHANNELS: { @@ -58,17 +68,75 @@ const CHANNELS: { { value: "in_app", label: "In-app", icon: Smartphone }, ] +function buildAudienceLabel( + audienceMode: NotificationAudienceMode, + platformRole: PlatformRole, + teamRole: TeamRole, + selectedUserIds: number[], + selectedTeamMemberIds: number[], + directRecipients: string, + channel: NotificationChannel, +): string { + if (audienceMode === "platform_role") { + const role = PLATFORM_ROLES.find((r) => r.value === platformRole)?.label ?? platformRole + return `All platform ${role.toLowerCase()}` + } + if (audienceMode === "platform_selected") { + const count = selectedUserIds.length + return `${count} selected platform user${count === 1 ? "" : "s"}` + } + if (audienceMode === "team_role") { + return `All team ${formatTeamRoleLabel(teamRole).toLowerCase()}` + } + if (audienceMode === "team_selected") { + const count = selectedTeamMemberIds.length + return `${count} selected team member${count === 1 ? "" : "s"}` + } + const direct = parseDirectRecipients(directRecipients) + const noun = channel === "sms" ? "phone number" : "email address" + return `${direct.length} direct ${noun}${direct.length === 1 ? "" : "s"}` +} + +function buildContentPreview( + channel: NotificationChannel, + title: string, + message: string, + emailTemplateSlug: string, +): { titlePreview: string; messagePreview: string } { + if (channel === "email" && emailTemplateSlug) { + return { + titlePreview: title.trim() || `Template: ${emailTemplateSlug}`, + messagePreview: message.trim() || `Using template "${emailTemplateSlug}"`, + } + } + if (channel === "sms") { + return { + titlePreview: title.trim() || "SMS", + messagePreview: message.trim(), + } + } + return { + titlePreview: title.trim(), + messagePreview: message.trim(), + } +} + export function CreateNotificationPage() { const navigate = useNavigate() const [channel, setChannel] = useState("push") - const [audienceMode, setAudienceMode] = useState("role") + const [audienceMode, setAudienceMode] = useState("platform_role") const [sendMode, setSendMode] = useState("now") const [platformRole, setPlatformRole] = useState("STUDENT") + const [teamRole, setTeamRole] = useState("ADMIN") const [users, setUsers] = useState([]) + const [teamMembers, setTeamMembers] = useState([]) const [recipientsLoading, setRecipientsLoading] = useState(false) + const [teamRecipientsLoading, setTeamRecipientsLoading] = useState(false) const [selectedUserIds, setSelectedUserIds] = useState([]) + const [selectedTeamMemberIds, setSelectedTeamMemberIds] = useState([]) const [userSearchQuery, setUserSearchQuery] = useState("") + const [teamSearchQuery, setTeamSearchQuery] = useState("") const [directRecipients, setDirectRecipients] = useState("") const [title, setTitle] = useState("") const [message, setMessage] = useState("") @@ -82,6 +150,7 @@ export function CreateNotificationPage() { const [emailTemplateVariables, setEmailTemplateVariables] = useState>({}) const [emailTemplates, setEmailTemplates] = useState([]) const [emailTemplatesLoading, setEmailTemplatesLoading] = useState(false) + const [sendSummary, setSendSummary] = useState(null) useEffect(() => { setRecipientsLoading(true) @@ -91,6 +160,28 @@ export function CreateNotificationPage() { .finally(() => setRecipientsLoading(false)) }, []) + useEffect(() => { + if (channel !== "email" && channel !== "in_app") { + setTeamMembers([]) + return + } + let cancelled = false + setTeamRecipientsLoading(true) + fetchAllTeamMembers() + .then((members) => { + if (!cancelled) setTeamMembers(members) + }) + .catch(() => { + if (!cancelled) setTeamMembers([]) + }) + .finally(() => { + if (!cancelled) setTeamRecipientsLoading(false) + }) + return () => { + cancelled = true + } + }, [channel]) + useEffect(() => { if (channel !== "email") { setEmailTemplateSlug("") @@ -136,6 +227,23 @@ export function CreateNotificationPage() { [filteredUsers, selectedUserIds], ) + const filteredTeamMembers = useMemo(() => { + const q = teamSearchQuery.trim().toLowerCase() + if (!q) return teamMembers + return teamMembers.filter((member) => { + const fullName = `${member.first_name ?? ""} ${member.last_name ?? ""}`.trim().toLowerCase() + const email = (member.email ?? "").toLowerCase() + return fullName.includes(q) || email.includes(q) + }) + }, [teamMembers, teamSearchQuery]) + + const filteredSelectedTeamCount = useMemo( + () => filteredTeamMembers.filter((m) => selectedTeamMemberIds.includes(m.id)).length, + [filteredTeamMembers, selectedTeamMemberIds], + ) + + const supportsTeamTargeting = channel === "email" || channel === "in_app" + const needsTitle = channel === "push" || channel === "in_app" || (channel === "email" && !emailTemplateSlug) const titleLabel = channel === "email" ? "Subject" : channel === "sms" ? "Title (optional)" : "Title" @@ -148,10 +256,13 @@ export function CreateNotificationPage() { setTitle("") setMessage("") setHtmlBody("") - setAudienceMode("role") + setAudienceMode("platform_role") setPlatformRole("STUDENT") + setTeamRole("ADMIN") setSelectedUserIds([]) + setSelectedTeamMemberIds([]) setUserSearchQuery("") + setTeamSearchQuery("") setDirectRecipients("") setScheduledAt("") setAttachment(null) @@ -190,10 +301,17 @@ export function CreateNotificationPage() { ]) const validateTargeting = (): boolean => { - if (audienceMode === "role") return true - if (audienceMode === "selected") { + if (audienceMode === "platform_role" || audienceMode === "team_role") return true + if (audienceMode === "platform_selected") { if (selectedUserIds.length === 0) { - toast.error("Select at least one user") + toast.error("Select at least one platform user") + return false + } + return true + } + if (audienceMode === "team_selected") { + if (selectedTeamMemberIds.length === 0) { + toast.error("Select at least one team member") return false } return true @@ -207,12 +325,18 @@ export function CreateNotificationPage() { } const buildTargeting = () => { - if (audienceMode === "role") { + if (audienceMode === "platform_role") { return { role: platformRole } } - if (audienceMode === "selected") { + if (audienceMode === "platform_selected") { return { user_ids: selectedUserIds } } + if (audienceMode === "team_role") { + return { team_role: teamRole } + } + if (audienceMode === "team_selected") { + return { team_member_ids: selectedTeamMemberIds } + } const direct = parseDirectRecipients(directRecipients) if (channel === "sms") return { phone_numbers: direct } return { emails: direct } @@ -251,6 +375,16 @@ export function CreateNotificationPage() { const targeting = buildTargeting() const schedule = isScheduling && scheduledAt ? { scheduled_at: scheduledAt } : {} + const audienceLabel = buildAudienceLabel( + audienceMode, + platformRole, + teamRole, + selectedUserIds, + selectedTeamMemberIds, + directRecipients, + channel, + ) + const contentPreview = buildContentPreview(channel, title, message, emailTemplateSlug) try { setSending(true) @@ -275,6 +409,10 @@ export function CreateNotificationPage() { if ("user_ids" in targeting) { form.append("user_ids", JSON.stringify(targeting.user_ids)) } + if ("team_role" in targeting) form.append("team_role", targeting.team_role) + if ("team_member_ids" in targeting) { + form.append("team_member_ids", JSON.stringify(targeting.team_member_ids)) + } if ("emails" in targeting) { form.append("emails", JSON.stringify(targeting.emails)) } @@ -303,7 +441,22 @@ export function CreateNotificationPage() { } as Parameters[0]) } + const completedAt = new Date().toISOString() + if (result.kind === "scheduled") { + setSendSummary({ + kind: "scheduled", + channel, + audienceLabel, + titlePreview: contentPreview.titlePreview, + messagePreview: contentPreview.messagePreview, + jobId: result.data.id, + scheduledAt: result.data.scheduled_at, + status: result.data.status, + emailTemplateSlug: result.data.email_template_slug, + completedAt, + apiMessage: result.message || undefined, + }) toast.success("Notification scheduled", { description: `Job #${result.data.id} · ${new Date(result.data.scheduled_at).toLocaleString()}`, action: { @@ -314,9 +467,30 @@ export function CreateNotificationPage() { } else { const { data } = result const total = - data.total_recipients ?? data.target_users ?? data.sent + data.failed + channel === "push" + ? (data.devices_targeted ?? data.target_users ?? data.sent + data.failed) + : (data.total_recipients ?? data.target_users ?? data.sent + data.failed) + setSendSummary({ + kind: "immediate", + channel, + audienceLabel, + titlePreview: contentPreview.titlePreview, + messagePreview: contentPreview.messagePreview, + sent: data.sent, + failed: data.failed, + total, + targetUsers: data.target_users, + devicesTargeted: data.devices_targeted, + pushImage: data.image, + completedAt, + apiMessage: result.message || undefined, + }) + const toastDetail = + channel === "push" + ? `${data.sent} devices sent · ${data.failed} failed · ${data.target_users ?? 0} users` + : `${data.sent} sent · ${data.failed} failed · ${total} recipient${total === 1 ? "" : "s"}` toast.success("Notification sent", { - description: `${data.sent} sent · ${data.failed} failed · ${total} recipient${total === 1 ? "" : "s"}`, + description: toastDetail, }) } @@ -387,6 +561,10 @@ export function CreateNotificationPage() {
+ {sendSummary ? ( + setSendSummary(null)} /> + ) : null} +
{ setChannel(value) - if (value !== "sms" && value !== "email" && audienceMode === "direct") { - setAudienceMode("role") + if (!isAudienceModeValidForChannel(audienceMode, value)) { + setAudienceMode("platform_role") } if (value === "sms") setTitle("") }} @@ -569,6 +747,7 @@ export function CreateNotificationPage() { {channel === "push" ? "Image (push only)" : "Attachment (email only)"}

- + -

Audience

+
+

Platform recipients

+

Learners and platform users

+
{supportsDirect && (
)} -
-
- {audienceMode === "selected" && ( - - -
-

Selected users

- - {selectedUsers.length} selected - -
-
+ {audienceMode === "platform_selected" && ( +
+
+

Select users

+ + {selectedUsers.length} selected + +
+
@@ -810,6 +998,173 @@ export function CreateNotificationPage() { })}
+
+ )} + + + + {supportsTeamTargeting && ( + + +
+

Team recipients

+

Staff and team members

+
+
+ + +
+ + {audienceMode === "team_role" && ( +
+ + +

+ Sends to all staff with this team role. +

+
+ )} + + {audienceMode === "team_selected" && ( +
+
+

Select team members

+ + {selectedTeamMemberIds.length} selected + +
+
+
+
+ + setTeamSearchQuery(e.target.value)} + className="h-8 border-grayScale-200 bg-white pl-8 text-xs" + disabled={teamRecipientsLoading} + /> +
+
+ + · + +
+
+
+ {teamRecipientsLoading && ( +
+ + Loading team members… +
+ )} + {!teamRecipientsLoading && teamMembers.length === 0 && ( +
+ No team members available to select. +
+ )} + {!teamRecipientsLoading && + filteredTeamMembers.map((member) => { + const checked = selectedTeamMemberIds.includes(member.id) + return ( + + ) + })} +
+
+
+ )}
)} diff --git a/src/pages/notifications/NotificationsPage.tsx b/src/pages/notifications/NotificationsPage.tsx index 1ed1fbf..188933a 100644 --- a/src/pages/notifications/NotificationsPage.tsx +++ b/src/pages/notifications/NotificationsPage.tsx @@ -3,8 +3,6 @@ import { Bell, BellOff, AlertTriangle, - ChevronLeft, - ChevronRight, MailOpen, Mail, CheckCheck, @@ -32,13 +30,13 @@ import { cn } from "../../lib/utils" import { SpinnerIcon } from "../../components/ui/spinner-icon" import { useNavigate } from "react-router-dom" import { - getNotificationById, getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, markAllUnread, + resolveNotificationDetail, } from "../../api/notifications.api" import { NotificationDetailDialog } from "../../components/notifications/NotificationDetailDialog" import { NotificationDeleteDialog } from "../../components/notifications/NotificationDeleteDialog" @@ -49,9 +47,11 @@ import { getNotificationLevelBadge, NOTIFICATION_TYPE_CONFIG, } from "../../lib/notificationDisplay" -import { getNotificationMessage, getNotificationTitle, type Notification } from "../../types/notification.types" +import { getNotificationMessage, getNotificationTitle, hasNotificationContent, type Notification } from "../../types/notification.types" +import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket" import { toast } from "sonner" -import { DEFAULT_TABLE_PAGE_SIZE, TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination" +import { TablePagination } from "../../components/admin/TablePagination" +import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination" function NotificationItem({ notification, @@ -224,6 +224,39 @@ export function NotificationsPage() { void fetchData() }, [fetchData]) + useEffect(() => { + const processedRealtimeIds = new Set() + + const onRealtime = (event: Event) => { + const notification = (event as CustomEvent).detail + if (!notification || processedRealtimeIds.has(notification.id)) return + processedRealtimeIds.add(notification.id) + + setNotifications((prev) => { + const withoutDuplicate = prev.filter((n) => n.id !== notification.id) + return [notification, ...withoutDuplicate] + }) + setAllCount((count) => count + 1) + } + + const onNotificationsUpdated = async () => { + try { + const res = await getUnreadCount() + setGlobalUnread(res.data.unread) + } catch { + // silently fail + } + } + + window.addEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime) + window.addEventListener("notifications-updated", onNotificationsUpdated) + + return () => { + window.removeEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime) + window.removeEventListener("notifications-updated", onNotificationsUpdated) + } + }, []) + useEffect(() => { setOffset(0) }, [searchTerm, channelFilter, activeStatusTab, typeFilter, levelFilter, pageSize]) @@ -307,20 +340,6 @@ export function NotificationsPage() { const startEntry = totalCount === 0 ? 0 : offset + 1 const endEntry = Math.min(offset + paginatedNotifications.length, totalCount) - const getPageNumbers = () => { - const pages: (number | string)[] = [] - if (totalPages <= 7) { - for (let i = 1; i <= totalPages; i++) pages.push(i) - } else { - pages.push(1, 2, 3) - if (currentPage > 4) pages.push("...") - if (currentPage > 3 && currentPage < totalPages - 2) pages.push(currentPage) - if (currentPage < totalPages - 3) pages.push("...") - pages.push(totalPages) - } - return pages - } - const activeFilterCount = countActiveFilters([ { value: activeStatusTab, defaultValue: "all" }, { value: channelFilter, defaultValue: "all" }, @@ -335,42 +354,57 @@ export function NotificationsPage() { setLevelFilter("all") } - const loadNotificationDetail = useCallback(async (id: string) => { + const loadNotificationDetail = useCallback(async (notification: Notification) => { setDetailLoading(true) setDetailError(false) - setSelectedNotification(null) - setSelectedNotificationId(id) + setSelectedNotification(notification) + setSelectedNotificationId(notification.id) setDetailOpen(true) try { - const res = await getNotificationById(id) - if (!res.data) { + const resolved = await resolveNotificationDetail(notification) + if (!hasNotificationContent(resolved)) { setDetailError(true) toast.error("Notification not found") return } - setSelectedNotification(res.data) - if (!res.data.is_read) { + setSelectedNotification(resolved) + if (!resolved.is_read) { setNotifications((prev) => - prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)), + prev.map((n) => (n.id === notification.id ? { ...n, is_read: true } : n)), ) setGlobalUnread((prev) => Math.max(0, prev - 1)) try { - await markAsRead(id) + await markAsRead(notification.id) } catch { // list refresh on next load will reconcile } } } catch { - setDetailError(true) - toast.error("Failed to load notification details") + if (hasNotificationContent(notification)) { + setSelectedNotification(notification) + if (!notification.is_read) { + setNotifications((prev) => + prev.map((n) => (n.id === notification.id ? { ...n, is_read: true } : n)), + ) + setGlobalUnread((prev) => Math.max(0, prev - 1)) + try { + await markAsRead(notification.id) + } catch { + // list refresh on next load will reconcile + } + } + } else { + setDetailError(true) + toast.error("Failed to load notification details") + } } finally { setDetailLoading(false) } }, []) const handleOpenDetail = (notification: Notification) => { - void loadNotificationDetail(notification.id) + void loadNotificationDetail(notification) } const handleNotificationDeleted = useCallback((id: string) => { @@ -394,8 +428,8 @@ export function NotificationsPage() { {/* Header */}
Notifications
-
-
+
+

My Notifications

{totalCount > 0 && {totalCount}} {globalUnread > 0 && {globalUnread} unread} @@ -403,7 +437,7 @@ export function NotificationsPage() { {/* Bulk actions */} {!loading && !error && ( -
+
- {getPageNumbers().map((n, idx) => - typeof n === "string" ? ( - - ... - - ) : ( - - ), - )} - -
-
+ { + setPageSize(size) + setOffset(0) + }} + currentPage={currentPage} + totalPages={totalPages} + onPageChange={(page) => setOffset((page - 1) * pageSize)} + /> )} @@ -870,8 +845,8 @@ export function NotificationsPage() { loading={detailLoading} error={detailError} onRetry={ - selectedNotificationId - ? () => void loadNotificationDetail(selectedNotificationId) + selectedNotification + ? () => void loadNotificationDetail(selectedNotification) : undefined } onDelete={ diff --git a/src/pages/notifications/components/BulkSendSummaryPanel.tsx b/src/pages/notifications/components/BulkSendSummaryPanel.tsx new file mode 100644 index 0000000..43f7124 --- /dev/null +++ b/src/pages/notifications/components/BulkSendSummaryPanel.tsx @@ -0,0 +1,290 @@ +import { Link } from "react-router-dom" +import { + CalendarClock, + CheckCircle2, + AlertTriangle, + X, + Users, + Send, + XCircle, + Smartphone, +} from "lucide-react" +import { Badge } from "../../../components/ui/badge" +import { Button } from "../../../components/ui/button" +import { Card, CardContent } from "../../../components/ui/card" +import { channelLabel, formatScheduledAtLabel } from "../../../lib/notificationBulk" +import { cn } from "../../../lib/utils" +import type { NotificationChannel } from "../../../types/notification.types" + +export type BulkSendSummary = + | { + kind: "immediate" + channel: NotificationChannel + audienceLabel: string + titlePreview: string + messagePreview: string + sent: number + failed: number + total: number + targetUsers?: number + devicesTargeted?: number + pushImage?: string + completedAt: string + apiMessage?: string + } + | { + kind: "scheduled" + channel: NotificationChannel + audienceLabel: string + titlePreview: string + messagePreview: string + jobId: number + scheduledAt: string + status?: string + emailTemplateSlug?: string + completedAt: string + apiMessage?: string + } + +interface BulkSendSummaryPanelProps { + summary: BulkSendSummary + onDismiss: () => void +} + +function StatBlock({ + label, + value, + tone = "default", +}: { + label: string + value: number | string + tone?: "default" | "success" | "danger" | "muted" +}) { + const valueClass = + tone === "success" + ? "text-mint-600" + : tone === "danger" + ? "text-destructive" + : tone === "muted" + ? "text-grayScale-500" + : "text-grayScale-800" + + return ( +
+

+ {label} +

+

{value}

+
+ ) +} + +export function BulkSendSummaryPanel({ summary, onDismiss }: BulkSendSummaryPanelProps) { + const isImmediate = summary.kind === "immediate" + const isPush = summary.channel === "push" + const hasFailures = isImmediate && summary.failed > 0 + const allFailed = isImmediate && summary.sent === 0 && summary.failed > 0 + + const borderTone = allFailed + ? "border-destructive/30 bg-destructive/5" + : hasFailures + ? "border-gold-300/60 bg-gold-50/50" + : "border-mint-300/60 bg-mint-50/40" + + const StatusIcon = allFailed ? XCircle : hasFailures ? AlertTriangle : CheckCircle2 + const statusIconClass = allFailed + ? "text-destructive" + : hasFailures + ? "text-gold-600" + : "text-mint-600" + + const headline = isImmediate + ? allFailed + ? "Delivery failed" + : hasFailures + ? "Sent with some failures" + : "Notification sent successfully" + : "Notification scheduled" + + const completedLabel = new Date(summary.completedAt).toLocaleString("en-US", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + const progressTotal = isImmediate ? Math.max(summary.total, 1) : 1 + + return ( + + +
+
+ + + +
+
+

{headline}

+ + {isImmediate ? "Delivered" : "Scheduled"} + + {channelLabel(summary.channel)} + {!isImmediate && summary.status ? ( + {summary.status} + ) : null} +
+

+ {isImmediate + ? `Completed at ${completedLabel}` + : `Scheduled for ${formatScheduledAtLabel(summary.scheduledAt)} · created ${completedLabel}`} +

+ {summary.apiMessage ? ( +

{summary.apiMessage}

+ ) : null} +
+
+ +
+ +
+
+

+ + Audience +

+

{summary.audienceLabel}

+
+
+

+ + Content +

+

+ {summary.titlePreview || "—"} +

+

{summary.messagePreview || "—"}

+ {!isImmediate && summary.emailTemplateSlug ? ( +

+ Template: {summary.emailTemplateSlug} +

+ ) : null} +
+
+ + {isImmediate ? ( + <> + {isPush ? ( +
+ + + + 0 ? "danger" : "muted"} + /> +
+ ) : ( +
+ + + 0 ? "danger" : "muted"} + /> +
+ )} + {summary.total > 0 ? ( +
+
+ {summary.sent > 0 ? ( +
+ ) : null} + {summary.failed > 0 ? ( +
+ ) : null} +
+

+ {isPush + ? `${summary.sent} of ${summary.devicesTargeted ?? summary.total} device deliveries succeeded` + : `${summary.sent} of ${summary.total} delivered`} + {summary.failed > 0 ? ` · ${summary.failed} failed` : ""} +

+
+ ) : null} + {isPush && summary.pushImage ? ( +

+ Image: {summary.pushImage} +

+ ) : null} + {isPush && + (summary.devicesTargeted ?? 0) === 0 && + (summary.targetUsers ?? 0) > 0 ? ( +

+ + Targeted users have no active FCM device tokens. They must register a device + from the learner app while logged in. +

+ ) : null} + + ) : ( +
+ +
+

+ + Scheduled at +

+

+ {formatScheduledAtLabel(summary.scheduledAt)} +

+
+
+ )} + +
+

+ This summary is temporary and clears when you dismiss it or send again. +

+
+ {!isImmediate ? ( + + ) : null} + +
+
+ + + ) +} diff --git a/src/pages/personas/PersonasPage.tsx b/src/pages/personas/PersonasPage.tsx index 1b32877..d5cb211 100644 --- a/src/pages/personas/PersonasPage.tsx +++ b/src/pages/personas/PersonasPage.tsx @@ -251,7 +251,7 @@ export function PersonasPage() { } /> -
+
diff --git a/src/pages/ratings/AppReviewsPage.tsx b/src/pages/ratings/AppReviewsPage.tsx index 08a1c88..314896f 100644 --- a/src/pages/ratings/AppReviewsPage.tsx +++ b/src/pages/ratings/AppReviewsPage.tsx @@ -246,7 +246,7 @@ export function AppReviewsPage() { } /> -
+
diff --git a/src/pages/role-management/RoleManagementLayout.tsx b/src/pages/role-management/RoleManagementLayout.tsx index 152c401..e5658db 100644 --- a/src/pages/role-management/RoleManagementLayout.tsx +++ b/src/pages/role-management/RoleManagementLayout.tsx @@ -2,7 +2,7 @@ import { Outlet } from "react-router-dom" export function RoleManagementLayout() { return ( -
+
Role Management
diff --git a/src/pages/role-management/RolesListPage.tsx b/src/pages/role-management/RolesListPage.tsx index 40a4432..ddcd760 100644 --- a/src/pages/role-management/RolesListPage.tsx +++ b/src/pages/role-management/RolesListPage.tsx @@ -484,7 +484,7 @@ export function RolesListPage() { Invite team members -
+
-
+
@@ -487,7 +487,7 @@ export function TeamManagementPage() { {confirmDialog && (
-
+

Confirm Status Change

diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index 004c315..5e624ab 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -422,7 +422,7 @@ export function UserDetailPage() { -
+
diff --git a/src/pages/user-management/UserManagementLayout.tsx b/src/pages/user-management/UserManagementLayout.tsx index 1160194..f373d8d 100644 --- a/src/pages/user-management/UserManagementLayout.tsx +++ b/src/pages/user-management/UserManagementLayout.tsx @@ -2,7 +2,7 @@ import { Outlet } from "react-router-dom" export function UserManagementLayout() { return ( -
+
) diff --git a/src/pages/user-management/UsersListPage.tsx b/src/pages/user-management/UsersListPage.tsx index 5b481f2..758ebf1 100644 --- a/src/pages/user-management/UsersListPage.tsx +++ b/src/pages/user-management/UsersListPage.tsx @@ -419,7 +419,7 @@ export function UsersListPage() {
-
+
-
+

Confirm Status Change