Improve notifications delivery and admin UX with realtime inbox, platform-wide browsing, and mobile-responsive layouts.
Restore WebSocket in-app delivery, fix inbox preview/detail handling, add Gmail-style delete undo, an all-notifications admin page with filters, notification composer audience split, shared table pagination, and responsive table/grid fixes across admin pages. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
53cdb5060a
commit
076edee45d
|
|
@ -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')
|
||||
}
|
||||
}, [])
|
||||
|
|
|
|||
|
|
@ -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<LoginResult> => {
|
||||
const res = await http.post<LoginResponse>("/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<LoginResult> => {
|
|||
}
|
||||
}
|
||||
|
||||
export const login = async (payload: LoginRequest): Promise<LoginResult> => {
|
||||
const res = await http.post<LoginResponse>("/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<LoginResult> => {
|
||||
const res = await http.post<LoginResponse>("/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"
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> | null => {
|
||||
|
|
@ -86,35 +90,38 @@ const shouldAttachApiAuth = (url?: string): boolean => {
|
|||
return requestOrigin === API_BASE_ORIGIN;
|
||||
};
|
||||
|
||||
const refreshAccessToken = async (): Promise<string> => {
|
||||
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<string, unknown>;
|
||||
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<string> => {
|
||||
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<string> => {
|
||||
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<string> => {
|
|||
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;
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> {
|
||||
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<string, unknown>,
|
||||
): 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<string, unknown> | 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<unknown>("/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<string, string | number | boolean> = { 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<unknown>("/notifications/all", { params: query }).then((res) => ({
|
||||
...res,
|
||||
data: parseAllNotificationsListData(res.data, page, limit),
|
||||
}))
|
||||
}
|
||||
|
||||
export const getNotificationById = (id: string) =>
|
||||
http.get<unknown>(`/notifications/${id}`).then((res) => ({
|
||||
...res,
|
||||
data: normalizeNotification(unwrapEnvelopeData(res.data)),
|
||||
}))
|
||||
|
||||
export async function resolveNotificationDetail(
|
||||
notification: Notification,
|
||||
): Promise<Notification> {
|
||||
if (!isNumericNotificationId(notification.id)) {
|
||||
return notification
|
||||
}
|
||||
const res = await getNotificationById(notification.id)
|
||||
return res.data ?? notification
|
||||
}
|
||||
|
||||
export const getUnreadCount = () =>
|
||||
http.get<unknown>("/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,
|
||||
|
|
|
|||
48
src/api/teamRefresh.api.ts
Normal file
48
src/api/teamRefresh.api.ts
Normal file
|
|
@ -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<TeamMemberSession> {
|
||||
const payload: TeamMemberRefreshRequest = { refresh_token: refreshToken }
|
||||
try {
|
||||
const res = await axios.post<LoginResponse>(
|
||||
`${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"
|
||||
|
|
@ -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={<ScheduledNotificationsPage />}
|
||||
/>
|
||||
<Route path="/notifications/all" element={<AllNotificationsPage />} />
|
||||
<Route path="/payments" element={<PaymentsPage />} />
|
||||
<Route path="/user-log" element={<UserLogPage />} />
|
||||
<Route path="/issues" element={<IssuesPage />} />
|
||||
|
|
|
|||
37
src/components/admin/AdminPageHeader.tsx
Normal file
37
src/components/admin/AdminPageHeader.tsx
Normal file
|
|
@ -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 (
|
||||
<div className={cn("flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between", className)}>
|
||||
<div className="min-w-0 flex-1">
|
||||
{eyebrow ? (
|
||||
<p className="text-sm font-semibold text-grayScale-500">{eyebrow}</p>
|
||||
) : null}
|
||||
<div className={cn(eyebrow && "mt-1")}>{title}</div>
|
||||
{description ? (
|
||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{actions ? (
|
||||
<div className="flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto sm:justify-end">
|
||||
{actions}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
22
src/components/admin/AdminTableContainer.tsx
Normal file
22
src/components/admin/AdminTableContainer.tsx
Normal file
|
|
@ -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 (
|
||||
<div className={cn("min-w-0 overflow-x-auto rounded-lg border border-grayScale-100", className)}>
|
||||
<div style={minWidth ? { minWidth } : undefined} className={minWidth ? undefined : "min-w-0"}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
130
src/components/admin/TablePagination.tsx
Normal file
130
src/components/admin/TablePagination.tsx
Normal file
|
|
@ -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 (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3 text-sm text-grayScale-500",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span>Showing</span>
|
||||
<span className="font-medium text-grayScale-600">
|
||||
{startEntry}-{endEntry}
|
||||
</span>
|
||||
<span>of</span>
|
||||
<span className="font-medium text-grayScale-600">{totalCount}</span>
|
||||
<span className="mr-2 sm:mr-4">entries</span>
|
||||
<span className="hidden border-l pl-4 sm:inline">Rows per page</span>
|
||||
<span className="sm:hidden">·</span>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={pageSize}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onPageSizeChange(Number(e.target.value))}
|
||||
className="h-8 appearance-none rounded-md border bg-white pl-2 pr-7 text-sm font-medium text-grayScale-600 focus:outline-none"
|
||||
aria-label="Rows per page"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-grayScale-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPageChange(Math.max(1, currentPage - 1))}
|
||||
disabled={disabled || currentPage <= 1}
|
||||
className={cn(
|
||||
"flex h-8 w-8 items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
(disabled || currentPage <= 1) && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
aria-label="Previous page"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
{getPageNumbers(currentPage, totalPages).map((n, idx) =>
|
||||
typeof n === "string" ? (
|
||||
<span key={`ellipsis-${idx}`} className="px-2 text-grayScale-400">
|
||||
...
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => onPageChange(n)}
|
||||
className={cn(
|
||||
"h-8 w-8 rounded-md border text-sm font-medium",
|
||||
n === currentPage
|
||||
? "border-brand-500 bg-brand-500 text-white"
|
||||
: "bg-white text-grayScale-600 hover:bg-grayScale-50",
|
||||
)}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPageChange(Math.min(totalPages, currentPage + 1))}
|
||||
disabled={disabled || currentPage >= totalPages}
|
||||
className={cn(
|
||||
"flex h-8 w-8 items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
(disabled || currentPage >= totalPages) && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
aria-label="Next page"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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<string, unknown>
|
||||
}
|
||||
|
||||
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 (
|
||||
<DynamicSequenceOrderSlot
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
slotLabel={fieldLabel}
|
||||
config={row.config}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (mode === "text") {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
>
|
||||
<span className="w-10 text-xs font-medium text-grayScale-500">
|
||||
{blank.blank_id}
|
||||
<span className="w-16 shrink-0 text-[10px] font-bold uppercase tracking-wide text-grayScale-400">
|
||||
Blank {blank.blank_id}
|
||||
</span>
|
||||
<select
|
||||
value={blank.word_id}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,204 @@
|
|||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from "@dnd-kit/core"
|
||||
import {
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
arrayMove,
|
||||
} from "@dnd-kit/sortable"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { GripVertical, Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "../ui/button"
|
||||
import { Input } from "../ui/input"
|
||||
import { cn } from "../../lib/utils"
|
||||
import {
|
||||
addSequenceOrderItem,
|
||||
limitsFromSchemaConfig,
|
||||
parseSequenceOrderSlotValue,
|
||||
removeSequenceOrderItem,
|
||||
serializeSequenceOrderSlotValue,
|
||||
updateSequenceOrderItemText,
|
||||
type SequenceOrderSlotValue,
|
||||
} from "../../lib/sequenceOrderSlotValue"
|
||||
|
||||
function SortableSequenceRow({
|
||||
id,
|
||||
itemId,
|
||||
text,
|
||||
index,
|
||||
disabled,
|
||||
canRemove,
|
||||
onTextChange,
|
||||
onRemove,
|
||||
}: {
|
||||
id: string
|
||||
itemId: string
|
||||
text: string
|
||||
index: number
|
||||
disabled: boolean
|
||||
canRemove: boolean
|
||||
onTextChange: (text: string) => void
|
||||
onRemove: () => void
|
||||
}) {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id })
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-50/50 p-3 sm:flex-nowrap",
|
||||
isDragging && "relative z-50 opacity-60",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-9 w-9 shrink-0 cursor-grab items-center justify-center rounded-md text-grayScale-400 hover:bg-white hover:text-grayScale-600 active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={disabled}
|
||||
aria-label={`Drag item ${itemId}`}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
>
|
||||
<GripVertical className="h-4 w-4" />
|
||||
</button>
|
||||
<p className="w-16 shrink-0 text-[10px] font-bold uppercase tracking-wide text-grayScale-400">
|
||||
Item {itemId}
|
||||
</p>
|
||||
<Input
|
||||
value={text}
|
||||
onChange={(e) => 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}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled || !canRemove}
|
||||
className="h-9 w-9 shrink-0 text-grayScale-400 hover:text-red-600 disabled:opacity-40"
|
||||
aria-label={`Remove item ${itemId}`}
|
||||
onClick={onRemove}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DynamicSequenceOrderSlot({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
slotLabel,
|
||||
config,
|
||||
}: {
|
||||
value: string
|
||||
onChange: (next: string) => void
|
||||
disabled: boolean
|
||||
slotLabel: string
|
||||
config?: Record<string, unknown>
|
||||
}) {
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<label className="text-sm font-medium text-grayScale-700">{slotLabel}</label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled || !canAdd}
|
||||
className="h-8 gap-1.5 rounded-lg border-brand-200 text-brand-600 hover:bg-brand-50"
|
||||
onClick={() => updateValue(addSequenceOrderItem(parsed, maxItems))}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
Add item
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
|
||||
<div className="space-y-2">
|
||||
{parsed.items.map((item, index) => (
|
||||
<SortableSequenceRow
|
||||
key={item.id}
|
||||
id={item.id}
|
||||
itemId={item.id}
|
||||
text={item.text}
|
||||
index={index}
|
||||
disabled={disabled}
|
||||
canRemove={canRemove}
|
||||
onTextChange={(text) =>
|
||||
updateValue(updateSequenceOrderItemText(parsed, index, text))
|
||||
}
|
||||
onRemove={() =>
|
||||
updateValue(removeSequenceOrderItem(parsed, index))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<p className="text-[11px] text-grayScale-500">
|
||||
Minimum {minItems} items (max {maxItems}). Drag to set the correct order.
|
||||
Whitespace in text is preserved.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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" },
|
||||
|
|
|
|||
|
|
@ -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<typeof setTimeout>
|
||||
}
|
||||
|
||||
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<HTMLDivElement>(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 (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"group relative flex w-full gap-3 rounded-lg px-3 py-3 text-left transition-colors hover:bg-grayScale-100",
|
||||
)}
|
||||
onClick={() => onOpen(notification)}
|
||||
>
|
||||
{!notification.is_read && (
|
||||
<span className="absolute left-0.5 top-1/2 h-2 w-2 -translate-y-1/2 rounded-full bg-brand-500" />
|
||||
)}
|
||||
|
||||
<span
|
||||
<div className="overflow-hidden">
|
||||
<div
|
||||
ref={slideRef}
|
||||
className={cn(
|
||||
"ml-3 grid h-9 w-9 shrink-0 place-items-center rounded-lg",
|
||||
cfg.bg,
|
||||
"w-full will-change-transform transition-[transform,opacity] duration-300 ease-in-out",
|
||||
slideOut ? "-translate-x-full opacity-0" : "translate-x-0 opacity-100",
|
||||
)}
|
||||
>
|
||||
<Icon className={cn("h-4 w-4", cfg.color)} />
|
||||
</span>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"text-sm leading-snug text-grayScale-900",
|
||||
!notification.is_read && "font-semibold",
|
||||
"group relative flex w-full gap-3 rounded-lg px-3 py-3 text-left transition-colors hover:bg-grayScale-100",
|
||||
)}
|
||||
onClick={() => onOpen(notification)}
|
||||
>
|
||||
{getNotificationTitle(notification) || "Notification"}
|
||||
</p>
|
||||
<p className="mt-0.5 line-clamp-2 text-xs text-grayScale-700">
|
||||
{getNotificationMessage(notification) || "No preview text available."}
|
||||
</p>
|
||||
<p className="mt-1 text-[11px] text-grayScale-600">
|
||||
{formatNotificationTimestamp(notification.timestamp)}
|
||||
</p>
|
||||
</div>
|
||||
{!notification.is_read && (
|
||||
<span className="absolute left-0.5 top-1/2 h-2 w-2 -translate-y-1/2 rounded-full bg-brand-500" />
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="hidden shrink-0 self-center rounded-md p-1.5 text-grayScale-400 hover:bg-grayScale-200 hover:text-grayScale-600 group-hover:block"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (notification.is_read) {
|
||||
onMarkUnread(notification.id)
|
||||
} else {
|
||||
onMarkRead(notification.id)
|
||||
}
|
||||
}}
|
||||
aria-label={notification.is_read ? "Mark as unread" : "Mark as read"}
|
||||
>
|
||||
{notification.is_read ? (
|
||||
<Mail className="h-4 w-4" />
|
||||
) : (
|
||||
<MailOpen className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="hidden shrink-0 self-center rounded-md p-1.5 text-destructive hover:bg-destructive/10 group-hover:block"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(notification)
|
||||
}}
|
||||
aria-label="Delete notification"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</button>
|
||||
<span
|
||||
className={cn(
|
||||
"ml-3 grid h-9 w-9 shrink-0 place-items-center rounded-lg",
|
||||
cfg.bg,
|
||||
)}
|
||||
>
|
||||
<Icon className={cn("h-4 w-4", cfg.color)} />
|
||||
</span>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm leading-snug text-grayScale-900",
|
||||
!notification.is_read && "font-semibold",
|
||||
)}
|
||||
>
|
||||
{getNotificationTitle(notification) || "Notification"}
|
||||
</p>
|
||||
<p className="mt-0.5 line-clamp-2 text-xs text-grayScale-700">
|
||||
{getNotificationMessage(notification) || "No preview text available."}
|
||||
</p>
|
||||
<p className="mt-1 text-[11px] text-grayScale-600">
|
||||
{formatNotificationTimestamp(notification.timestamp)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="hidden shrink-0 self-center rounded-md p-1.5 text-grayScale-400 hover:bg-grayScale-200 hover:text-grayScale-600 group-hover:block"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (notification.is_read) {
|
||||
onMarkUnread(notification.id)
|
||||
} else {
|
||||
onMarkRead(notification.id)
|
||||
}
|
||||
}}
|
||||
aria-label={notification.is_read ? "Mark as unread" : "Mark as read"}
|
||||
>
|
||||
{notification.is_read ? (
|
||||
<Mail className="h-4 w-4" />
|
||||
) : (
|
||||
<MailOpen className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="hidden shrink-0 self-center rounded-md p-1.5 text-destructive hover:bg-destructive/10 group-hover:block"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(notification)
|
||||
}}
|
||||
aria-label="Delete notification"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -111,7 +152,11 @@ export function NotificationDropdown() {
|
|||
const [detailError, setDetailError] = useState(false)
|
||||
const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null)
|
||||
const [selectedNotificationId, setSelectedNotificationId] = useState<string | null>(null)
|
||||
const [notificationPendingDelete, setNotificationPendingDelete] = useState<Notification | null>(null)
|
||||
const [dismissingIds, setDismissingIds] = useState<Set<string>>(() => new Set())
|
||||
const [hiddenIds, setHiddenIds] = useState<Set<string>>(() => new Set())
|
||||
const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null)
|
||||
const slideTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())
|
||||
const pendingDeleteRef = useRef<PendingDelete | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(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 (
|
||||
<>
|
||||
<div ref={containerRef} className="relative">
|
||||
|
|
@ -198,7 +341,7 @@ export function NotificationDropdown() {
|
|||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="animate-in fade-in-0 zoom-in-95 absolute right-0 top-12 z-50 w-[380px] rounded-xl bg-white shadow-lg ring-1 ring-black/5">
|
||||
<div className="animate-in fade-in-0 zoom-in-95 absolute right-0 top-12 z-50 w-[min(380px,calc(100vw-1.5rem))] max-w-[calc(100vw-1.5rem)] rounded-xl bg-white shadow-lg ring-1 ring-black/5">
|
||||
<div className="flex items-center justify-between border-b px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-semibold text-grayScale-800">Notifications</h3>
|
||||
|
|
@ -225,30 +368,43 @@ export function NotificationDropdown() {
|
|||
<div className="flex items-center justify-center py-12">
|
||||
<SpinnerIcon className="h-6 w-6" />
|
||||
</div>
|
||||
) : notifications.length === 0 ? (
|
||||
) : visibleNotifications.length === 0 && !pendingDelete ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-12 text-grayScale-400">
|
||||
<BellOff className="h-8 w-8" />
|
||||
<p className="text-sm">No notifications</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-1">
|
||||
{notifications.map((n) => (
|
||||
{visibleNotifications.map((n) => (
|
||||
<NotificationItem
|
||||
key={n.id}
|
||||
notification={n}
|
||||
isDismissing={dismissingIds.has(n.id)}
|
||||
onOpen={handleOpenNotification}
|
||||
onMarkRead={markOneRead}
|
||||
onMarkUnread={markOneUnread}
|
||||
onDelete={(notification) => {
|
||||
setOpen(false)
|
||||
setNotificationPendingDelete(notification)
|
||||
}}
|
||||
onDelete={beginDeleteWithUndo}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{pendingDelete ? (
|
||||
<div className="animate-in slide-in-from-bottom-2 fade-in-0 border-t bg-grayScale-900 px-4 py-2.5 duration-200">
|
||||
<div className="flex items-center justify-between gap-3 text-xs text-white">
|
||||
<span className="truncate text-grayScale-100">Notification deleted</span>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-md px-2 py-1 font-semibold text-brand-300 transition-colors hover:bg-white/10 hover:text-white"
|
||||
onClick={handleUndoDelete}
|
||||
>
|
||||
Undo
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="border-t px-4 py-2.5">
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -272,25 +428,20 @@ export function NotificationDropdown() {
|
|||
loading={detailLoading}
|
||||
error={detailError}
|
||||
onRetry={
|
||||
selectedNotificationId
|
||||
? () => void loadNotificationDetail(selectedNotificationId, false)
|
||||
selectedNotificationId && selectedNotification
|
||||
? () => void loadNotificationDetail(selectedNotification, false)
|
||||
: undefined
|
||||
}
|
||||
onDelete={
|
||||
selectedNotification
|
||||
? () => setNotificationPendingDelete(selectedNotification)
|
||||
? () => {
|
||||
setDetailOpen(false)
|
||||
setOpen(true)
|
||||
beginDeleteWithUndo(selectedNotification)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<NotificationDeleteDialog
|
||||
notification={notificationPendingDelete}
|
||||
open={notificationPendingDelete !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setNotificationPendingDelete(null)
|
||||
}}
|
||||
onDeleted={handleNotificationDeleted}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ import * as React from "react"
|
|||
import { Upload } from "lucide-react"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
export interface FileUploadProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "type"> {
|
||||
export interface FileUploadProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "type" | "value"> {
|
||||
/** Controlled selected file; when set, internal state follows this value. */
|
||||
value?: File | null
|
||||
onFileSelect?: (file: File | null) => void
|
||||
accept?: string
|
||||
label?: string
|
||||
|
|
@ -12,15 +14,26 @@ export interface FileUploadProps extends Omit<React.InputHTMLAttributes<HTMLInpu
|
|||
}
|
||||
|
||||
export const FileUpload = React.forwardRef<HTMLInputElement, FileUploadProps>(
|
||||
({ className, onFileSelect, accept, label, description, variant = "default", ...props }, ref) => {
|
||||
const [file, setFile] = React.useState<File | null>(null)
|
||||
(
|
||||
{ className, value, onFileSelect, accept, label, description, variant = "default", ...props },
|
||||
ref,
|
||||
) => {
|
||||
const [internalFile, setInternalFile] = React.useState<File | null>(null)
|
||||
const [dragActive, setDragActive] = React.useState(false)
|
||||
const inputRef = React.useRef<HTMLInputElement>(null)
|
||||
const isControlled = value !== undefined
|
||||
const file = isControlled ? value : internalFile
|
||||
|
||||
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!file && inputRef.current) {
|
||||
inputRef.current.value = ""
|
||||
}
|
||||
}, [file])
|
||||
|
||||
const handleFile = (selectedFile: File | null) => {
|
||||
setFile(selectedFile)
|
||||
if (!isControlled) setInternalFile(selectedFile)
|
||||
onFileSelect?.(selectedFile)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ export const Table = React.forwardRef<HTMLTableElement, TableProps>(
|
|||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
)
|
||||
if (noWrapper) return table
|
||||
return <div className="relative w-full overflow-auto">{table}</div>
|
||||
return <div className="relative w-full min-w-0 overflow-auto">{table}</div>
|
||||
},
|
||||
)
|
||||
Table.displayName = "Table"
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
import { useEffect, useState, useCallback, useRef } from "react"
|
||||
import { getNotifications, getUnreadCount, markAsRead, markAsUnread, markAllRead, deleteNotification } from "../api/notifications.api"
|
||||
import {
|
||||
getNotifications,
|
||||
getUnreadCount,
|
||||
markAsRead,
|
||||
markAsUnread,
|
||||
markAllRead,
|
||||
deleteNotification,
|
||||
} from "../api/notifications.api"
|
||||
import type { Notification } from "../types/notification.types"
|
||||
import {
|
||||
NOTIFICATION_REALTIME_EVENT,
|
||||
} from "../lib/notificationsWebSocket"
|
||||
|
||||
const MAX_DROPDOWN = 5
|
||||
const RECONNECT_MS = 5000
|
||||
|
||||
function getWsUrl() {
|
||||
const base = import.meta.env.VITE_API_BASE_URL as string
|
||||
const wsBase = base.replace(/^https/, "wss").replace(/^http/, "ws")
|
||||
const token = localStorage.getItem("access_token") ?? ""
|
||||
return `${wsBase}/ws/connect?token=${encodeURIComponent(token)}`
|
||||
}
|
||||
const ENRICH_REFRESH_MS = 2000
|
||||
|
||||
export function useNotifications() {
|
||||
const [notifications, setNotifications] = useState<Notification[]>([])
|
||||
const [unreadCount, setUnreadCount] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const enrichRefreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const intentionalCloseRef = useRef(false)
|
||||
const connectAttemptRef = useRef(0)
|
||||
|
||||
const dispatchUpdate = () => {
|
||||
window.dispatchEvent(new Event("notifications-updated"))
|
||||
|
|
@ -43,92 +43,84 @@ export function useNotifications() {
|
|||
}
|
||||
}, [])
|
||||
|
||||
const clearReconnectTimer = useCallback(() => {
|
||||
if (reconnectTimer.current) {
|
||||
clearTimeout(reconnectTimer.current)
|
||||
reconnectTimer.current = null
|
||||
const syncUnreadCount = useCallback(async () => {
|
||||
try {
|
||||
const countRes = await getUnreadCount()
|
||||
if (mountedRef.current) setUnreadCount(countRes.data.unread)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}, [])
|
||||
|
||||
const disconnectWs = useCallback(
|
||||
(intentional: boolean) => {
|
||||
intentionalCloseRef.current = intentional
|
||||
clearReconnectTimer()
|
||||
const ws = wsRef.current
|
||||
wsRef.current = null
|
||||
if (!ws) return
|
||||
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
||||
ws.close()
|
||||
}
|
||||
const refreshQuietly = useCallback(async () => {
|
||||
try {
|
||||
const [notifRes, countRes] = await Promise.all([
|
||||
getNotifications(5, 0),
|
||||
getUnreadCount(),
|
||||
])
|
||||
if (!mountedRef.current) return
|
||||
setNotifications((prev) => {
|
||||
const fromApi = notifRes.data.notifications ?? []
|
||||
const apiIds = new Set(fromApi.map((n) => n.id))
|
||||
const pending = prev.filter((n) => !apiIds.has(n.id))
|
||||
return [...pending, ...fromApi].slice(0, MAX_DROPDOWN)
|
||||
})
|
||||
setUnreadCount(countRes.data.unread)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}, [])
|
||||
|
||||
const clearEnrichRefreshTimer = useCallback(() => {
|
||||
if (enrichRefreshTimer.current) {
|
||||
clearTimeout(enrichRefreshTimer.current)
|
||||
enrichRefreshTimer.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const scheduleEnrichRefresh = useCallback(() => {
|
||||
clearEnrichRefreshTimer()
|
||||
enrichRefreshTimer.current = setTimeout(() => {
|
||||
enrichRefreshTimer.current = null
|
||||
void refreshQuietly()
|
||||
}, ENRICH_REFRESH_MS)
|
||||
}, [clearEnrichRefreshTimer, refreshQuietly])
|
||||
|
||||
const applyRealtimeNotification = useCallback(
|
||||
(notif: Notification) => {
|
||||
setNotifications((prev) => {
|
||||
const withoutDuplicate = prev.filter((n) => n.id !== notif.id)
|
||||
return [notif, ...withoutDuplicate].slice(0, MAX_DROPDOWN)
|
||||
})
|
||||
scheduleEnrichRefresh()
|
||||
},
|
||||
[clearReconnectTimer],
|
||||
[scheduleEnrichRefresh],
|
||||
)
|
||||
|
||||
const connectWs = useCallback(() => {
|
||||
if (!mountedRef.current) return
|
||||
|
||||
const token = localStorage.getItem("access_token")?.trim()
|
||||
if (!token) return
|
||||
|
||||
disconnectWs(true)
|
||||
intentionalCloseRef.current = false
|
||||
|
||||
const attempt = ++connectAttemptRef.current
|
||||
const ws = new WebSocket(getWsUrl())
|
||||
wsRef.current = ws
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const raw = JSON.parse(event.data)
|
||||
const notif: Notification = {
|
||||
id: raw.id ?? crypto.randomUUID(),
|
||||
recipient_id: raw.recipient_id ?? 0,
|
||||
type: raw.type ?? "",
|
||||
level: raw.level ?? "",
|
||||
error_severity: raw.error_severity ?? "",
|
||||
reciever: raw.reciever ?? "",
|
||||
is_read: raw.is_read ?? false,
|
||||
delivery_status: raw.delivery_status ?? "",
|
||||
delivery_channel: raw.delivery_channel ?? "",
|
||||
payload: {
|
||||
headline: raw.payload?.headline ?? raw.payload?.title ?? raw.headline ?? raw.title ?? "",
|
||||
message: raw.payload?.message ?? raw.payload?.body ?? raw.message ?? raw.body ?? "",
|
||||
tags: raw.payload?.tags ?? raw.tags ?? null,
|
||||
},
|
||||
timestamp: raw.timestamp ?? raw.created_at ?? new Date().toISOString(),
|
||||
expires: raw.expires ?? "",
|
||||
image: raw.image ?? "",
|
||||
}
|
||||
setNotifications((prev) => [notif, ...prev].slice(0, MAX_DROPDOWN))
|
||||
setUnreadCount((prev) => prev + 1)
|
||||
dispatchUpdate()
|
||||
} catch {
|
||||
// ignore malformed messages
|
||||
}
|
||||
}
|
||||
|
||||
ws.onclose = () => {
|
||||
if (connectAttemptRef.current !== attempt) return
|
||||
if (wsRef.current === ws) wsRef.current = null
|
||||
if (!mountedRef.current || intentionalCloseRef.current) return
|
||||
clearReconnectTimer()
|
||||
reconnectTimer.current = setTimeout(() => {
|
||||
if (mountedRef.current) connectWs()
|
||||
}, RECONNECT_MS)
|
||||
}
|
||||
}, [clearReconnectTimer, disconnectWs])
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
intentionalCloseRef.current = false
|
||||
fetchData()
|
||||
connectWs()
|
||||
|
||||
const onRealtime = (event: Event) => {
|
||||
const detail = (event as CustomEvent<Notification>).detail
|
||||
if (!detail) return
|
||||
applyRealtimeNotification(detail)
|
||||
}
|
||||
|
||||
const onNotificationsUpdated = () => {
|
||||
void syncUnreadCount()
|
||||
}
|
||||
|
||||
window.addEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime)
|
||||
window.addEventListener("notifications-updated", onNotificationsUpdated)
|
||||
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
disconnectWs(true)
|
||||
window.removeEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime)
|
||||
window.removeEventListener("notifications-updated", onNotificationsUpdated)
|
||||
clearEnrichRefreshTimer()
|
||||
}
|
||||
}, [fetchData, connectWs, disconnectWs])
|
||||
}, [fetchData, applyRealtimeNotification, clearEnrichRefreshTimer, syncUnreadCount])
|
||||
|
||||
const markOneRead = useCallback(async (id: string) => {
|
||||
setNotifications((prev) =>
|
||||
|
|
@ -182,6 +174,27 @@ export function useNotifications() {
|
|||
}
|
||||
}, [notifications, fetchData])
|
||||
|
||||
const commitDeleteNotification = useCallback(async (notification: Notification) => {
|
||||
setNotifications((prev) => prev.filter((n) => n.id !== notification.id))
|
||||
if (!notification.is_read) {
|
||||
setUnreadCount((prev) => Math.max(0, prev - 1))
|
||||
}
|
||||
dispatchUpdate()
|
||||
try {
|
||||
await deleteNotification(notification.id)
|
||||
} catch {
|
||||
await fetchData()
|
||||
throw new Error("delete failed")
|
||||
}
|
||||
}, [fetchData])
|
||||
|
||||
const restoreNotification = useCallback((notification: Notification) => {
|
||||
setNotifications((prev) => {
|
||||
if (prev.some((n) => n.id === notification.id)) return prev
|
||||
return [notification, ...prev].slice(0, MAX_DROPDOWN)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
|
@ -194,6 +207,8 @@ export function useNotifications() {
|
|||
markOneUnread,
|
||||
markAllAsRead,
|
||||
deleteOne,
|
||||
commitDeleteNotification,
|
||||
restoreNotification,
|
||||
refresh,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -157,4 +157,20 @@
|
|||
html.dark .bg-white {
|
||||
background-color: var(--gs-50);
|
||||
}
|
||||
|
||||
.admin-page-header {
|
||||
@apply flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4;
|
||||
}
|
||||
|
||||
.admin-page-actions {
|
||||
@apply flex w-full flex-wrap items-stretch gap-2 sm:w-auto sm:justify-end;
|
||||
}
|
||||
|
||||
.admin-responsive-grid-2 {
|
||||
@apply grid grid-cols-1 gap-4 sm:grid-cols-2;
|
||||
}
|
||||
|
||||
.admin-responsive-grid-3 {
|
||||
@apply grid grid-cols-1 gap-4 sm:grid-cols-3;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,11 @@ import { useState, useCallback, useEffect, useMemo, useRef } from "react"
|
|||
import { Navigate, Outlet, useLocation } from "react-router-dom"
|
||||
import { Sidebar } from "../components/sidebar/Sidebar"
|
||||
import { Topbar } from "../components/topbar/Topbar"
|
||||
import { getAccessToken } from "../lib/teamAuthStorage"
|
||||
import {
|
||||
connectNotificationsWebSocket,
|
||||
disconnectNotificationsWebSocket,
|
||||
} from "../lib/notificationsWebSocket"
|
||||
|
||||
export function AppLayout() {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||
|
|
@ -12,7 +17,13 @@ export function AppLayout() {
|
|||
const scrollStoragePrefix = "app:scroll:"
|
||||
const routeKey = useMemo(() => `${location.pathname}${location.search}`, [location.pathname, location.search])
|
||||
|
||||
const token = localStorage.getItem("access_token")
|
||||
const token = getAccessToken()
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
connectNotificationsWebSocket()
|
||||
return () => disconnectNotificationsWebSocket()
|
||||
}, [token])
|
||||
|
||||
const handleSidebarToggle = useCallback(() => {
|
||||
setSidebarOpen((prev) => !prev)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
import { clearTeamSession } from "./teamAuthStorage"
|
||||
|
||||
/** Clear session tokens and redirect to login (full page navigation). */
|
||||
export function logoutToLogin(options?: { passwordChanged?: boolean }) {
|
||||
localStorage.removeItem("access_token")
|
||||
localStorage.removeItem("refresh_token")
|
||||
localStorage.removeItem("member_id")
|
||||
localStorage.removeItem("role")
|
||||
clearTeamSession()
|
||||
const search = options?.passwordChanged ? "?password_changed=1" : ""
|
||||
window.location.href = `/login${search}`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,13 @@ import {
|
|||
validateSelectMissingWordsResponseSlotValue,
|
||||
validateSelectMissingWordsStimulusSlotValue,
|
||||
} from "./selectMissingWordsSlotValue"
|
||||
import {
|
||||
defaultSequenceOrderSlotValue,
|
||||
parseSequenceOrderSlotValue,
|
||||
sequenceOrderSlotHasContent,
|
||||
serializeSequenceOrderSlotValue,
|
||||
validateSequenceOrderSlotValue,
|
||||
} from "./sequenceOrderSlotValue"
|
||||
import { isNoInputComponentKind } from "./questionComponentKinds"
|
||||
|
||||
function isMultipleChoiceKind(kind: string): boolean {
|
||||
|
|
@ -52,12 +59,17 @@ function isSelectMissingWordsKind(kind: string): boolean {
|
|||
return kind.trim().toUpperCase() === "SELECT_MISSING_WORDS"
|
||||
}
|
||||
|
||||
function isSequenceOrderKind(kind: string): boolean {
|
||||
return kind.trim().toUpperCase() === "SEQUENCE_ORDER"
|
||||
}
|
||||
|
||||
function isStructuredDynamicSlotKind(kind: string): boolean {
|
||||
return (
|
||||
isMultipleChoiceKind(kind) ||
|
||||
isMatchingInputsKind(kind) ||
|
||||
isMatchingAnswerKind(kind) ||
|
||||
isSelectMissingWordsKind(kind)
|
||||
isSelectMissingWordsKind(kind) ||
|
||||
isSequenceOrderKind(kind)
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -87,6 +99,9 @@ function defaultValueForSchemaSlot(
|
|||
}
|
||||
return serializeSelectMissingWordsResponseSlotValue({ blanks: [] })
|
||||
}
|
||||
if (isSequenceOrderKind(kind)) {
|
||||
return serializeSequenceOrderSlotValue(defaultSequenceOrderSlotValue())
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
|
@ -281,6 +296,16 @@ export function questionRowHasContent(
|
|||
}
|
||||
continue
|
||||
}
|
||||
if (isSequenceOrderKind(row.kind)) {
|
||||
if (
|
||||
sequenceOrderSlotHasContent(
|
||||
parseSequenceOrderSlotValue(fv[`response:${row.id}`]),
|
||||
)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (fv[`response:${row.id}`]?.trim()) return true
|
||||
}
|
||||
return false
|
||||
|
|
@ -556,6 +581,19 @@ export function validateDefinitionQuestion(
|
|||
return `Question ${n} (response "${row.label || row.id}"): ${err}`
|
||||
}
|
||||
}
|
||||
if (isSequenceOrderKind(row.kind)) {
|
||||
const val = parseSequenceOrderSlotValue(fieldValues[`response:${row.id}`])
|
||||
if (!sequenceOrderSlotHasContent(val)) {
|
||||
if (row.required) {
|
||||
return `Question ${n}: add sequence items for response "${row.label || row.id}".`
|
||||
}
|
||||
continue
|
||||
}
|
||||
const err = validateSequenceOrderSlotValue(val, row.config)
|
||||
if (err) {
|
||||
return `Question ${n} (response "${row.label || row.id}"): ${err}`
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
import type { UserApiDTO } from "../types/user.types"
|
||||
import type { TeamMember } from "../types/team.types"
|
||||
import type {
|
||||
BulkSendResult,
|
||||
PlatformRole,
|
||||
ScheduledNotification,
|
||||
TeamRole,
|
||||
} from "../types/notification.types"
|
||||
import { getUsers } from "../api/users.api"
|
||||
import { getTeamMembers } from "../api/team.api"
|
||||
import { TEAM_ROLE_OPTIONS } from "./teamRoles"
|
||||
|
||||
export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [
|
||||
{ value: "STUDENT", label: "Students" },
|
||||
|
|
@ -15,6 +19,20 @@ export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [
|
|||
{ value: "SUPPORT", label: "Support" },
|
||||
]
|
||||
|
||||
export const TEAM_ROLES: { value: TeamRole; label: string }[] = TEAM_ROLE_OPTIONS.map(
|
||||
(option) => ({
|
||||
value: option.value as TeamRole,
|
||||
label: option.label,
|
||||
}),
|
||||
)
|
||||
|
||||
export type NotificationAudienceMode =
|
||||
| "platform_role"
|
||||
| "platform_selected"
|
||||
| "team_role"
|
||||
| "team_selected"
|
||||
| "direct"
|
||||
|
||||
export const IN_APP_TYPES = [
|
||||
{ value: "system_alert", label: "System alert" },
|
||||
{ value: "subscription_expiring", label: "Subscription expiring" },
|
||||
|
|
@ -49,6 +67,8 @@ export function parseBulkResponseData(data: unknown): BulkSendResult | Scheduled
|
|||
sent: Number(data.sent ?? 0),
|
||||
failed: Number(data.failed ?? 0),
|
||||
target_users: data.target_users != null ? Number(data.target_users) : undefined,
|
||||
devices_targeted:
|
||||
data.devices_targeted != null ? Number(data.devices_targeted) : undefined,
|
||||
image: data.image != null ? String(data.image) : undefined,
|
||||
}
|
||||
}
|
||||
|
|
@ -163,6 +183,39 @@ export async function fetchAllPlatformUsers(): Promise<UserApiDTO[]> {
|
|||
return [...firstBatch, ...rest]
|
||||
}
|
||||
|
||||
export async function fetchAllTeamMembers(): Promise<TeamMember[]> {
|
||||
const pageSize = 50
|
||||
const firstRes = await getTeamMembers(1, pageSize)
|
||||
const firstBatch = firstRes.data?.data ?? []
|
||||
const total = firstRes.data?.metadata?.total ?? firstBatch.length
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize))
|
||||
|
||||
if (totalPages <= 1) return firstBatch
|
||||
|
||||
const remaining = await Promise.all(
|
||||
Array.from({ length: totalPages - 1 }, (_, i) =>
|
||||
getTeamMembers(i + 2, pageSize),
|
||||
),
|
||||
)
|
||||
const rest = remaining.flatMap((r) => r.data?.data ?? [])
|
||||
return [...firstBatch, ...rest]
|
||||
}
|
||||
|
||||
export function channelSupportsTeamTargeting(channel: string): boolean {
|
||||
return channel === "email" || channel === "in_app"
|
||||
}
|
||||
|
||||
export function isAudienceModeValidForChannel(
|
||||
mode: NotificationAudienceMode,
|
||||
channel: string,
|
||||
): boolean {
|
||||
if (mode === "direct") return channel === "sms" || channel === "email"
|
||||
if (mode === "team_role" || mode === "team_selected") {
|
||||
return channelSupportsTeamTargeting(channel)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export function extractApiErrorMessage(err: unknown, fallback: string): string {
|
||||
if (isRecord(err) && isRecord(err.response) && isRecord(err.response.data)) {
|
||||
const data = err.response.data
|
||||
|
|
|
|||
98
src/lib/notificationsWebSocket.ts
Normal file
98
src/lib/notificationsWebSocket.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { parseRealtimeNotification } from "../api/notifications.api"
|
||||
import type { Notification } from "../types/notification.types"
|
||||
import { getAccessToken, TEAM_SESSION_UPDATED_EVENT } from "./teamAuthStorage"
|
||||
|
||||
const RECONNECT_MS = 5000
|
||||
|
||||
export const NOTIFICATION_REALTIME_EVENT = "yimaru:notification-realtime"
|
||||
|
||||
function getWsUrl() {
|
||||
const base = import.meta.env.VITE_API_BASE_URL as string
|
||||
const wsBase = base.replace(/^https/, "wss").replace(/^http/, "ws")
|
||||
const token = getAccessToken() ?? ""
|
||||
return `${wsBase}/ws/connect?token=${encodeURIComponent(token)}`
|
||||
}
|
||||
|
||||
let ws: WebSocket | null = null
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let intentionalClose = false
|
||||
let connectAttempt = 0
|
||||
let sessionListenerAttached = false
|
||||
|
||||
function clearReconnectTimer() {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer)
|
||||
reconnectTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function dispatchRealtimeNotification(notification: Notification) {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<Notification>(NOTIFICATION_REALTIME_EVENT, { detail: notification }),
|
||||
)
|
||||
window.dispatchEvent(new Event("notifications-updated"))
|
||||
}
|
||||
|
||||
function handleMessage(event: MessageEvent) {
|
||||
try {
|
||||
const parsed = JSON.parse(event.data as string)
|
||||
const notification = parseRealtimeNotification(parsed)
|
||||
if (!notification) return
|
||||
dispatchRealtimeNotification(notification)
|
||||
} catch {
|
||||
// ignore malformed messages
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
clearReconnectTimer()
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null
|
||||
connectNotificationsWebSocket()
|
||||
}, RECONNECT_MS)
|
||||
}
|
||||
|
||||
export function disconnectNotificationsWebSocket() {
|
||||
intentionalClose = true
|
||||
clearReconnectTimer()
|
||||
const socket = ws
|
||||
ws = null
|
||||
if (!socket) return
|
||||
if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
|
||||
socket.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function connectNotificationsWebSocket() {
|
||||
const token = getAccessToken()?.trim()
|
||||
if (!token) return
|
||||
|
||||
disconnectNotificationsWebSocket()
|
||||
intentionalClose = false
|
||||
|
||||
const attempt = ++connectAttempt
|
||||
const socket = new WebSocket(getWsUrl())
|
||||
ws = socket
|
||||
|
||||
socket.onmessage = handleMessage
|
||||
|
||||
socket.onclose = () => {
|
||||
if (connectAttempt !== attempt) return
|
||||
if (ws === socket) ws = null
|
||||
if (intentionalClose) return
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
if (!sessionListenerAttached) {
|
||||
sessionListenerAttached = true
|
||||
window.addEventListener(TEAM_SESSION_UPDATED_EVENT, () => {
|
||||
connectNotificationsWebSocket()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureNotificationsWebSocket() {
|
||||
if (!ws || ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
|
||||
connectNotificationsWebSocket()
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,11 @@ import {
|
|||
selectMissingWordsResponseHasContent,
|
||||
selectMissingWordsStimulusHasContent,
|
||||
} from "./selectMissingWordsSlotValue"
|
||||
import {
|
||||
finalizeSequenceOrderPayload,
|
||||
parseSequenceOrderSlotValue,
|
||||
sequenceOrderSlotHasContent,
|
||||
} from "./sequenceOrderSlotValue"
|
||||
import {
|
||||
multipleChoiceOptionHasValue,
|
||||
multipleChoiceSlotHasContent,
|
||||
|
|
@ -64,6 +69,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 slotValueForRow(
|
||||
row: { id: string; kind: string },
|
||||
side: "stimulus" | "response",
|
||||
|
|
@ -139,6 +148,14 @@ function slotValueForRow(
|
|||
return { blanks: [] }
|
||||
}
|
||||
|
||||
if (isSequenceOrderKind(row.kind)) {
|
||||
const fromField = parseSequenceOrderSlotValue(rawField)
|
||||
if (sequenceOrderSlotHasContent(fromField)) {
|
||||
return finalizeSequenceOrderPayload(fromField)
|
||||
}
|
||||
return { items: [], correct_order: [] }
|
||||
}
|
||||
|
||||
if (side === "stimulus" && PLAIN_TEXT_STIMULUS_KINDS.has(row.kind.trim().toUpperCase())) {
|
||||
return (rawField ?? "").trim()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,20 +37,13 @@ export const SELECT_MISSING_WORDS_MIN_BLANKS = 1
|
|||
const DEFAULT_BLANK_COUNT = 2
|
||||
const DEFAULT_WORD_BANK_COUNT = 4
|
||||
|
||||
function reindexBlankSegments(segments: ClozeSegment[]): ClozeSegment[] {
|
||||
let blankIndex = 0
|
||||
return segments.map((segment) => {
|
||||
if (segment.type !== "blank") return segment
|
||||
blankIndex += 1
|
||||
return { type: "blank", id: `b${blankIndex}` }
|
||||
})
|
||||
}
|
||||
|
||||
function reindexWordBank(items: WordBankItem[]): WordBankItem[] {
|
||||
return items.map((item, index) => ({
|
||||
id: `w${index + 1}`,
|
||||
text: item.text,
|
||||
}))
|
||||
function nextStableId(prefix: string, existingIds: string[]): string {
|
||||
let max = 0
|
||||
for (const id of existingIds) {
|
||||
const match = id.match(new RegExp(`^${prefix}(\\d+)$`))
|
||||
if (match) max = Math.max(max, Number.parseInt(match[1], 10))
|
||||
}
|
||||
return `${prefix}${max + 1}`
|
||||
}
|
||||
|
||||
function normalizeTextSegment(raw: unknown, index: number): ClozeTextSegment {
|
||||
|
|
@ -158,16 +151,19 @@ function ensureMinWordBank(
|
|||
value: SelectMissingWordsStimulusValue,
|
||||
): SelectMissingWordsStimulusValue {
|
||||
const wordBank = [...value.word_bank]
|
||||
const wordIds = wordBank.map((item) => item.id)
|
||||
while (wordBank.length < SELECT_MISSING_WORDS_MIN_BANK) {
|
||||
wordBank.push({ id: `w${wordBank.length + 1}`, text: "" })
|
||||
const id = nextStableId("w", wordIds)
|
||||
wordIds.push(id)
|
||||
wordBank.push({ id, text: "" })
|
||||
}
|
||||
return {
|
||||
...value,
|
||||
segments:
|
||||
value.segments.length > 0
|
||||
? reindexBlankSegments(value.segments)
|
||||
? value.segments
|
||||
: defaultSelectMissingWordsStimulusSlotValue().segments,
|
||||
word_bank: reindexWordBank(wordBank),
|
||||
word_bank: wordBank,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -340,12 +336,13 @@ export function addWordBankItem(
|
|||
value: SelectMissingWordsStimulusValue,
|
||||
): SelectMissingWordsStimulusValue {
|
||||
const next = ensureMinWordBank(value)
|
||||
const id = nextStableId(
|
||||
"w",
|
||||
next.word_bank.map((item) => item.id),
|
||||
)
|
||||
return {
|
||||
...next,
|
||||
word_bank: reindexWordBank([
|
||||
...next.word_bank,
|
||||
{ id: `w${next.word_bank.length + 1}`, text: "" },
|
||||
]),
|
||||
word_bank: [...next.word_bank, { id, text: "" }],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -372,13 +369,10 @@ export function addTextSegment(
|
|||
export function addBlankSegment(
|
||||
value: SelectMissingWordsStimulusValue,
|
||||
): SelectMissingWordsStimulusValue {
|
||||
const blankCount = blankIdsFromStimulus(value).length
|
||||
const id = nextStableId("b", blankIdsFromStimulus(value))
|
||||
return ensureMinWordBank({
|
||||
...value,
|
||||
segments: [
|
||||
...value.segments,
|
||||
{ type: "blank", id: `b${blankCount + 1}` },
|
||||
],
|
||||
segments: [...value.segments, { type: "blank", id }],
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
254
src/lib/sequenceOrderSlotValue.ts
Normal file
254
src/lib/sequenceOrderSlotValue.ts
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
export interface SequenceOrderItem {
|
||||
id: string
|
||||
text: string
|
||||
}
|
||||
|
||||
export interface SequenceOrderSlotValue {
|
||||
items: SequenceOrderItem[]
|
||||
correct_order: string[]
|
||||
}
|
||||
|
||||
export const SEQUENCE_ORDER_MIN_ITEMS = 2
|
||||
export const SEQUENCE_ORDER_MAX_ITEMS = 12
|
||||
|
||||
const DEFAULT_ITEM_COUNT = 4
|
||||
|
||||
function nextStableId(prefix: string, existingIds: string[]): string {
|
||||
let max = 0
|
||||
for (const id of existingIds) {
|
||||
const match = id.match(new RegExp(`^${prefix}(\\d+)$`))
|
||||
if (match) max = Math.max(max, Number.parseInt(match[1], 10))
|
||||
}
|
||||
return `${prefix}${max + 1}`
|
||||
}
|
||||
|
||||
function normalizeItem(raw: unknown, index: number): SequenceOrderItem {
|
||||
if (raw && typeof raw === "object") {
|
||||
const record = raw as Record<string, unknown>
|
||||
return {
|
||||
id: String(record.id ?? `s${index + 1}`),
|
||||
text: String(record.text ?? ""),
|
||||
}
|
||||
}
|
||||
return { id: `s${index + 1}`, text: "" }
|
||||
}
|
||||
|
||||
function orderItemsByCorrectOrder(
|
||||
items: SequenceOrderItem[],
|
||||
correctOrder: string[],
|
||||
): SequenceOrderItem[] {
|
||||
if (!correctOrder.length) return items
|
||||
const byId = new Map(items.map((item) => [item.id, item]))
|
||||
const ordered = correctOrder
|
||||
.map((id) => byId.get(id))
|
||||
.filter((item): item is SequenceOrderItem => Boolean(item))
|
||||
const orderedIds = new Set(ordered.map((item) => item.id))
|
||||
const remainder = items.filter((item) => !orderedIds.has(item.id))
|
||||
return [...ordered, ...remainder]
|
||||
}
|
||||
|
||||
export function defaultSequenceOrderSlotValue(
|
||||
count = DEFAULT_ITEM_COUNT,
|
||||
): SequenceOrderSlotValue {
|
||||
const items = Array.from({ length: count }, (_, index) => ({
|
||||
id: `s${index + 1}`,
|
||||
text: "",
|
||||
}))
|
||||
return {
|
||||
items,
|
||||
correct_order: items.map((item) => item.id),
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeSequenceOrderSlotValue(value: SequenceOrderSlotValue): string {
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
function ensureMinItems(value: SequenceOrderSlotValue): SequenceOrderSlotValue {
|
||||
const items = [...value.items]
|
||||
const existingIds = items.map((item) => item.id)
|
||||
while (items.length < SEQUENCE_ORDER_MIN_ITEMS) {
|
||||
const id = nextStableId("s", existingIds)
|
||||
existingIds.push(id)
|
||||
items.push({ id, text: "" })
|
||||
}
|
||||
const correctOrder =
|
||||
value.correct_order.length > 0
|
||||
? value.correct_order.filter((id) => items.some((item) => item.id === id))
|
||||
: items.map((item) => item.id)
|
||||
const missingIds = items
|
||||
.map((item) => item.id)
|
||||
.filter((id) => !correctOrder.includes(id))
|
||||
return {
|
||||
items: orderItemsByCorrectOrder(items, correctOrder),
|
||||
correct_order: [...correctOrder, ...missingIds],
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeSequenceOrderValue(raw: unknown): SequenceOrderSlotValue {
|
||||
if (raw && typeof raw === "object") {
|
||||
const record = raw as Record<string, unknown>
|
||||
const items = Array.isArray(record.items)
|
||||
? record.items.map((item, index) => normalizeItem(item, index))
|
||||
: []
|
||||
const correctOrder = Array.isArray(record.correct_order)
|
||||
? record.correct_order.map((id) => String(id))
|
||||
: []
|
||||
if (items.length > 0) {
|
||||
return ensureMinItems({
|
||||
items,
|
||||
correct_order:
|
||||
correctOrder.length > 0 ? correctOrder : items.map((item) => item.id),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof raw === "string" && raw.trim()) {
|
||||
try {
|
||||
return normalizeSequenceOrderValue(JSON.parse(raw) as unknown)
|
||||
} catch {
|
||||
return defaultSequenceOrderSlotValue()
|
||||
}
|
||||
}
|
||||
|
||||
return defaultSequenceOrderSlotValue()
|
||||
}
|
||||
|
||||
export function parseSequenceOrderSlotValue(
|
||||
raw: string | undefined,
|
||||
): SequenceOrderSlotValue {
|
||||
const trimmed = (raw ?? "").trim()
|
||||
if (!trimmed) return defaultSequenceOrderSlotValue()
|
||||
try {
|
||||
return ensureMinItems(
|
||||
normalizeSequenceOrderValue(JSON.parse(trimmed) as unknown),
|
||||
)
|
||||
} catch {
|
||||
return defaultSequenceOrderSlotValue()
|
||||
}
|
||||
}
|
||||
|
||||
export function sequenceOrderItemHasValue(text: string): boolean {
|
||||
return text.length > 0
|
||||
}
|
||||
|
||||
export function sequenceOrderSlotHasContent(value: SequenceOrderSlotValue): boolean {
|
||||
return value.items.some((item) => sequenceOrderItemHasValue(item.text))
|
||||
}
|
||||
|
||||
export function finalizeSequenceOrderPayload(
|
||||
value: SequenceOrderSlotValue,
|
||||
): SequenceOrderSlotValue {
|
||||
const items = value.items
|
||||
.filter((item) => sequenceOrderItemHasValue(item.text))
|
||||
.map((item) => ({ id: item.id, text: item.text }))
|
||||
return {
|
||||
items,
|
||||
correct_order: items.map((item) => item.id),
|
||||
}
|
||||
}
|
||||
|
||||
export function addSequenceOrderItem(
|
||||
value: SequenceOrderSlotValue,
|
||||
maxItems = SEQUENCE_ORDER_MAX_ITEMS,
|
||||
): SequenceOrderSlotValue {
|
||||
if (value.items.length >= maxItems) return value
|
||||
const id = nextStableId(
|
||||
"s",
|
||||
value.items.map((item) => item.id),
|
||||
)
|
||||
const items = [...value.items, { id, text: "" }]
|
||||
return {
|
||||
items,
|
||||
correct_order: [...value.correct_order, id],
|
||||
}
|
||||
}
|
||||
|
||||
export function removeSequenceOrderItem(
|
||||
value: SequenceOrderSlotValue,
|
||||
index: number,
|
||||
): SequenceOrderSlotValue {
|
||||
if (value.items.length <= SEQUENCE_ORDER_MIN_ITEMS) return value
|
||||
const removed = value.items[index]
|
||||
if (!removed) return value
|
||||
const items = value.items.filter((_, itemIndex) => itemIndex !== index)
|
||||
return {
|
||||
items,
|
||||
correct_order: value.correct_order.filter((id) => id !== removed.id),
|
||||
}
|
||||
}
|
||||
|
||||
export function updateSequenceOrderItemText(
|
||||
value: SequenceOrderSlotValue,
|
||||
index: number,
|
||||
text: string,
|
||||
): SequenceOrderSlotValue {
|
||||
const items = [...value.items]
|
||||
if (!items[index]) return value
|
||||
items[index] = { ...items[index], text }
|
||||
return { ...value, items }
|
||||
}
|
||||
|
||||
export function reorderSequenceOrderItems(
|
||||
value: SequenceOrderSlotValue,
|
||||
fromIndex: number,
|
||||
toIndex: number,
|
||||
): SequenceOrderSlotValue {
|
||||
if (fromIndex === toIndex) return value
|
||||
const items = [...value.items]
|
||||
const [moved] = items.splice(fromIndex, 1)
|
||||
if (!moved) return value
|
||||
items.splice(toIndex, 0, moved)
|
||||
return {
|
||||
items,
|
||||
correct_order: items.map((item) => item.id),
|
||||
}
|
||||
}
|
||||
|
||||
export function limitsFromSchemaConfig(
|
||||
config?: Record<string, unknown>,
|
||||
): { minItems: number; maxItems: number } {
|
||||
const minRaw = config?.min_items
|
||||
const maxRaw = config?.max_items
|
||||
const minItems =
|
||||
typeof minRaw === "number" && Number.isFinite(minRaw) && minRaw >= 1
|
||||
? Math.floor(minRaw)
|
||||
: SEQUENCE_ORDER_MIN_ITEMS
|
||||
const maxItems =
|
||||
typeof maxRaw === "number" && Number.isFinite(maxRaw) && maxRaw >= minItems
|
||||
? Math.floor(maxRaw)
|
||||
: SEQUENCE_ORDER_MAX_ITEMS
|
||||
return { minItems, maxItems }
|
||||
}
|
||||
|
||||
export function validateSequenceOrderSlotValue(
|
||||
value: SequenceOrderSlotValue,
|
||||
config?: Record<string, unknown>,
|
||||
): string | null {
|
||||
const { minItems, maxItems } = limitsFromSchemaConfig(config)
|
||||
const filled = value.items.filter((item) => sequenceOrderItemHasValue(item.text))
|
||||
|
||||
if (filled.length < minItems) {
|
||||
return `Add at least ${minItems} sequence items.`
|
||||
}
|
||||
if (value.items.length > maxItems) {
|
||||
return `Too many items (max ${maxItems}).`
|
||||
}
|
||||
|
||||
const itemIds = new Set(value.items.map((item) => item.id))
|
||||
if (itemIds.size !== value.items.length) {
|
||||
return "Duplicate item id."
|
||||
}
|
||||
|
||||
if (value.correct_order.length !== value.items.length) {
|
||||
return "Correct order must include every item."
|
||||
}
|
||||
|
||||
for (const id of value.correct_order) {
|
||||
if (!itemIds.has(id)) {
|
||||
return `Invalid id "${id}" in correct order.`
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
63
src/lib/teamAuthStorage.ts
Normal file
63
src/lib/teamAuthStorage.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import type { TeamMemberSession } from "../types/auth.types"
|
||||
|
||||
const KEYS = {
|
||||
accessToken: "access_token",
|
||||
refreshToken: "refresh_token",
|
||||
role: "role",
|
||||
memberId: "member_id",
|
||||
} as const
|
||||
|
||||
export const TEAM_SESSION_UPDATED_EVENT = "yimaru:team-session-updated"
|
||||
|
||||
function dispatchSessionUpdated() {
|
||||
window.dispatchEvent(new Event(TEAM_SESSION_UPDATED_EVENT))
|
||||
}
|
||||
|
||||
export function loadTeamSession(): TeamMemberSession | null {
|
||||
const access_token = localStorage.getItem(KEYS.accessToken)
|
||||
const refresh_token = localStorage.getItem(KEYS.refreshToken)
|
||||
const team_role = localStorage.getItem(KEYS.role) ?? ""
|
||||
const memberIdRaw = localStorage.getItem(KEYS.memberId)
|
||||
if (!access_token || !refresh_token) return null
|
||||
const member_id = Number(memberIdRaw)
|
||||
if (!Number.isFinite(member_id)) return null
|
||||
return { access_token, refresh_token, member_id, team_role }
|
||||
}
|
||||
|
||||
export function saveTeamSession(session: TeamMemberSession): void {
|
||||
localStorage.setItem(KEYS.accessToken, session.access_token)
|
||||
localStorage.setItem(KEYS.refreshToken, session.refresh_token)
|
||||
localStorage.setItem(KEYS.role, session.team_role)
|
||||
localStorage.setItem(KEYS.memberId, String(session.member_id))
|
||||
dispatchSessionUpdated()
|
||||
}
|
||||
|
||||
export function saveTeamSessionFromLoginResult(result: {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
role: string
|
||||
memberId: number
|
||||
}): void {
|
||||
saveTeamSession({
|
||||
access_token: result.accessToken,
|
||||
refresh_token: result.refreshToken,
|
||||
team_role: result.role,
|
||||
member_id: result.memberId,
|
||||
})
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
return localStorage.getItem(KEYS.accessToken)
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem(KEYS.refreshToken)
|
||||
}
|
||||
|
||||
export function clearTeamSession(): void {
|
||||
localStorage.removeItem(KEYS.accessToken)
|
||||
localStorage.removeItem(KEYS.refreshToken)
|
||||
localStorage.removeItem(KEYS.role)
|
||||
localStorage.removeItem(KEYS.memberId)
|
||||
dispatchSessionUpdated()
|
||||
}
|
||||
|
|
@ -175,7 +175,7 @@ export function DashboardPage() {
|
|||
: null
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl">
|
||||
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
||||
<div className="mb-2 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="text-sm font-semibold text-grayScale-500">Dashboard</div>
|
||||
<AnalyticsTimeRangeFilter value={filters} onChange={setFilters} />
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
|||
import { login, loginWithGoogle } from "../../api/auth.api";
|
||||
import type { LoginRequest } from "../../types/auth.types";
|
||||
import type { LoginResult } from "../../api/auth.api";
|
||||
import { saveTeamSessionFromLoginResult, getAccessToken } from "../../lib/teamAuthStorage";
|
||||
import { toast } from "sonner";
|
||||
|
||||
declare global {
|
||||
|
|
@ -67,7 +68,7 @@ export function LoginPage() {
|
|||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const token = localStorage.getItem("access_token");
|
||||
const token = getAccessToken();
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get("password_changed") !== "1") return;
|
||||
|
|
@ -77,6 +78,14 @@ export function LoginPage() {
|
|||
setSearchParams({}, { replace: true });
|
||||
}, [searchParams, setSearchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get("account_inactive") !== "1") return;
|
||||
toast.error("Account inactive", {
|
||||
description: "Your team account is no longer active. Contact an administrator.",
|
||||
});
|
||||
setSearchParams({}, { replace: true });
|
||||
}, [searchParams, setSearchParams]);
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
|
@ -90,10 +99,7 @@ export function LoginPage() {
|
|||
|
||||
const storeTokensAndRedirect = useCallback(
|
||||
(result: LoginResult) => {
|
||||
localStorage.setItem("access_token", result.accessToken);
|
||||
localStorage.setItem("refresh_token", result.refreshToken);
|
||||
localStorage.setItem("role", result.role);
|
||||
localStorage.setItem("member_id", result.memberId.toString());
|
||||
saveTeamSessionFromLoginResult(result);
|
||||
toast.success("Welcome back!", {
|
||||
description: "You have signed in successfully.",
|
||||
});
|
||||
|
|
|
|||
|
|
@ -677,7 +677,7 @@ export function AddNewPracticePage() {
|
|||
<h3 className="text-xs font-semibold uppercase tracking-wider text-grayScale-500">
|
||||
Scoring & behavior
|
||||
</h3>
|
||||
<div className="mt-4 grid grid-cols-2 gap-4">
|
||||
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-grayScale-700">
|
||||
Passing score
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ export function AddVideoPage() {
|
|||
{/* Preview Card */}
|
||||
{videoFile && (
|
||||
<Card className="border-grayScale-200 overflow-hidden p-0 shadow-sm">
|
||||
<div className="border-b border-grayScale-100 px-6 py-4 sm:px-8">
|
||||
<div className="border-b border-grayScale-100 px-4 py-4 sm:px-6 sm:px-8">
|
||||
<h2 className="text-lg font-semibold tracking-tight text-grayScale-600">
|
||||
Video Preview
|
||||
</h2>
|
||||
|
|
|
|||
|
|
@ -324,7 +324,7 @@ export function AllCoursesPage() {
|
|||
|
||||
{/* Courses Table */}
|
||||
{filteredCourses.length > 0 ? (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Outlet } from "react-router-dom";
|
|||
|
||||
export function ContentManagementLayout() {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
|
||||
<div className="mx-auto w-full min-w-0 max-w-7xl px-0 py-4 sm:px-4 sm:py-6 lg:px-6">
|
||||
<div className="mb-8">
|
||||
<div className="mb-8 flex items-center gap-3">
|
||||
<div className="h-9 w-1 rounded-full bg-gradient-to-b from-brand-500 to-brand-600" />
|
||||
|
|
|
|||
|
|
@ -927,7 +927,7 @@ export function CourseDetailPage() {
|
|||
{deletingModule && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">
|
||||
Delete module
|
||||
</h2>
|
||||
|
|
|
|||
|
|
@ -1000,7 +1000,7 @@ export function CourseManagementPage() {
|
|||
>
|
||||
<DialogContent className="max-w-md rounded-[16px] border-none p-0 overflow-hidden">
|
||||
<div className="bg-white">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Delete Unit
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -1199,7 +1199,7 @@ export function CourseModuleDetailPage() {
|
|||
>
|
||||
<DialogContent className="max-w-md rounded-[16px] border-none p-0 overflow-hidden">
|
||||
<div className="bg-white">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Delete Lesson
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -349,7 +349,7 @@ export function CoursesPage() {
|
|||
</div>
|
||||
|
||||
{subCategories.length === 0 ? (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<div className="flex flex-col items-center justify-center px-6 py-16 text-center">
|
||||
<img src={practiceSrc} alt="" className="h-16 w-16" />
|
||||
<h3 className="mt-4 text-base font-semibold text-grayScale-600">No sub-categories yet</h3>
|
||||
|
|
@ -365,7 +365,7 @@ export function CoursesPage() {
|
|||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -577,7 +577,7 @@ export function CoursesPage() {
|
|||
{showModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-2xl animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">Add New Sub-category</h2>
|
||||
<button
|
||||
onClick={handleCloseModal}
|
||||
|
|
@ -666,7 +666,7 @@ export function CoursesPage() {
|
|||
{showEditModal && subCategoryToEdit && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-md animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">Edit Sub-category</h2>
|
||||
<button
|
||||
onClick={handleCloseEditModal}
|
||||
|
|
@ -750,7 +750,7 @@ export function CoursesPage() {
|
|||
{showDeleteModal && subCategoryToDelete && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">Delete Sub-category</h2>
|
||||
<button
|
||||
onClick={() => setShowDeleteModal(false)}
|
||||
|
|
|
|||
|
|
@ -1039,7 +1039,7 @@ export function HumanLanguageHierarchyPage() {
|
|||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-grayScale-600">Module naming</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={!createModuleUseDefaultNaming ? "default" : "outline"}
|
||||
|
|
@ -1076,7 +1076,7 @@ export function HumanLanguageHierarchyPage() {
|
|||
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-grayScale-600">Icon URL (optional)</label>
|
||||
<div className="mb-2 grid grid-cols-2 gap-2">
|
||||
<div className="mb-2 grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={createModuleIconSource === "url" ? "default" : "outline"}
|
||||
|
|
@ -1181,7 +1181,7 @@ export function HumanLanguageHierarchyPage() {
|
|||
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-grayScale-600">Icon URL (optional)</label>
|
||||
<div className="mb-2 grid grid-cols-2 gap-2">
|
||||
<div className="mb-2 grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={editModuleIconSource === "url" ? "default" : "outline"}
|
||||
|
|
|
|||
|
|
@ -427,7 +427,7 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
if (setsLoading) {
|
||||
return (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -468,7 +468,7 @@ export function HumanLanguageSubModulePage() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -572,7 +572,7 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
if (lessonsLoading) {
|
||||
return (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -612,7 +612,7 @@ export function HumanLanguageSubModulePage() {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -925,7 +925,7 @@ export function HumanLanguageSubModulePage() {
|
|||
|
||||
{activeTab === "videos" ? (
|
||||
videosLoading ? (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -955,7 +955,7 @@ export function HumanLanguageSubModulePage() {
|
|||
No intro videos on this sub-module yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
|
|||
|
|
@ -886,7 +886,7 @@ export function LearnEnglishPage() {
|
|||
{deletingProgram && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">Delete program</h2>
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -836,7 +836,7 @@ export function ModuleDetailPage() {
|
|||
{deletingLesson && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">
|
||||
Delete lesson
|
||||
</h2>
|
||||
|
|
|
|||
|
|
@ -796,7 +796,7 @@ export function PracticeQuestionsPage() {
|
|||
{showDeleteModal && questionToDelete && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Delete Question</h2>
|
||||
<button
|
||||
onClick={() => setShowDeleteModal(false)}
|
||||
|
|
@ -826,7 +826,7 @@ export function PracticeQuestionsPage() {
|
|||
{showAddModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Add New Question</h2>
|
||||
<button
|
||||
onClick={() => setShowAddModal(false)}
|
||||
|
|
@ -1042,7 +1042,7 @@ export function PracticeQuestionsPage() {
|
|||
{showEditModal && questionToEdit && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Edit Question</h2>
|
||||
<button
|
||||
onClick={() => setShowEditModal(false)}
|
||||
|
|
|
|||
|
|
@ -961,7 +961,7 @@ export function ProgramCoursesPage() {
|
|||
{deletingCourse && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm animate-in fade-in zoom-in-95 rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-5">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-bold text-grayScale-700">Delete course</h2>
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -949,7 +949,7 @@ export function ProgramDetailPage() {
|
|||
>
|
||||
<DialogContent className="max-w-md rounded-[16px] border-none p-0 overflow-hidden">
|
||||
<div className="bg-white">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Delete Course
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -194,7 +194,7 @@ export function QuestionTypeGroupDetailPage() {
|
|||
</div>
|
||||
|
||||
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
|
||||
<CardHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<CardHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<CardTitle className="text-base font-bold text-grayScale-900">
|
||||
Definitions in this group
|
||||
</CardTitle>
|
||||
|
|
|
|||
|
|
@ -432,7 +432,7 @@ export function QuestionTypeLibraryPage() {
|
|||
</Card>
|
||||
|
||||
<Card className="overflow-hidden rounded-2xl border border-grayScale-200 bg-white shadow-none">
|
||||
<CardHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<CardHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
|
||||
|
|
|
|||
|
|
@ -432,7 +432,7 @@ export function QuestionsPage() {
|
|||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -638,7 +638,7 @@ export function QuestionsPage() {
|
|||
{deleteDialogOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-md rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">
|
||||
Delete {pendingDeleteIds.length > 1 ? "Questions" : "Question"}
|
||||
</h2>
|
||||
|
|
@ -673,7 +673,7 @@ export function QuestionsPage() {
|
|||
{detailsOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-2xl rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Question Details</h2>
|
||||
<button
|
||||
onClick={() => setDetailsOpen(false)}
|
||||
|
|
@ -691,7 +691,7 @@ export function QuestionsPage() {
|
|||
<p className="text-xs font-semibold uppercase tracking-wider text-grayScale-500">Question</p>
|
||||
<p className="mt-1 text-sm text-grayScale-700">{detailData.question_text}</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
|
||||
<p><span className="font-medium">ID:</span> {detailData.id}</p>
|
||||
<p><span className="font-medium">Type:</span> {typeLabels[detailData.question_type] || detailData.question_type}</p>
|
||||
<p><span className="font-medium">Difficulty:</span> {detailData.difficulty_level || "—"}</p>
|
||||
|
|
@ -790,7 +790,7 @@ export function QuestionsPage() {
|
|||
{editOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Edit Question</h2>
|
||||
<button
|
||||
onClick={() => setEditOpen(false)}
|
||||
|
|
|
|||
|
|
@ -1657,7 +1657,7 @@ export function SpeakingPage() {
|
|||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-medium text-grayScale-500">Difficulty</label>
|
||||
<select
|
||||
|
|
@ -1790,7 +1790,7 @@ export function SpeakingPage() {
|
|||
<p className="text-xs font-medium text-grayScale-500">Question Text</p>
|
||||
<p className="mt-1 text-sm text-grayScale-700">{selectedQuestionDetail.question_text}</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-grayScale-500">Status</p>
|
||||
<p className="mt-1 text-grayScale-700">{selectedQuestionDetail.status || "—"}</p>
|
||||
|
|
|
|||
|
|
@ -910,7 +910,7 @@ export function SubModuleContentPage() {
|
|||
{showDeleteModal && practiceToDelete && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Delete Practice</h2>
|
||||
<button
|
||||
onClick={() => setShowDeleteModal(false)}
|
||||
|
|
@ -941,7 +941,7 @@ export function SubModuleContentPage() {
|
|||
{showEditPracticeModal && practiceToEdit && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-md rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Edit Practice</h2>
|
||||
<button
|
||||
onClick={() => setShowEditPracticeModal(false)}
|
||||
|
|
@ -999,7 +999,7 @@ export function SubModuleContentPage() {
|
|||
{showAddVideoModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-lg rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Add Video</h2>
|
||||
<button
|
||||
onClick={() => { setShowAddVideoModal(false); setVideoFile(null) }}
|
||||
|
|
@ -1040,7 +1040,7 @@ export function SubModuleContentPage() {
|
|||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">File Size (bytes)</label>
|
||||
<Input
|
||||
|
|
@ -1062,7 +1062,7 @@ export function SubModuleContentPage() {
|
|||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Resolution</label>
|
||||
<Input
|
||||
|
|
@ -1081,7 +1081,7 @@ export function SubModuleContentPage() {
|
|||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Visibility</label>
|
||||
<select
|
||||
|
|
@ -1130,7 +1130,7 @@ export function SubModuleContentPage() {
|
|||
{showEditVideoModal && videoToEdit && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-md rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Edit Video</h2>
|
||||
<button
|
||||
onClick={() => setShowEditVideoModal(false)}
|
||||
|
|
@ -1188,7 +1188,7 @@ export function SubModuleContentPage() {
|
|||
{showDeleteVideoModal && videoToDelete && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Delete Video</h2>
|
||||
<button
|
||||
onClick={() => setShowDeleteVideoModal(false)}
|
||||
|
|
@ -1219,7 +1219,7 @@ export function SubModuleContentPage() {
|
|||
{showPreviewModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-2xl rounded-2xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">
|
||||
{previewVideo?.name ?? "Video Preview"}
|
||||
|
|
|
|||
|
|
@ -1145,7 +1145,7 @@ export function UnitManagementPage() {
|
|||
>
|
||||
<DialogContent className="max-w-md rounded-[16px] border-none p-0 overflow-hidden">
|
||||
<div className="bg-white">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Delete Module
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ export function PracticeActionChoiceDialog({
|
|||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg rounded-2xl border-grayScale-200 p-0 sm:max-w-lg">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5 text-left">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6 text-left">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Add practice
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ export function QuestionTypeDefinitionPracticesDialog({
|
|||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-hidden rounded-2xl border-grayScale-200 p-0 sm:max-w-3xl">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5 text-left">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6 text-left">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg font-bold text-grayScale-900">
|
||||
<GraduationCap className="h-5 w-5 text-brand-600 shrink-0" aria-hidden />
|
||||
Practices using this definition
|
||||
|
|
|
|||
|
|
@ -135,7 +135,7 @@ export function QuestionTypeGroupFormDialog({
|
|||
className="min-h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium text-grayScale-700">Display order</label>
|
||||
<Input
|
||||
|
|
|
|||
|
|
@ -188,7 +188,7 @@ export function PracticeSequentialReview({
|
|||
) : null}
|
||||
|
||||
<Card className="overflow-hidden border-grayScale-200/80 p-0 shadow-sm">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h3 className="font-semibold text-grayScale-900">Basic Information</h3>
|
||||
{onEditContext ? (
|
||||
<button
|
||||
|
|
@ -295,7 +295,7 @@ export function PracticeSequentialReview({
|
|||
<Card className="overflow-hidden border-grayScale-200/80 p-0 shadow-sm">
|
||||
<div className="grid md:grid-cols-2 md:divide-x md:divide-grayScale-100">
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center gap-2.5 border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center gap-2.5 border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h3 className="font-semibold text-grayScale-900">Questions</h3>
|
||||
<span className="flex h-6 min-w-6 items-center justify-center rounded-full bg-grayScale-100 px-2 text-xs font-semibold text-grayScale-500">
|
||||
{filledQuestions.length}
|
||||
|
|
@ -332,7 +332,7 @@ export function PracticeSequentialReview({
|
|||
</div>
|
||||
|
||||
<div className="flex flex-col border-t border-grayScale-100 md:border-t-0">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<h3 className="font-semibold text-grayScale-900">Answers</h3>
|
||||
<span className="flex h-6 min-w-6 items-center justify-center rounded-full bg-grayScale-100 px-2 text-xs font-semibold text-grayScale-500">
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@ import { useCallback, useEffect, useState } from "react";
|
|||
import {
|
||||
Search,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
AlertCircle,
|
||||
Eye,
|
||||
RefreshCw,
|
||||
|
|
@ -43,7 +41,7 @@ import {
|
|||
DialogDescription,
|
||||
} from "../../components/ui/dialog";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination";
|
||||
import { TablePagination } from "../../components/admin/TablePagination";
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon";
|
||||
import {
|
||||
getIssues,
|
||||
|
|
@ -336,22 +334,6 @@ export function IssuesPage() {
|
|||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||
const safePage = Math.min(page, pageCount);
|
||||
const paginatedIssues = filteredIssues.slice((safePage - 1) * pageSize, safePage * pageSize);
|
||||
const handlePrev = () => safePage > 1 && setPage(safePage - 1);
|
||||
const handleNext = () => safePage < pageCount && setPage(safePage + 1);
|
||||
|
||||
const getPageNumbers = () => {
|
||||
const pages: (number | string)[] = [];
|
||||
if (pageCount <= 7) {
|
||||
for (let i = 1; i <= pageCount; i++) pages.push(i);
|
||||
} else {
|
||||
pages.push(1, 2, 3);
|
||||
if (safePage > 4) pages.push("...");
|
||||
if (safePage > 3 && safePage < pageCount - 2) pages.push(safePage);
|
||||
if (safePage < pageCount - 3) pages.push("...");
|
||||
pages.push(pageCount);
|
||||
}
|
||||
return pages;
|
||||
};
|
||||
|
||||
const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1;
|
||||
const endEntry = Math.min(safePage * pageSize, totalCount);
|
||||
|
|
@ -364,14 +346,14 @@ export function IssuesPage() {
|
|||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="admin-page-header">
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-2xl font-bold text-grayScale-600">Issue Reports</h1>
|
||||
<p className="text-sm text-grayScale-400">
|
||||
Review and manage user-reported issues across the platform.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="admin-page-actions">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
|
|
@ -495,15 +477,15 @@ export function IssuesPage() {
|
|||
</AdminFiltersPanel>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>SUBJECT</TableHead>
|
||||
<TableHead>TYPE</TableHead>
|
||||
<TableHead className="hidden md:table-cell">TYPE</TableHead>
|
||||
<TableHead>STATUS</TableHead>
|
||||
<TableHead>REPORTER</TableHead>
|
||||
<TableHead>CREATED</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">REPORTER</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">CREATED</TableHead>
|
||||
<TableHead className="text-right">ACTIONS</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
|
|
@ -557,7 +539,7 @@ export function IssuesPage() {
|
|||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell className="hidden md:table-cell">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium",
|
||||
|
|
@ -591,7 +573,7 @@ export function IssuesPage() {
|
|||
<ChevronDown className="absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 pointer-events-none opacity-50" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-grayScale-100 text-grayScale-500">
|
||||
<User className="h-3.5 w-3.5" />
|
||||
|
|
@ -606,7 +588,7 @@ export function IssuesPage() {
|
|||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<TableCell className="hidden sm:table-cell">
|
||||
<div>
|
||||
<p className="text-sm text-grayScale-600">
|
||||
{formatDate(issue.created_at)}
|
||||
|
|
@ -643,82 +625,19 @@ export function IssuesPage() {
|
|||
</TableBody>
|
||||
</Table>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3 text-sm text-grayScale-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Showing</span>
|
||||
<span className="font-medium text-grayScale-600">
|
||||
{startEntry}–{endEntry}
|
||||
</span>
|
||||
<span>of</span>
|
||||
<span className="font-medium text-grayScale-600">{totalCount}</span>
|
||||
<span className="mr-4">entries</span>
|
||||
<span className="border-l pl-4">Rows per page</span>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => {
|
||||
setPageSize(Number(e.target.value));
|
||||
setPage(1);
|
||||
}}
|
||||
className="h-8 appearance-none rounded-md border bg-white pl-2 pr-7 text-sm font-medium text-grayScale-600 focus:outline-none"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={handlePrev}
|
||||
disabled={safePage === 1}
|
||||
className={cn(
|
||||
"h-8 w-8 flex items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
safePage === 1 && "opacity-50 cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
{getPageNumbers().map((n, idx) =>
|
||||
typeof n === "string" ? (
|
||||
<span key={`ellipsis-${idx}`} className="px-2 text-grayScale-400">
|
||||
...
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
onClick={() => setPage(n)}
|
||||
className={cn(
|
||||
"h-8 w-8 rounded-md border text-sm font-medium",
|
||||
n === safePage
|
||||
? "border-brand-500 bg-brand-500 text-white"
|
||||
: "bg-white text-grayScale-600 hover:bg-grayScale-50"
|
||||
)}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleNext}
|
||||
disabled={safePage === pageCount}
|
||||
className={cn(
|
||||
"h-8 w-8 flex items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
safePage === pageCount && "opacity-50 cursor-not-allowed"
|
||||
)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<TablePagination
|
||||
startEntry={startEntry}
|
||||
endEntry={endEntry}
|
||||
totalCount={totalCount}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={(size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
}}
|
||||
currentPage={safePage}
|
||||
totalPages={pageCount}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Detail Dialog */}
|
||||
|
|
@ -779,7 +698,7 @@ export function IssuesPage() {
|
|||
</div>
|
||||
|
||||
{/* Detail grid */}
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
|
||||
<DetailItem
|
||||
icon={<User className="h-4 w-4" />}
|
||||
label="Reporter"
|
||||
|
|
|
|||
429
src/pages/notifications/AllNotificationsPage.tsx
Normal file
429
src/pages/notifications/AllNotificationsPage.tsx
Normal file
|
|
@ -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<Notification[]>([])
|
||||
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<Notification | null>(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 (
|
||||
<div className="mx-auto w-full min-w-0 max-w-6xl space-y-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-grayScale-500">Notifications</p>
|
||||
<h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-grayScale-800">
|
||||
<List className="h-6 w-6 text-brand-500" />
|
||||
All notifications
|
||||
</h1>
|
||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||
Browse every notification sent across the platform. Filter by channel, type, recipient,
|
||||
read state, or date range.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" className="shrink-0" asChild>
|
||||
<Link to="/notifications">My inbox</Link>
|
||||
</Button>
|
||||
<Button variant="outline" className="shrink-0" disabled={loading} onClick={() => void load()}>
|
||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
summary={
|
||||
loading
|
||||
? "Loading…"
|
||||
: `${totalCount} notification${totalCount === 1 ? "" : "s"}`
|
||||
}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Select
|
||||
value={channelFilter}
|
||||
onChange={(e) => setChannelFilter(e.target.value as typeof channelFilter)}
|
||||
>
|
||||
{CHANNEL_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<Select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)}>
|
||||
<option value="">All types</option>
|
||||
{IN_APP_TYPES.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={readFilter}
|
||||
onChange={(e) => setReadFilter(e.target.value as typeof readFilter)}
|
||||
>
|
||||
{READ_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder="Recipient user ID"
|
||||
value={userIdFilter}
|
||||
onChange={(e) => setUserIdFilter(e.target.value)}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={afterFilter}
|
||||
onChange={(e) => setAfterFilter(e.target.value)}
|
||||
aria-label="Created after"
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={beforeFilter}
|
||||
onChange={(e) => setBeforeFilter(e.target.value)}
|
||||
aria-label="Created before"
|
||||
/>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="space-y-4 p-4 sm:p-6">
|
||||
{loading && (
|
||||
<div className="flex items-center justify-center py-16 text-sm text-grayScale-500">
|
||||
<SpinnerIcon className="mr-2 h-5 w-5" alt="" />
|
||||
Loading notifications…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 p-6 text-center text-sm text-destructive">
|
||||
Could not load notifications.
|
||||
<Button variant="outline" size="sm" className="ml-3" onClick={() => void load()}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && rows.length === 0 && (
|
||||
<div className="rounded-lg border border-dashed border-grayScale-200 bg-grayScale-50/50 py-16 text-center">
|
||||
<Bell className="mx-auto mb-3 h-8 w-8 text-grayScale-300" />
|
||||
<p className="text-sm font-medium text-grayScale-600">No notifications found</p>
|
||||
<p className="mt-1 text-xs text-grayScale-400">
|
||||
Try adjusting your filters or send a notification from the composer.
|
||||
</p>
|
||||
<Button className="mt-4" size="sm" asChild>
|
||||
<Link to="/notifications/create">Send notification</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && rows.length > 0 && (
|
||||
<>
|
||||
<div className="overflow-x-auto rounded-lg border border-grayScale-100">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Recipient</TableHead>
|
||||
<TableHead>Title / message</TableHead>
|
||||
<TableHead>Channel</TableHead>
|
||||
<TableHead className="hidden md:table-cell">Type</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Level</TableHead>
|
||||
<TableHead>Read</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">Delivery</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">Sent</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((notification) => (
|
||||
<TableRow
|
||||
key={notification.id}
|
||||
className="cursor-pointer hover:bg-grayScale-50"
|
||||
onClick={() => void openDetail(notification)}
|
||||
>
|
||||
<TableCell className="max-w-[140px] text-xs text-grayScale-600">
|
||||
<p className="truncate font-medium">{recipientLabel(notification)}</p>
|
||||
<p className="truncate font-mono text-[10px] text-grayScale-400">
|
||||
{notification.id}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px]">
|
||||
<p className="truncate text-sm font-medium text-grayScale-700">
|
||||
{getNotificationTitle(notification) || "—"}
|
||||
</p>
|
||||
<p className="truncate text-xs text-grayScale-400">
|
||||
{getNotificationMessage(notification) || "—"}
|
||||
</p>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs capitalize text-grayScale-600">
|
||||
{channelLabel(notification.delivery_channel) || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-xs text-grayScale-600 md:table-cell">
|
||||
{formatNotificationTypeLabel(notification.type)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden lg:table-cell">
|
||||
<Badge
|
||||
variant={getNotificationLevelBadge(notification.level)}
|
||||
className="text-[10px]"
|
||||
>
|
||||
{notification.level || "—"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={notification.is_read ? "secondary" : "default"}>
|
||||
{notification.is_read ? "Read" : "Unread"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-xs capitalize text-grayScale-500 sm:table-cell">
|
||||
{notification.delivery_status || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-xs text-grayScale-500 sm:table-cell">
|
||||
{formatNotificationTimestamp(notification.timestamp)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
{!loading && !error && totalCount > 0 && (
|
||||
<TablePagination
|
||||
startEntry={startEntry}
|
||||
endEntry={endEntry}
|
||||
totalCount={totalCount}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={(size) => {
|
||||
setPageSize(size)
|
||||
setPage(1)
|
||||
}}
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={setPage}
|
||||
disabled={loading}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<NotificationDetailDialog
|
||||
open={detailOpen}
|
||||
onOpenChange={setDetailOpen}
|
||||
notification={selectedNotification}
|
||||
loading={detailLoading}
|
||||
error={detailError}
|
||||
onRetry={
|
||||
selectedNotification
|
||||
? () => void openDetail(selectedNotification)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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<NotificationChannel>("push")
|
||||
const [audienceMode, setAudienceMode] = useState<AudienceMode>("role")
|
||||
const [audienceMode, setAudienceMode] = useState<NotificationAudienceMode>("platform_role")
|
||||
const [sendMode, setSendMode] = useState<SendMode>("now")
|
||||
const [platformRole, setPlatformRole] = useState<PlatformRole>("STUDENT")
|
||||
const [teamRole, setTeamRole] = useState<TeamRole>("ADMIN")
|
||||
const [users, setUsers] = useState<UserApiDTO[]>([])
|
||||
const [teamMembers, setTeamMembers] = useState<TeamMember[]>([])
|
||||
const [recipientsLoading, setRecipientsLoading] = useState(false)
|
||||
const [teamRecipientsLoading, setTeamRecipientsLoading] = useState(false)
|
||||
const [selectedUserIds, setSelectedUserIds] = useState<number[]>([])
|
||||
const [selectedTeamMemberIds, setSelectedTeamMemberIds] = useState<number[]>([])
|
||||
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<Record<string, string>>({})
|
||||
const [emailTemplates, setEmailTemplates] = useState<EmailTemplate[]>([])
|
||||
const [emailTemplatesLoading, setEmailTemplatesLoading] = useState(false)
|
||||
const [sendSummary, setSendSummary] = useState<BulkSendSummary | null>(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<typeof sendBulkInApp>[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() {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{sendSummary ? (
|
||||
<BulkSendSummaryPanel summary={sendSummary} onDismiss={() => setSendSummary(null)} />
|
||||
) : null}
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="grid gap-4 md:grid-cols-[minmax(0,1.5fr)_minmax(0,1.1fr)]"
|
||||
|
|
@ -406,8 +584,8 @@ export function CreateNotificationPage() {
|
|||
type="button"
|
||||
onClick={() => {
|
||||
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)"}
|
||||
</p>
|
||||
<FileUpload
|
||||
value={attachment}
|
||||
accept={channel === "push" ? "image/*" : undefined}
|
||||
onFileSelect={setAttachment}
|
||||
label={channel === "push" ? "Upload notification image" : "Upload attachment"}
|
||||
|
|
@ -615,36 +794,48 @@ export function CreateNotificationPage() {
|
|||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<Card
|
||||
className={cn(
|
||||
"border shadow-none",
|
||||
audienceMode === "platform_role" ||
|
||||
audienceMode === "platform_selected" ||
|
||||
audienceMode === "direct"
|
||||
? "border-brand-200 ring-1 ring-brand-100"
|
||||
: "border-grayScale-100",
|
||||
)}
|
||||
>
|
||||
<CardContent className="space-y-3 p-4">
|
||||
<p className="text-xs font-semibold text-grayScale-600">Audience</p>
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-grayScale-600">Platform recipients</p>
|
||||
<p className="text-[10px] text-grayScale-400">Learners and platform users</p>
|
||||
</div>
|
||||
<div className="inline-flex flex-wrap gap-1 rounded-full border border-grayScale-200 bg-grayScale-50 p-0.5 text-xs font-medium">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAudienceMode("role")}
|
||||
onClick={() => setAudienceMode("platform_role")}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1.5 transition-colors",
|
||||
audienceMode === "role"
|
||||
audienceMode === "platform_role"
|
||||
? "bg-brand-500 text-white shadow-sm"
|
||||
: "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
By role
|
||||
Platform role
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setAudienceMode("selected")
|
||||
setAudienceMode("platform_selected")
|
||||
setUserSearchQuery("")
|
||||
}}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1.5 transition-colors",
|
||||
audienceMode === "selected"
|
||||
audienceMode === "platform_selected"
|
||||
? "bg-brand-500 text-white shadow-sm"
|
||||
: "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
Selected users
|
||||
Platform users
|
||||
</button>
|
||||
{supportsDirect && (
|
||||
<button
|
||||
|
|
@ -662,7 +853,7 @@ export function CreateNotificationPage() {
|
|||
)}
|
||||
</div>
|
||||
|
||||
{audienceMode === "role" && (
|
||||
{audienceMode === "platform_role" && (
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-grayScale-500">
|
||||
Platform role
|
||||
|
|
@ -678,7 +869,7 @@ export function CreateNotificationPage() {
|
|||
))}
|
||||
</Select>
|
||||
<p className="mt-1 text-[10px] text-grayScale-400">
|
||||
Sends to all users with this platform role.
|
||||
Sends to all learners/users with this platform role.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -703,19 +894,16 @@ export function CreateNotificationPage() {
|
|||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{audienceMode === "selected" && (
|
||||
<Card className="border border-grayScale-100 shadow-none">
|
||||
<CardContent className="space-y-2 p-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs font-semibold text-grayScale-600">Selected users</p>
|
||||
<span className="text-[10px] text-grayScale-400">
|
||||
{selectedUsers.length} selected
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-lg border border-grayScale-100 bg-grayScale-50/60">
|
||||
{audienceMode === "platform_selected" && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs font-medium text-grayScale-500">Select users</p>
|
||||
<span className="text-[10px] text-grayScale-400">
|
||||
{selectedUsers.length} selected
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-lg border border-grayScale-100 bg-grayScale-50/60">
|
||||
<div className="sticky top-0 z-10 space-y-2 border-b border-grayScale-100 bg-grayScale-50/95 p-2 backdrop-blur-sm">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-grayScale-400" />
|
||||
|
|
@ -810,6 +998,173 @@ export function CreateNotificationPage() {
|
|||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{supportsTeamTargeting && (
|
||||
<Card
|
||||
className={cn(
|
||||
"border shadow-none",
|
||||
audienceMode === "team_role" || audienceMode === "team_selected"
|
||||
? "border-brand-200 ring-1 ring-brand-100"
|
||||
: "border-grayScale-100",
|
||||
)}
|
||||
>
|
||||
<CardContent className="space-y-3 p-4">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-grayScale-600">Team recipients</p>
|
||||
<p className="text-[10px] text-grayScale-400">Staff and team members</p>
|
||||
</div>
|
||||
<div className="inline-flex flex-wrap gap-1 rounded-full border border-grayScale-200 bg-grayScale-50 p-0.5 text-xs font-medium">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAudienceMode("team_role")}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1.5 transition-colors",
|
||||
audienceMode === "team_role"
|
||||
? "bg-brand-500 text-white shadow-sm"
|
||||
: "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
Team role
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setAudienceMode("team_selected")
|
||||
setTeamSearchQuery("")
|
||||
}}
|
||||
className={cn(
|
||||
"rounded-full px-3 py-1.5 transition-colors",
|
||||
audienceMode === "team_selected"
|
||||
? "bg-brand-500 text-white shadow-sm"
|
||||
: "text-grayScale-500 hover:text-grayScale-700",
|
||||
)}
|
||||
>
|
||||
Team members
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{audienceMode === "team_role" && (
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-medium text-grayScale-500">
|
||||
Team role
|
||||
</label>
|
||||
<Select
|
||||
value={teamRole}
|
||||
onChange={(e) => setTeamRole(e.target.value as TeamRole)}
|
||||
>
|
||||
{TEAM_ROLES.map((r) => (
|
||||
<option key={r.value} value={r.value}>
|
||||
{r.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<p className="mt-1 text-[10px] text-grayScale-400">
|
||||
Sends to all staff with this team role.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{audienceMode === "team_selected" && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs font-medium text-grayScale-500">Select team members</p>
|
||||
<span className="text-[10px] text-grayScale-400">
|
||||
{selectedTeamMemberIds.length} selected
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-lg border border-grayScale-100 bg-grayScale-50/60">
|
||||
<div className="sticky top-0 z-10 space-y-2 border-b border-grayScale-100 bg-grayScale-50/95 p-2 backdrop-blur-sm">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-grayScale-400" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder="Search by name or email…"
|
||||
value={teamSearchQuery}
|
||||
onChange={(e) => setTeamSearchQuery(e.target.value)}
|
||||
className="h-8 border-grayScale-200 bg-white pl-8 text-xs"
|
||||
disabled={teamRecipientsLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={teamRecipientsLoading || filteredTeamMembers.length === 0}
|
||||
onClick={() => {
|
||||
const ids = filteredTeamMembers.map((m) => m.id)
|
||||
setSelectedTeamMemberIds((prev) => [...new Set([...prev, ...ids])])
|
||||
}}
|
||||
className="text-[11px] font-medium text-brand-600 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
Select all
|
||||
</button>
|
||||
<span className="text-grayScale-300">·</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={teamRecipientsLoading || filteredSelectedTeamCount === 0}
|
||||
onClick={() => {
|
||||
const filteredIds = new Set(filteredTeamMembers.map((m) => m.id))
|
||||
setSelectedTeamMemberIds((prev) =>
|
||||
prev.filter((id) => !filteredIds.has(id)),
|
||||
)
|
||||
}}
|
||||
className="text-[11px] font-medium text-grayScale-500 hover:text-grayScale-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
Unselect all
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-64 space-y-1.5 overflow-y-auto p-2">
|
||||
{teamRecipientsLoading && (
|
||||
<div className="flex items-center justify-center py-6 text-xs text-grayScale-400">
|
||||
<SpinnerIcon className="mr-2 h-4 w-4" alt="" />
|
||||
Loading team members…
|
||||
</div>
|
||||
)}
|
||||
{!teamRecipientsLoading && teamMembers.length === 0 && (
|
||||
<div className="py-4 text-center text-xs text-grayScale-400">
|
||||
No team members available to select.
|
||||
</div>
|
||||
)}
|
||||
{!teamRecipientsLoading &&
|
||||
filteredTeamMembers.map((member) => {
|
||||
const checked = selectedTeamMemberIds.includes(member.id)
|
||||
return (
|
||||
<label
|
||||
key={member.id}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs",
|
||||
checked ? "bg-brand-50 text-brand-700" : "hover:bg-grayScale-100",
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-3.5 w-3.5 rounded border-grayScale-300"
|
||||
checked={checked}
|
||||
onChange={(e) => {
|
||||
setSelectedTeamMemberIds((prev) =>
|
||||
e.target.checked
|
||||
? [...prev, member.id]
|
||||
: prev.filter((id) => id !== member.id),
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<span className="truncate">
|
||||
{member.first_name} {member.last_name}
|
||||
<span className="ml-1 text-[10px] text-grayScale-400">
|
||||
· {member.email || `ID ${member.id}`}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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<string>()
|
||||
|
||||
const onRealtime = (event: Event) => {
|
||||
const notification = (event as CustomEvent<Notification>).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 */}
|
||||
<div className="mb-5">
|
||||
<div className="mb-1 text-sm font-semibold text-grayScale-500">Notifications</div>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2 sm:gap-3">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">My Notifications</h1>
|
||||
{totalCount > 0 && <Badge variant="secondary">{totalCount}</Badge>}
|
||||
{globalUnread > 0 && <Badge variant="default">{globalUnread} unread</Badge>}
|
||||
|
|
@ -403,7 +437,7 @@ export function NotificationsPage() {
|
|||
|
||||
{/* Bulk actions */}
|
||||
{!loading && !error && (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
className="bg-brand-500 text-white hover:bg-brand-600"
|
||||
|
|
@ -787,78 +821,19 @@ export function NotificationsPage() {
|
|||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3 text-sm text-grayScale-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Showing</span>
|
||||
<span className="font-medium text-grayScale-600">
|
||||
{startEntry}-{endEntry}
|
||||
</span>
|
||||
<span>of</span>
|
||||
<span className="font-medium text-grayScale-600">{totalCount}</span>
|
||||
<span className="mr-4">entries</span>
|
||||
<span className="border-l pl-4">Rows per page</span>
|
||||
<div className="relative">
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => {
|
||||
setPageSize(Number(e.target.value))
|
||||
setOffset(0)
|
||||
}}
|
||||
className="h-8 appearance-none rounded-md border bg-white pl-2 pr-7 text-sm font-medium text-grayScale-600 focus:outline-none"
|
||||
>
|
||||
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>
|
||||
{size}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-grayScale-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => currentPage > 1 && setOffset(Math.max(0, offset - pageSize))}
|
||||
disabled={currentPage <= 1}
|
||||
className={cn(
|
||||
"flex h-8 w-8 items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
currentPage <= 1 && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
{getPageNumbers().map((n, idx) =>
|
||||
typeof n === "string" ? (
|
||||
<span key={`ellipsis-${idx}`} className="px-2 text-grayScale-400">
|
||||
...
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
onClick={() => setOffset((n - 1) * pageSize)}
|
||||
className={cn(
|
||||
"h-8 w-8 rounded-md border text-sm font-medium",
|
||||
n === currentPage
|
||||
? "border-brand-500 bg-brand-500 text-white"
|
||||
: "bg-white text-grayScale-600 hover:bg-grayScale-50",
|
||||
)}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
<button
|
||||
onClick={() => currentPage < totalPages && setOffset(offset + pageSize)}
|
||||
disabled={currentPage >= totalPages}
|
||||
className={cn(
|
||||
"flex h-8 w-8 items-center justify-center rounded-md border bg-white text-grayScale-500",
|
||||
currentPage >= totalPages && "cursor-not-allowed opacity-50",
|
||||
)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<TablePagination
|
||||
startEntry={startEntry}
|
||||
endEntry={endEntry}
|
||||
totalCount={totalCount}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={(size) => {
|
||||
setPageSize(size)
|
||||
setOffset(0)
|
||||
}}
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={(page) => setOffset((page - 1) * pageSize)}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
|
|
@ -870,8 +845,8 @@ export function NotificationsPage() {
|
|||
loading={detailLoading}
|
||||
error={detailError}
|
||||
onRetry={
|
||||
selectedNotificationId
|
||||
? () => void loadNotificationDetail(selectedNotificationId)
|
||||
selectedNotification
|
||||
? () => void loadNotificationDetail(selectedNotification)
|
||||
: undefined
|
||||
}
|
||||
onDelete={
|
||||
|
|
|
|||
290
src/pages/notifications/components/BulkSendSummaryPanel.tsx
Normal file
290
src/pages/notifications/components/BulkSendSummaryPanel.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="rounded-lg border border-grayScale-100 bg-white px-3 py-2.5">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
{label}
|
||||
</p>
|
||||
<p className={cn("mt-0.5 text-xl font-semibold tabular-nums", valueClass)}>{value}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<Card className={cn("border shadow-sm", borderTone)}>
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<span
|
||||
className={cn(
|
||||
"mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white shadow-sm",
|
||||
statusIconClass,
|
||||
)}
|
||||
>
|
||||
<StatusIcon className="h-5 w-5" />
|
||||
</span>
|
||||
<div className="min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h2 className="text-sm font-semibold text-grayScale-800">{headline}</h2>
|
||||
<Badge variant={isImmediate ? (hasFailures ? "warning" : "success") : "info"}>
|
||||
{isImmediate ? "Delivered" : "Scheduled"}
|
||||
</Badge>
|
||||
<Badge variant="secondary">{channelLabel(summary.channel)}</Badge>
|
||||
{!isImmediate && summary.status ? (
|
||||
<Badge variant="secondary">{summary.status}</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-xs text-grayScale-500">
|
||||
{isImmediate
|
||||
? `Completed at ${completedLabel}`
|
||||
: `Scheduled for ${formatScheduledAtLabel(summary.scheduledAt)} · created ${completedLabel}`}
|
||||
</p>
|
||||
{summary.apiMessage ? (
|
||||
<p className="text-xs text-grayScale-600">{summary.apiMessage}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-grayScale-400 hover:text-grayScale-700"
|
||||
onClick={onDismiss}
|
||||
aria-label="Dismiss summary"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="rounded-lg border border-grayScale-100 bg-white/80 px-3 py-2.5">
|
||||
<p className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
<Users className="h-3 w-3" />
|
||||
Audience
|
||||
</p>
|
||||
<p className="mt-1 text-sm font-medium text-grayScale-800">{summary.audienceLabel}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-grayScale-100 bg-white/80 px-3 py-2.5">
|
||||
<p className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
<Send className="h-3 w-3" />
|
||||
Content
|
||||
</p>
|
||||
<p className="mt-1 truncate text-sm font-medium text-grayScale-800">
|
||||
{summary.titlePreview || "—"}
|
||||
</p>
|
||||
<p className="truncate text-xs text-grayScale-500">{summary.messagePreview || "—"}</p>
|
||||
{!isImmediate && summary.emailTemplateSlug ? (
|
||||
<p className="mt-1 text-[10px] text-grayScale-400">
|
||||
Template: {summary.emailTemplateSlug}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isImmediate ? (
|
||||
<>
|
||||
{isPush ? (
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<StatBlock label="Target users" value={summary.targetUsers ?? 0} />
|
||||
<StatBlock
|
||||
label="Devices targeted"
|
||||
value={summary.devicesTargeted ?? 0}
|
||||
/>
|
||||
<StatBlock label="Devices sent" value={summary.sent} tone="success" />
|
||||
<StatBlock
|
||||
label="Devices failed"
|
||||
value={summary.failed}
|
||||
tone={summary.failed > 0 ? "danger" : "muted"}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<StatBlock label="Total recipients" value={summary.total} />
|
||||
<StatBlock label="Sent" value={summary.sent} tone="success" />
|
||||
<StatBlock
|
||||
label="Failed"
|
||||
value={summary.failed}
|
||||
tone={summary.failed > 0 ? "danger" : "muted"}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{summary.total > 0 ? (
|
||||
<div className="space-y-1">
|
||||
<div className="flex h-2 overflow-hidden rounded-full bg-grayScale-100">
|
||||
{summary.sent > 0 ? (
|
||||
<div
|
||||
className="bg-mint-500 transition-all"
|
||||
style={{ width: `${(summary.sent / progressTotal) * 100}%` }}
|
||||
/>
|
||||
) : null}
|
||||
{summary.failed > 0 ? (
|
||||
<div
|
||||
className="bg-destructive transition-all"
|
||||
style={{ width: `${(summary.failed / progressTotal) * 100}%` }}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-[10px] text-grayScale-400">
|
||||
{isPush
|
||||
? `${summary.sent} of ${summary.devicesTargeted ?? summary.total} device deliveries succeeded`
|
||||
: `${summary.sent} of ${summary.total} delivered`}
|
||||
{summary.failed > 0 ? ` · ${summary.failed} failed` : ""}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
{isPush && summary.pushImage ? (
|
||||
<p className="truncate text-[10px] text-grayScale-400">
|
||||
Image: {summary.pushImage}
|
||||
</p>
|
||||
) : null}
|
||||
{isPush &&
|
||||
(summary.devicesTargeted ?? 0) === 0 &&
|
||||
(summary.targetUsers ?? 0) > 0 ? (
|
||||
<p className="flex items-start gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
|
||||
<Smartphone className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
Targeted users have no active FCM device tokens. They must register a device
|
||||
from the learner app while logged in.
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<StatBlock label="Job ID" value={`#${summary.jobId}`} />
|
||||
<div className="rounded-lg border border-grayScale-100 bg-white px-3 py-2.5">
|
||||
<p className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-grayScale-400">
|
||||
<CalendarClock className="h-3 w-3" />
|
||||
Scheduled at
|
||||
</p>
|
||||
<p className="mt-0.5 text-sm font-semibold text-grayScale-800">
|
||||
{formatScheduledAtLabel(summary.scheduledAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-grayScale-100/80 pt-3">
|
||||
<p className="text-[11px] text-grayScale-400">
|
||||
This summary is temporary and clears when you dismiss it or send again.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!isImmediate ? (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link to="/notifications/scheduled">View scheduled jobs</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" variant="outline" size="sm" onClick={onDismiss}>
|
||||
Dismiss
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
|
@ -251,7 +251,7 @@ export function PersonasPage() {
|
|||
}
|
||||
/>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
|
|||
|
|
@ -246,7 +246,7 @@ export function AppReviewsPage() {
|
|||
}
|
||||
/>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Outlet } from "react-router-dom"
|
|||
|
||||
export function RoleManagementLayout() {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl">
|
||||
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
||||
<div className="mb-4 text-sm font-semibold text-grayScale-500">Role Management</div>
|
||||
<Outlet />
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -484,7 +484,7 @@ export function RolesListPage() {
|
|||
Invite team members
|
||||
</Button>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
|
|
|
|||
|
|
@ -143,7 +143,7 @@ export function CreateAppVersionDialog({
|
|||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
New app version
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ export function CreateSubscriptionPlanDialog({
|
|||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
New subscription package
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -135,7 +135,7 @@ export function EditAppVersionDialog({
|
|||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Edit app version
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -135,7 +135,7 @@ export function EditSubscriptionPlanDialog({
|
|||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-lg overflow-y-auto rounded-[12px] border border-grayScale-100 p-0">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogHeader className="border-b border-grayScale-100 px-6 py-5">
|
||||
<DialogHeader className="border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<DialogTitle className="text-lg font-bold text-grayScale-900">
|
||||
Edit subscription package
|
||||
</DialogTitle>
|
||||
|
|
|
|||
|
|
@ -295,7 +295,7 @@ export function TeamManagementPage() {
|
|||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
@ -487,7 +487,7 @@ export function TeamManagementPage() {
|
|||
{confirmDialog && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Confirm Status Change</h2>
|
||||
<button
|
||||
onClick={handleCancelConfirm}
|
||||
|
|
|
|||
|
|
@ -339,7 +339,7 @@ export function TeamMemberDetailPage() {
|
|||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<InfoItem label="Team role" value={roleLabel} />
|
||||
<InfoItem label="Department" value={displayValue(member.department)} />
|
||||
<InfoItem label="Job title" value={displayValue(member.job_title)} />
|
||||
|
|
|
|||
|
|
@ -354,7 +354,7 @@ export function ActivityLogListPanel({
|
|||
</div>
|
||||
</AdminFiltersPanel>
|
||||
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<div
|
||||
className={cn(
|
||||
scrollable && "min-w-0 w-full max-w-full overflow-x-auto",
|
||||
|
|
@ -545,7 +545,7 @@ export function ActivityLogListPanel({
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
|
||||
<DetailItem
|
||||
icon={<User className="h-4 w-4" />}
|
||||
label="Actor"
|
||||
|
|
|
|||
|
|
@ -501,7 +501,7 @@ export function DeletionRequestsPage() {
|
|||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-5">
|
||||
<div className="rounded-xl border bg-white">
|
||||
<div className="min-w-0 overflow-hidden rounded-xl border bg-white">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
|
|
|||
|
|
@ -422,7 +422,7 @@ export function UserDetailPage() {
|
|||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<InfoItem label="Education level" value={displayValue(user.education_level)} />
|
||||
<InfoItem label="Age group" value={formatAgeGroup(user.age_group)} />
|
||||
<InfoItem label="Favorite topic" value={displayValue(user.favoutite_topic)} />
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Outlet } from "react-router-dom"
|
|||
|
||||
export function UserManagementLayout() {
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-6xl">
|
||||
<div className="mx-auto w-full min-w-0 max-w-6xl">
|
||||
<Outlet />
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -419,7 +419,7 @@ export function UsersListPage() {
|
|||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border">
|
||||
<div className="min-w-0 overflow-hidden bg-white rounded-xl border">
|
||||
<AdminFiltersPanel
|
||||
className="border-0 border-b rounded-none shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
|
|
@ -739,7 +739,7 @@ export function UsersListPage() {
|
|||
{confirmDialog && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm">
|
||||
<div className="mx-4 w-full max-w-sm rounded-xl bg-white shadow-2xl">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-6 py-4">
|
||||
<div className="flex items-center justify-between border-b border-grayScale-100 px-4 py-4 sm:px-6">
|
||||
<h2 className="text-lg font-semibold text-grayScale-900">Confirm Status Change</h2>
|
||||
<button
|
||||
onClick={() => setConfirmDialog(null)}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,17 @@ export interface LoginRequest {
|
|||
password: string
|
||||
}
|
||||
|
||||
export interface TeamMemberSession {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
member_id: number
|
||||
team_role: string
|
||||
}
|
||||
|
||||
export interface TeamMemberRefreshRequest {
|
||||
refresh_token: string
|
||||
}
|
||||
|
||||
export interface LoginResponseData {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
|
|
@ -17,3 +28,19 @@ export interface LoginResponse {
|
|||
status_code: number
|
||||
metadata: any | null
|
||||
}
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
message: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export class TeamAuthError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly detail: string | undefined,
|
||||
public readonly status: number,
|
||||
) {
|
||||
super(message)
|
||||
this.name = "TeamAuthError"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,6 +45,15 @@ export function getNotificationMessage(notification: Notification): string {
|
|||
)
|
||||
}
|
||||
|
||||
/** Platform user notifications use numeric IDs; team-member notifications use UUIDs. */
|
||||
export function isNumericNotificationId(id: string): boolean {
|
||||
return /^\d+$/.test(id.trim())
|
||||
}
|
||||
|
||||
export function hasNotificationContent(notification: Notification): boolean {
|
||||
return Boolean(getNotificationTitle(notification) || getNotificationMessage(notification))
|
||||
}
|
||||
|
||||
export interface GetNotificationsResponse {
|
||||
notifications: Notification[]
|
||||
total_count: number
|
||||
|
|
@ -75,11 +84,22 @@ export type PlatformRole =
|
|||
| "SUPER_ADMIN"
|
||||
| "SUPPORT"
|
||||
|
||||
export type TeamRole =
|
||||
| "SUPER_ADMIN"
|
||||
| "ADMIN"
|
||||
| "CONTENT_MANAGER"
|
||||
| "SUPPORT_AGENT"
|
||||
| "INSTRUCTOR"
|
||||
| "FINANCE"
|
||||
| "HR"
|
||||
| "ANALYST"
|
||||
|
||||
export interface BulkSendResult {
|
||||
total_recipients?: number
|
||||
sent: number
|
||||
failed: number
|
||||
target_users?: number
|
||||
devices_targeted?: number
|
||||
image?: string
|
||||
}
|
||||
|
||||
|
|
@ -88,6 +108,8 @@ export interface ScheduledNotificationTargetRaw {
|
|||
emails?: string[]
|
||||
type?: string
|
||||
level?: string
|
||||
team_member_ids?: number[]
|
||||
team_role?: string
|
||||
}
|
||||
|
||||
export interface ScheduledNotification {
|
||||
|
|
@ -102,6 +124,8 @@ export interface ScheduledNotification {
|
|||
status: ScheduledNotificationStatus
|
||||
target_user_ids?: number[]
|
||||
target_role?: string
|
||||
target_team_member_ids?: number[]
|
||||
target_team_role?: string
|
||||
target_raw?: ScheduledNotificationTargetRaw
|
||||
attempt_count?: number
|
||||
last_error?: string
|
||||
|
|
@ -133,6 +157,8 @@ export interface BulkInAppRequest {
|
|||
message: string
|
||||
user_ids?: number[]
|
||||
role?: string
|
||||
team_member_ids?: number[]
|
||||
team_role?: string
|
||||
scheduled_at?: string
|
||||
type?: string
|
||||
level?: InAppNotificationLevel
|
||||
|
|
@ -146,3 +172,21 @@ export interface GetScheduledNotificationsParams {
|
|||
limit?: number
|
||||
page?: number
|
||||
}
|
||||
|
||||
export interface GetAllNotificationsParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
channel?: NotificationChannel
|
||||
type?: string
|
||||
user_id?: number
|
||||
is_read?: boolean
|
||||
after?: string
|
||||
before?: string
|
||||
}
|
||||
|
||||
export interface ListAllNotificationsResponse {
|
||||
notifications: Notification[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user