Improve notifications, EAT timezone defaults, and bulk send UX.

Add in-app notification pop-ups with a toggle, polish the realtime toast, use EAT for scheduling and datetime display, simplify bulk audience targeting with search highlighting, fix team-only send validation, and keep compose state after send.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-16 18:57:41 +03:00
parent 8fa47328d4
commit 9caf9dfc30
19 changed files with 757 additions and 343 deletions

View File

@ -5,6 +5,7 @@ import { Input } from "../ui/input"
import { Button } from "../ui/button"
import { Select } from "../ui/select"
import { formatPaymentMethod } from "../../lib/payments"
import { APP_TIMEZONE, APP_TIMEZONE_OFFSET } from "../../lib/datetime"
import type { DashboardFilters } from "../../types/analytics.types"
const MONTH_LABELS = [
@ -62,10 +63,10 @@ export function getDashboardFilterLabel(filters: DashboardFilters): string {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
timeZone: APP_TIMEZONE,
}
const from = new Date(`${filters.from}T00:00:00Z`)
const to = new Date(`${filters.to}T00:00:00Z`)
const from = new Date(`${filters.from}T00:00:00${APP_TIMEZONE_OFFSET}`)
const to = new Date(`${filters.to}T00:00:00${APP_TIMEZONE_OFFSET}`)
rangeLabel = `${from.toLocaleDateString("en-US", opts)} – ${to.toLocaleDateString("en-US", opts)}`
}

View File

@ -10,6 +10,7 @@ import {
} from "../ui/dropdown-menu"
import { cn } from "../../lib/utils"
import { formatScheduledAtLabel, toRfc3339Utc } from "../../lib/notificationBulk"
import { APP_TIMEZONE_LABEL, getAppDateTimeParts, getAppNowCalendarDate } from "../../lib/datetime"
function digitsOnly(value: string, maxLength: number) {
return value.replace(/\D/g, "").slice(0, maxLength)
@ -37,17 +38,42 @@ export function NotificationSchedulePicker({
const label = useMemo(() => formatScheduledAtLabel(value), [value])
const clearFields = () => {
const clearLocalFields = () => {
setYear("")
setMonth("")
setDay("")
setHour("")
setMinute("")
}
const clearFields = () => {
clearLocalFields()
onChange("")
}
const syncFieldsFromValue = (nextValue: string) => {
const parts = getAppDateTimeParts(nextValue)
if (!parts) {
clearLocalFields()
return
}
setYear(parts.year)
setMonth(parts.month)
setDay(parts.day)
setHour(parts.hour)
setMinute(parts.minute)
}
const handleOpenChange = (nextOpen: boolean) => {
setOpen(nextOpen)
if (nextOpen) {
if (value) syncFieldsFromValue(value)
else clearLocalFields()
}
}
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger asChild>
<button
type="button"
@ -67,7 +93,9 @@ export function NotificationSchedulePicker({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[320px] p-3">
<p className="mb-2 text-xs font-semibold text-grayScale-500">Schedule notification</p>
<p className="mb-2 text-xs font-semibold text-grayScale-500">
Schedule notification ({APP_TIMEZONE_LABEL})
</p>
<div className="space-y-2">
<div>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">Date</label>
@ -104,7 +132,9 @@ export function NotificationSchedulePicker({
</div>
</div>
<div>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">Time (UTC)</label>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">
Time ({APP_TIMEZONE_LABEL})
</label>
<div className="flex items-center gap-1.5">
<Input
type="text"
@ -136,10 +166,10 @@ export function NotificationSchedulePicker({
size="sm"
className="h-8"
onClick={() => {
const now = new Date()
setYear(String(now.getUTCFullYear()))
setMonth(String(now.getUTCMonth() + 1).padStart(2, "0"))
setDay(String(now.getUTCDate()).padStart(2, "0"))
const [y, m, d] = getAppNowCalendarDate().split("-")
setYear(y)
setMonth(m)
setDay(d)
}}
>
Today
@ -156,7 +186,7 @@ export function NotificationSchedulePicker({
const rfc3339 = toRfc3339Utc(year, month, day, hour, minute)
if (!rfc3339) {
toast.error("Invalid schedule time", {
description: "Use YYYY-MM-DD and HH:MM (24h UTC). Time must be in the future.",
description: `Use YYYY-MM-DD and HH:MM (24h ${APP_TIMEZONE_LABEL}). Time must be in the future.`,
})
return
}

View File

@ -0,0 +1,117 @@
import { ArrowRight, X } from "lucide-react"
import { toast } from "sonner"
import {
DEFAULT_NOTIFICATION_TYPE_CONFIG,
formatNotificationTimestamp,
formatNotificationTypeLabel,
NOTIFICATION_TYPE_CONFIG,
} from "../../lib/notificationDisplay"
import {
getNotificationMessage,
getNotificationTitle,
type Notification,
} from "../../types/notification.types"
import { cn } from "../../lib/utils"
type ShowNotificationRealtimePopupOptions = {
onOpen?: (notification: Notification) => void
}
function normalizeComparableText(value: string) {
return value.trim().toLowerCase().replace(/\s+/g, " ")
}
function getLevelAccentClass(level: string) {
switch (level) {
case "error":
case "critical":
return "yimaru-realtime-popup--error"
case "warning":
return "yimaru-realtime-popup--warning"
case "success":
return "yimaru-realtime-popup--success"
default:
return "yimaru-realtime-popup--info"
}
}
export function showNotificationRealtimePopup(
notification: Notification,
options?: ShowNotificationRealtimePopupOptions,
) {
const cfg = NOTIFICATION_TYPE_CONFIG[notification.type] ?? DEFAULT_NOTIFICATION_TYPE_CONFIG
const Icon = cfg.icon
const rawTitle = getNotificationTitle(notification)
const rawMessage = getNotificationMessage(notification)
const title = rawTitle || rawMessage || "Notification"
const message = rawMessage
const showMessage =
Boolean(message) &&
normalizeComparableText(message) !== normalizeComparableText(title)
toast.custom(
(toastId) => (
<div
className={cn(
"yimaru-realtime-popup pointer-events-auto",
getLevelAccentClass(notification.level),
)}
role="status"
aria-live="polite"
>
<div className="yimaru-realtime-popup__header">
<div className="yimaru-realtime-popup__meta">
<span className="yimaru-realtime-popup__type">
{formatNotificationTypeLabel(notification.type)}
</span>
<span className="yimaru-realtime-popup__dot" aria-hidden />
<time
className="yimaru-realtime-popup__time"
dateTime={notification.timestamp}
>
{formatNotificationTimestamp(notification.timestamp)}
</time>
</div>
<button
type="button"
className="yimaru-realtime-popup__close"
onClick={() => toast.dismiss(toastId)}
aria-label="Dismiss notification"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
<div className="yimaru-realtime-popup__body">
<div className={cn("yimaru-realtime-popup__icon", cfg.bg)}>
<Icon className={cn("h-4 w-4", cfg.color)} />
</div>
<div className="yimaru-realtime-popup__content">
<p className="yimaru-realtime-popup__title">{title}</p>
{showMessage ? (
<p className="yimaru-realtime-popup__message">{message}</p>
) : null}
<button
type="button"
className="yimaru-realtime-popup__action"
onClick={() => {
toast.dismiss(toastId)
options?.onOpen?.(notification)
}}
>
View details
<ArrowRight className="h-3 w-3" />
</button>
</div>
</div>
</div>
),
{
position: "bottom-right",
duration: 8000,
unstyled: true,
className: "yimaru-realtime-popup-host",
},
)
}

View File

@ -6,14 +6,22 @@ import { toast } from "sonner"
import { Badge } from "../ui/badge"
import { cn } from "../../lib/utils"
import { SpinnerIcon } from "../ui/spinner-icon"
import { ToggleSwitch } from "../ui/toggle-switch"
import { resolveNotificationDetail } from "../../api/notifications.api"
import { useNotifications } from "../../hooks/useNotifications"
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
import { showNotificationRealtimePopup } from "../notifications/showNotificationRealtimePopup"
import {
DEFAULT_NOTIFICATION_TYPE_CONFIG,
formatNotificationTimestamp,
NOTIFICATION_TYPE_CONFIG,
} from "../../lib/notificationDisplay"
import {
getNotificationPopupEnabled,
NOTIFICATION_POPUP_PREFERENCE_EVENT,
setNotificationPopupEnabled,
} from "../../lib/notificationPopupPreference"
import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket"
import {
getNotificationMessage,
getNotificationTitle,
@ -148,6 +156,7 @@ function NotificationItem({
export function NotificationDropdown() {
const [open, setOpen] = useState(false)
const [popupEnabled, setPopupEnabled] = useState(() => getNotificationPopupEnabled())
const [detailOpen, setDetailOpen] = useState(false)
const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState(false)
@ -158,6 +167,7 @@ export function NotificationDropdown() {
const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null)
const slideTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())
const pendingDeleteRef = useRef<PendingDelete | null>(null)
const popupShownIdsRef = useRef<Set<string>>(new Set())
const containerRef = useRef<HTMLDivElement>(null)
const navigate = useNavigate()
const {
@ -300,6 +310,39 @@ export function NotificationDropdown() {
[loadNotificationDetail],
)
useEffect(() => {
const onPreferenceChange = (event: Event) => {
const enabled = (event as CustomEvent<boolean>).detail
if (typeof enabled === "boolean") {
setPopupEnabled(enabled)
}
}
window.addEventListener(NOTIFICATION_POPUP_PREFERENCE_EVENT, onPreferenceChange)
return () => {
window.removeEventListener(NOTIFICATION_POPUP_PREFERENCE_EVENT, onPreferenceChange)
}
}, [])
useEffect(() => {
const onRealtime = (event: Event) => {
if (!popupEnabled) return
const notification = (event as CustomEvent<Notification>).detail
if (!notification) return
if (notification.delivery_channel && notification.delivery_channel !== "in_app") return
if (popupShownIdsRef.current.has(notification.id)) return
popupShownIdsRef.current.add(notification.id)
showNotificationRealtimePopup(notification, {
onOpen: (item) => handleOpenNotification(item),
})
}
window.addEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime)
return () => window.removeEventListener(NOTIFICATION_REALTIME_EVENT, onRealtime)
}, [popupEnabled, handleOpenNotification])
useEffect(() => {
function handleMouseDown(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
@ -343,25 +386,37 @@ export function NotificationDropdown() {
{open && (
<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">
<div className="flex items-center justify-between gap-3 border-b px-4 py-3">
<div className="flex min-w-0 items-center gap-2">
<h3 className="text-sm font-semibold text-grayScale-800">Notifications</h3>
{unreadCount > 0 && (
<Badge variant="default" className="px-1.5 py-0 text-[10px]">
{unreadCount}
</Badge>
)}
{unreadCount > 0 && (
<button
type="button"
className="ml-1 flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-grayScale-500 transition-colors hover:bg-grayScale-100 hover:text-grayScale-700"
onClick={markAllAsRead}
>
<CheckCheck className="h-3.5 w-3.5" />
Mark all read
</button>
)}
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="text-[10px] font-medium text-grayScale-500">Pop-ups</span>
<ToggleSwitch
checked={popupEnabled}
onCheckedChange={() => {
const next = !popupEnabled
setPopupEnabled(next)
setNotificationPopupEnabled(next)
}}
aria-label="Show in-app notification pop-ups"
/>
</div>
{unreadCount > 0 && (
<button
type="button"
className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-grayScale-500 transition-colors hover:bg-grayScale-100 hover:text-grayScale-700"
onClick={markAllAsRead}
>
<CheckCheck className="h-3.5 w-3.5" />
Mark all read
</button>
)}
</div>
<div className="max-h-[480px] overflow-y-auto">

View File

@ -312,4 +312,207 @@
.yimaru-toast[data-sonner-toast][data-styled="true"] {
padding-right: 2.25rem;
}
[data-sonner-toaster][data-y-position="bottom"][data-x-position="right"] {
bottom: 1.25rem;
right: 1.25rem;
}
[data-sonner-toast].yimaru-realtime-popup-host {
padding: 0;
margin: 0;
border: none;
background: transparent;
box-shadow: none;
--y: translate(115%, 115%);
opacity: 0;
transition:
transform 480ms cubic-bezier(0.16, 1, 0.3, 1),
opacity 480ms cubic-bezier(0.16, 1, 0.3, 1),
height 400ms ease;
}
[data-sonner-toast].yimaru-realtime-popup-host[data-mounted="true"] {
--y: translate(0, 0);
opacity: 1;
}
[data-sonner-toast].yimaru-realtime-popup-host[data-removed="true"][data-front="true"][data-swipe-out="false"] {
--y: translate(115%, 115%);
opacity: 0;
transition:
transform 360ms cubic-bezier(0.4, 0, 1, 1),
opacity 280ms ease;
}
[data-sonner-toast].yimaru-realtime-popup-host[data-removed="true"][data-front="false"][data-swipe-out="false"] {
--y: translate(60%, 60%);
opacity: 0;
}
.yimaru-realtime-popup {
--yimaru-popup-accent: #9e2891;
width: min(380px, calc(100vw - 2rem));
overflow: hidden;
border-radius: 0.75rem;
border: 1px solid var(--gs-200);
border-left: 3px solid var(--yimaru-popup-accent);
background: #fff;
color: hsl(var(--foreground));
box-shadow:
0 1px 2px rgba(15, 23, 42, 0.04),
0 12px 32px rgba(15, 23, 42, 0.12);
}
html.dark .yimaru-realtime-popup {
background: hsl(var(--card));
box-shadow:
0 1px 2px rgba(0, 0, 0, 0.25),
0 16px 40px rgba(0, 0, 0, 0.45);
}
.yimaru-realtime-popup--success {
--yimaru-popup-accent: #059669;
}
.yimaru-realtime-popup--error {
--yimaru-popup-accent: #dc2626;
}
.yimaru-realtime-popup--warning {
--yimaru-popup-accent: #d97706;
}
.yimaru-realtime-popup--info {
--yimaru-popup-accent: #9e2891;
}
.yimaru-realtime-popup__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.625rem 0.75rem 0.5rem 0.875rem;
border-bottom: 1px solid var(--gs-100);
background: var(--gs-50);
}
html.dark .yimaru-realtime-popup__header {
background: hsl(var(--muted) / 0.35);
border-bottom-color: hsl(var(--border));
}
.yimaru-realtime-popup__meta {
display: flex;
min-width: 0;
align-items: center;
gap: 0.375rem;
}
.yimaru-realtime-popup__type {
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--yimaru-popup-accent);
}
.yimaru-realtime-popup__dot {
width: 0.2rem;
height: 0.2rem;
flex-shrink: 0;
border-radius: 9999px;
background: var(--gs-300);
}
.yimaru-realtime-popup__time {
font-size: 0.6875rem;
font-weight: 500;
color: var(--gs-500);
white-space: nowrap;
}
.yimaru-realtime-popup__close {
display: grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
flex-shrink: 0;
border-radius: 0.375rem;
border: 1px solid transparent;
background: transparent;
color: var(--gs-400);
transition:
background-color 0.15s ease,
color 0.15s ease,
border-color 0.15s ease;
}
.yimaru-realtime-popup__close:hover {
background: #fff;
border-color: var(--gs-200);
color: var(--gs-600);
}
html.dark .yimaru-realtime-popup__close:hover {
background: hsl(var(--background));
}
.yimaru-realtime-popup__body {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 0.875rem 1rem;
}
.yimaru-realtime-popup__icon {
display: grid;
place-items: center;
width: 2.5rem;
height: 2.5rem;
flex-shrink: 0;
border-radius: 0.625rem;
}
.yimaru-realtime-popup__content {
min-width: 0;
flex: 1;
}
.yimaru-realtime-popup__title {
font-size: 0.875rem;
font-weight: 600;
line-height: 1.35;
letter-spacing: -0.015em;
color: hsl(var(--foreground));
}
.yimaru-realtime-popup__message {
margin-top: 0.25rem;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
font-size: 0.8125rem;
line-height: 1.45;
color: var(--gs-600);
}
.yimaru-realtime-popup__action {
display: inline-flex;
align-items: center;
gap: 0.25rem;
margin-top: 0.625rem;
padding: 0;
border: none;
background: transparent;
font-size: 0.75rem;
font-weight: 600;
color: var(--yimaru-popup-accent);
transition: opacity 0.15s ease;
}
.yimaru-realtime-popup__action:hover {
opacity: 0.8;
}
}

View File

@ -4,6 +4,7 @@ import type {
DateRevenue,
LabelCount,
} from "../types/analytics.types"
import { APP_TIMEZONE } from "./datetime"
/** Canonical subscription row statuses shown in analytics breakdowns. */
export const SUBSCRIPTION_STATUS_BREAKDOWN = [
@ -140,7 +141,7 @@ export function formatAnalyticsSeriesDate(dateStr: string): string {
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
timeZone: APP_TIMEZONE,
})
}
const d = new Date(dateStr)
@ -148,7 +149,7 @@ export function formatAnalyticsSeriesDate(dateStr: string): string {
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
timeZone: APP_TIMEZONE,
})
}
@ -161,7 +162,7 @@ function formatShortDate(iso: string) {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
timeZone: APP_TIMEZONE,
})
}
const d = new Date(iso)
@ -169,7 +170,7 @@ function formatShortDate(iso: string) {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
timeZone: APP_TIMEZONE,
})
}

View File

@ -8,6 +8,101 @@ export function isValidDateInput(value: string | null | undefined): value is str
return Boolean(value && /^\d{4}-\d{2}-\d{2}/.test(value.trim()))
}
/** Today's calendar date (YYYY-MM-DD) in the app timezone. */
export function getAppNowCalendarDate(): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: APP_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(new Date())
}
/** Split an instant into EAT wall-clock parts for schedule pickers. */
export function getAppDateTimeParts(iso: string | null | undefined): {
year: string
month: string
day: string
hour: string
minute: string
} | null {
if (!iso?.trim()) return null
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return null
const parts = new Intl.DateTimeFormat("en-GB", {
timeZone: APP_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).formatToParts(d)
const pick = (type: Intl.DateTimeFormatPartTypes) =>
parts.find((part) => part.type === type)?.value ?? ""
return {
year: pick("year"),
month: pick("month"),
day: pick("day"),
hour: pick("hour"),
minute: pick("minute"),
}
}
/**
* Parse YYYY-MM-DD HH:MM as EAT wall clock and return RFC3339 UTC.
* Returns null when invalid or not in the future.
*/
export function toRfc3339FromAppLocal(
year: string,
month: string,
day: string,
hour: string,
minute: string,
): string | null {
const y = year.trim()
const mo = month.trim().padStart(2, "0")
const d = day.trim().padStart(2, "0")
const h = hour.trim().padStart(2, "0")
const min = minute.trim().padStart(2, "0")
if (y.length !== 4 || mo.length !== 2 || d.length !== 2 || h.length !== 2 || min.length !== 2) {
return null
}
const mNum = Number(mo)
const dNum = Number(d)
const hNum = Number(h)
const minNum = Number(min)
if (mNum < 1 || mNum > 12 || dNum < 1 || dNum > 31 || hNum < 0 || hNum > 23 || minNum < 0 || minNum > 59) {
return null
}
const iso = `${y}-${mo}-${d}T${h}:${min}:00${APP_TIMEZONE_OFFSET}`
const parsed = new Date(iso)
if (Number.isNaN(parsed.getTime())) return null
if (toAppCalendarDate(parsed) !== `${y}-${mo}-${d}`) return null
if (parsed.getTime() <= Date.now()) return null
return parsed.toISOString()
}
/** Value for `<input type="datetime-local" />` showing wall clock in EAT. */
export function toDatetimeLocalAppValue(iso: string | null | undefined): string {
const parts = getAppDateTimeParts(iso)
if (!parts) return ""
return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}`
}
/** Parse datetime-local input as EAT wall clock → RFC3339 UTC. */
export function fromDatetimeLocalAppValue(value: string): string | undefined {
const trimmed = value?.trim()
if (!trimmed) return undefined
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(trimmed)
if (!match) return undefined
const [, year, month, day, hour, minute] = match
return toRfc3339FromAppLocal(year, month, day, hour, minute) ?? undefined
}
/** Calendar YYYY-MM-DD of an instant in the app timezone. */
export function toAppCalendarDate(iso: string | Date): string | null {
const d = typeof iso === "string" ? new Date(iso) : iso
@ -35,6 +130,52 @@ export function formatAppDate(
})
}
export function formatAppLongDate(
iso: string | null | undefined,
emptyLabel = "—",
): string {
if (!iso) return emptyLabel
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return emptyLabel
return d.toLocaleDateString("en-GB", {
timeZone: APP_TIMEZONE,
year: "numeric",
month: "long",
day: "numeric",
})
}
/** Relative activity stamp in EAT (Today/Yesterday/date + time). */
export function formatAppRelativeDateTime(
iso: string | null | undefined,
emptyLabel = "unassigned",
): string {
if (!iso?.trim()) return emptyLabel
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return emptyLabel
const today = getAppNowCalendarDate()
const thatDay = toAppCalendarDate(d)
if (!thatDay) return formatAppDateTime(iso, emptyLabel)
const dayDiff = Math.round(
(Date.parse(`${today}T00:00:00${APP_TIMEZONE_OFFSET}`) -
Date.parse(`${thatDay}T00:00:00${APP_TIMEZONE_OFFSET}`)) /
86_400_000,
)
const timePart = d.toLocaleTimeString("en-GB", {
timeZone: APP_TIMEZONE,
hour: "numeric",
minute: "2-digit",
hour12: true,
})
if (dayDiff === 0) return `Today, ${timePart}`
if (dayDiff === 1) return `Yesterday, ${timePart}`
return `${formatAppDate(iso, emptyLabel)}, ${timePart}`
}
export function formatAppDateTime(
iso: string | null | undefined,
emptyLabel = "—",
@ -53,6 +194,25 @@ export function formatAppDateTime(
})
}
export function formatAppDateTimeSeconds(
iso: string | null | undefined,
emptyLabel = "—",
): string {
if (!iso) return emptyLabel
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return emptyLabel
return d.toLocaleString("en-GB", {
timeZone: APP_TIMEZONE,
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
}
export function formatAppTime(
iso: string | null | undefined,
emptyLabel = "—",

View File

@ -8,7 +8,7 @@ import type {
} from "../types/notification.types"
import { getUsers } from "../api/users.api"
import { getTeamMembers } from "../api/team.api"
import { formatAppDateTime } from "./datetime"
import { formatAppDateTime, toRfc3339FromAppLocal } from "./datetime"
import { TEAM_ROLE_OPTIONS } from "./teamRoles"
export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [
@ -28,9 +28,7 @@ export const TEAM_ROLES: { value: TeamRole; label: string }[] = TEAM_ROLE_OPTION
)
export type NotificationAudienceMode =
| "platform_role"
| "platform_selected"
| "team_role"
| "team_selected"
| "direct"
@ -81,35 +79,7 @@ export function toRfc3339Utc(
hour: string,
minute: string,
): string | null {
const y = Number(year)
const m = Number(month)
const d = Number(day)
const h = Number(hour)
const min = Number(minute)
const formatOk =
year.length === 4 &&
month.length === 2 &&
day.length === 2 &&
hour.length === 2 &&
minute.length === 2
const dateValue = new Date(y, m - 1, d)
const dateOk =
formatOk &&
m >= 1 &&
m <= 12 &&
d >= 1 &&
d <= 31 &&
dateValue.getFullYear() === y &&
dateValue.getMonth() === m - 1 &&
dateValue.getDate() === d
const timeOk = h >= 0 && h <= 23 && min >= 0 && min <= 59
if (!dateOk || !timeOk) return null
const utc = new Date(Date.UTC(y, m - 1, d, h, min, 0, 0))
if (utc.getTime() <= Date.now()) return null
return utc.toISOString()
return toRfc3339FromAppLocal(year, month, day, hour, minute)
}
export function parseDirectRecipients(raw: string): string[] {
@ -205,7 +175,7 @@ export function isAudienceModeValidForChannel(
channel: string,
): boolean {
if (mode === "direct") return channel === "sms" || channel === "email"
if (mode === "team_role" || mode === "team_selected") {
if (mode === "team_selected") {
return channelSupportsTeamTargeting(channel)
}
return true

View File

@ -0,0 +1,24 @@
const STORAGE_KEY = "yimaru:notification-popup-enabled"
export const NOTIFICATION_POPUP_PREFERENCE_EVENT = "yimaru:notification-popup-preference"
export function getNotificationPopupEnabled(): boolean {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (raw === null) return true
return raw === "true"
} catch {
return true
}
}
export function setNotificationPopupEnabled(enabled: boolean): void {
try {
localStorage.setItem(STORAGE_KEY, String(enabled))
} catch {
// ignore storage failures
}
window.dispatchEvent(
new CustomEvent<boolean>(NOTIFICATION_POPUP_PREFERENCE_EVENT, { detail: enabled }),
)
}

View File

@ -55,6 +55,7 @@ import {
buildSubscriptionStatusPie,
} from "../lib/analytics"
import type { DashboardData, DashboardFilters } from "../types/analytics.types"
import { formatAppDateTime } from "../lib/datetime"
import { formatAverageStars } from "../lib/ratingsDisplay"
import { formatPlanDuration } from "../lib/subscriptionPlans"
import type { SubscriptionPlan } from "../types/subscription.types"
@ -184,14 +185,7 @@ export function DashboardPage() {
? getSubscriptionMetrics(dashboard.subscriptions)
: null
const generatedAt = dashboard
? new Date(dashboard.generated_at).toLocaleString("en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
: ""
const generatedAt = dashboard ? formatAppDateTime(dashboard.generated_at) : ""
const registrationPeakIndex = registrationData.reduce((best, row, idx) => {
return row.count > (registrationData[best]?.count ?? 0) ? idx : best

View File

@ -25,29 +25,14 @@ import type { TeamMeProfile } from "../types/team.types";
import { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField";
import { UnassignedLabel, isUnassignedLabel, DisplayValue } from "../lib/displayValue"
import { formatAppDateTime, formatAppLongDate } from "../lib/datetime"
function formatDate(dateStr: string | null | undefined): string {
if (!dateStr) return "unassigned";
const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return dateStr;
return date.toLocaleDateString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
});
return formatAppLongDate(dateStr, "unassigned")
}
function formatDateTime(dateStr: string | null | undefined): string {
if (!dateStr) return "unassigned";
const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return dateStr;
return date.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
return formatAppDateTime(dateStr, "unassigned")
}
function formatRoleLabel(role: string): string {

View File

@ -63,6 +63,7 @@ import {
formatRevenueAxisTick,
} from "../../lib/analytics"
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
import { formatAppDateTime } from "../../lib/datetime"
import { isUnassignedLabel } from "../../lib/displayValue"
import {
displayUserAgeGroup,
@ -466,13 +467,7 @@ export function AnalyticsPage() {
viewers: d.viewers_reached,
})) ?? []
const generatedAt = new Date(dashboard.generated_at).toLocaleString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
})
const generatedAt = formatAppDateTime(dashboard.generated_at)
return (
<SensitiveRevealProvider>

View File

@ -33,6 +33,7 @@ import {
DEFAULT_TABLE_PAGE_SIZE,
} from "../../lib/tablePagination"
import { UnassignedLabel } from "../../lib/displayValue"
import { fromDatetimeLocalAppValue } from "../../lib/datetime"
import {
getNotificationMessage,
getNotificationTitle,
@ -55,13 +56,6 @@ const READ_OPTIONS = [
{ 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) {
@ -121,11 +115,11 @@ export function AllNotificationsPage() {
...(parsedUserId != null ? { user_id: parsedUserId } : {}),
...(readFilter === "true" ? { is_read: true } : {}),
...(readFilter === "false" ? { is_read: false } : {}),
...(toRfc3339FromDatetimeLocal(afterFilter)
? { after: toRfc3339FromDatetimeLocal(afterFilter) }
...(fromDatetimeLocalAppValue(afterFilter)
? { after: fromDatetimeLocalAppValue(afterFilter) }
: {}),
...(toRfc3339FromDatetimeLocal(beforeFilter)
? { before: toRfc3339FromDatetimeLocal(beforeFilter) }
...(fromDatetimeLocalAppValue(beforeFilter)
? { before: fromDatetimeLocalAppValue(beforeFilter) }
: {}),
})
setRows(res.data.notifications)

View File

@ -13,6 +13,7 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"
import { NotificationSchedulePicker } from "../../components/notifications/NotificationSchedulePicker"
import { EmailComposeFields } from "../../components/notifications/EmailComposeFields"
import { cn } from "../../lib/utils"
import { SearchHighlight, getSearchTokens } from "../../components/SearchHighlight"
import { Stepper } from "../../components/ui/stepper"
import {
sendBulkEmail,
@ -33,11 +34,9 @@ import {
IN_APP_TYPES,
isAudienceModeValidForChannel,
parseDirectRecipients,
PLATFORM_ROLES,
TEAM_ROLES,
type NotificationAudienceMode,
} from "../../lib/notificationBulk"
import { formatTeamRoleLabel } from "../../lib/teamRoles"
import { formatAppDateTime } from "../../lib/datetime"
import {
BulkSendSummaryPanel,
type BulkSendSummary,
@ -45,8 +44,6 @@ import {
import type {
InAppNotificationLevel,
NotificationChannel,
PlatformRole,
TeamRole,
} from "../../types/notification.types"
import type { EmailTemplate } from "../../types/emailTemplate.types"
import type { UserApiDTO } from "../../types/user.types"
@ -69,24 +66,15 @@ const CHANNELS: {
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"}`
@ -134,10 +122,8 @@ export function CreateNotificationPage() {
const navigate = useNavigate()
const [channel, setChannel] = useState<NotificationChannel>("push")
const [audienceMode, setAudienceMode] = useState<NotificationAudienceMode>("platform_role")
const [audienceMode, setAudienceMode] = useState<NotificationAudienceMode>("platform_selected")
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)
@ -216,13 +202,18 @@ export function CreateNotificationPage() {
}, [channel])
const filteredUsers = useMemo(() => {
const q = userSearchQuery.trim().toLowerCase()
if (!q) return users
const tokens = getSearchTokens(userSearchQuery).map((token) => token.toLowerCase())
if (tokens.length === 0) return users
return users.filter((user) => {
const fullName = `${user.first_name ?? ""} ${user.last_name ?? ""}`.trim().toLowerCase()
const email = (user.email ?? "").toLowerCase()
const phone = (user.phone_number ?? "").toLowerCase()
return fullName.includes(q) || email.includes(q) || phone.includes(q)
const haystack = [
`${user.first_name ?? ""} ${user.last_name ?? ""}`.trim(),
user.email ?? "",
user.phone_number ?? "",
String(user.id),
]
.join(" ")
.toLowerCase()
return tokens.every((token) => haystack.includes(token))
})
}, [users, userSearchQuery])
@ -237,12 +228,17 @@ export function CreateNotificationPage() {
)
const filteredTeamMembers = useMemo(() => {
const q = teamSearchQuery.trim().toLowerCase()
if (!q) return teamMembers
const tokens = getSearchTokens(teamSearchQuery).map((token) => token.toLowerCase())
if (tokens.length === 0) 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)
const haystack = [
`${member.first_name ?? ""} ${member.last_name ?? ""}`.trim(),
member.email ?? "",
String(member.id),
]
.join(" ")
.toLowerCase()
return tokens.every((token) => haystack.includes(token))
})
}, [teamMembers, teamSearchQuery])
@ -265,9 +261,7 @@ export function CreateNotificationPage() {
setTitle("")
setMessage("")
setHtmlBody("")
setAudienceMode("platform_role")
setPlatformRole("STUDENT")
setTeamRole("ADMIN")
setAudienceMode("platform_selected")
setSelectedUserIds([])
setSelectedTeamMemberIds([])
setUserSearchQuery("")
@ -281,6 +275,8 @@ export function CreateNotificationPage() {
setInAppLevel("info")
setEmailTemplateSlug("")
setEmailTemplateVariables({})
setCurrentStep(1)
setSendSummary(null)
}
const selectedEmailTemplate = useMemo(
@ -309,6 +305,29 @@ export function CreateNotificationPage() {
emailTemplateVariables,
])
const validateTargeting = useCallback((): boolean => {
if (audienceMode === "platform_selected") {
if (selectedUserIds.length === 0) {
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
}
const direct = parseDirectRecipients(directRecipients)
if (direct.length === 0) {
toast.error(channel === "sms" ? "Enter at least one phone number" : "Enter at least one email")
return false
}
return true
}, [audienceMode, selectedUserIds, selectedTeamMemberIds, directRecipients, channel])
const validateStep = useCallback(
(step: number): boolean => {
if (step === 2) {
@ -343,7 +362,18 @@ export function CreateNotificationPage() {
}
return true
},
[channel, title, message, htmlBody, emailTemplateSlug, emailTemplateVariables, selectedEmailTemplate, isScheduling, scheduledAt],
[
channel,
title,
message,
htmlBody,
emailTemplateSlug,
emailTemplateVariables,
selectedEmailTemplate,
isScheduling,
scheduledAt,
validateTargeting,
],
)
const goNext = useCallback(() => {
@ -355,40 +385,10 @@ export function CreateNotificationPage() {
setCurrentStep((s) => Math.max(s - 1, 1))
}, [])
const validateTargeting = (): boolean => {
if (audienceMode === "platform_role" || audienceMode === "team_role") return true
if (audienceMode === "platform_selected") {
if (selectedUserIds.length === 0) {
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
}
const direct = parseDirectRecipients(directRecipients)
if (direct.length === 0) {
toast.error(channel === "sms" ? "Enter at least one phone number" : "Enter at least one email")
return false
}
return true
}
const buildTargeting = () => {
if (audienceMode === "platform_role") {
return { role: platformRole }
}
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 }
}
@ -432,8 +432,6 @@ export function CreateNotificationPage() {
const schedule = isScheduling && scheduledAt ? { scheduled_at: scheduledAt } : {}
const audienceLabel = buildAudienceLabel(
audienceMode,
platformRole,
teamRole,
selectedUserIds,
selectedTeamMemberIds,
directRecipients,
@ -470,7 +468,6 @@ 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))
}
@ -519,7 +516,7 @@ export function CreateNotificationPage() {
apiMessage: result.message || undefined,
})
toast.success("Notification scheduled", {
description: `Job #${result.data.id} · ${new Date(result.data.scheduled_at).toLocaleString()}`,
description: `Job #${result.data.id} · ${formatAppDateTime(result.data.scheduled_at)}`,
action: {
label: "View scheduled",
onClick: () => navigate("/notifications/scheduled"),
@ -554,8 +551,6 @@ export function CreateNotificationPage() {
description: toastDetail,
})
}
resetForm()
} catch (err) {
notifyApiError(err, "Failed to send notification")
} finally {
@ -639,7 +634,7 @@ export function CreateNotificationPage() {
const v = e.target.value as NotificationChannel
setChannel(v)
if (!isAudienceModeValidForChannel(audienceMode, v)) {
setAudienceMode("platform_role")
setAudienceMode("platform_selected")
}
if (v === "sms") setTitle("")
}}
@ -816,8 +811,7 @@ export function CreateNotificationPage() {
<Card
className={cn(
"border shadow-none",
audienceMode === "platform_role" ||
audienceMode === "platform_selected" ||
audienceMode === "platform_selected" ||
audienceMode === "direct"
? "border-brand-200 ring-1 ring-brand-100"
: "border-grayScale-100",
@ -834,18 +828,6 @@ export function CreateNotificationPage() {
</div>
</div>
<div className="inline-flex flex-wrap gap-1.5 text-xs font-medium">
<button
type="button"
onClick={() => setAudienceMode("platform_role")}
className={cn(
"rounded-[6px] px-3 py-2 transition-all",
audienceMode === "platform_role"
? "bg-brand-500 text-white shadow-sm"
: "border border-grayScale-200 bg-white text-grayScale-500 hover:border-grayScale-300 hover:text-grayScale-700",
)}
>
Platform role
</button>
<button
type="button"
onClick={() => {
@ -877,27 +859,6 @@ export function CreateNotificationPage() {
)}
</div>
{audienceMode === "platform_role" && (
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
Platform role
</label>
<Select
value={platformRole}
onChange={(e) => setPlatformRole(e.target.value as PlatformRole)}
>
{PLATFORM_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 learners/users with this platform role.
</p>
</div>
)}
{audienceMode === "direct" && (
<div>
<label className="mb-1 block text-xs font-medium text-grayScale-500">
@ -1012,9 +973,16 @@ export function CreateNotificationPage() {
}}
/>
<span className="truncate">
{user.first_name} {user.last_name}
<SearchHighlight
text={`${user.first_name ?? ""} ${user.last_name ?? ""}`.trim()}
query={userSearchQuery}
/>
<span className="ml-1 text-[10px] text-grayScale-400">
· {user.email ?? user.phone_number ?? `ID ${user.id}`}
·{" "}
<SearchHighlight
text={user.email ?? user.phone_number ?? `ID ${user.id}`}
query={userSearchQuery}
/>
</span>
</span>
</label>
@ -1031,7 +999,7 @@ export function CreateNotificationPage() {
<Card
className={cn(
"border shadow-none",
audienceMode === "team_role" || audienceMode === "team_selected"
audienceMode === "team_selected"
? "border-brand-200 ring-1 ring-brand-100"
: "border-grayScale-100",
)}
@ -1047,18 +1015,6 @@ export function CreateNotificationPage() {
</div>
</div>
<div className="inline-flex flex-wrap gap-1.5 text-xs font-medium">
<button
type="button"
onClick={() => setAudienceMode("team_role")}
className={cn(
"rounded-[6px] px-3 py-2 transition-all",
audienceMode === "team_role"
? "bg-brand-500 text-white shadow-sm"
: "border border-grayScale-200 bg-white text-grayScale-500 hover:border-grayScale-300 hover:text-grayScale-700",
)}
>
Team role
</button>
<button
type="button"
onClick={() => {
@ -1076,27 +1032,6 @@ export function CreateNotificationPage() {
</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">
@ -1144,6 +1079,11 @@ export function CreateNotificationPage() {
>
Unselect all
</button>
{teamSearchQuery.trim() && filteredTeamMembers.length > 0 && (
<span className="ml-auto text-[10px] text-grayScale-400">
{filteredTeamMembers.length} shown
</span>
)}
</div>
</div>
<div className="max-h-64 space-y-1.5 overflow-y-auto p-2">
@ -1158,6 +1098,13 @@ export function CreateNotificationPage() {
No team members available to select.
</div>
)}
{!teamRecipientsLoading &&
teamMembers.length > 0 &&
filteredTeamMembers.length === 0 && (
<div className="py-4 text-center text-xs text-grayScale-400">
No team members match &ldquo;{teamSearchQuery.trim()}&rdquo;.
</div>
)}
{!teamRecipientsLoading &&
filteredTeamMembers.map((member) => {
const checked = selectedTeamMemberIds.includes(member.id)
@ -1174,6 +1121,9 @@ export function CreateNotificationPage() {
className="h-3.5 w-3.5 rounded border-grayScale-300"
checked={checked}
onChange={(e) => {
if (e.target.checked) {
setAudienceMode("team_selected")
}
setSelectedTeamMemberIds((prev) =>
e.target.checked
? [...prev, member.id]
@ -1182,9 +1132,16 @@ export function CreateNotificationPage() {
}}
/>
<span className="truncate">
{member.first_name} {member.last_name}
<SearchHighlight
text={`${member.first_name ?? ""} ${member.last_name ?? ""}`.trim()}
query={teamSearchQuery}
/>
<span className="ml-1 text-[10px] text-grayScale-400">
· {member.email || `ID ${member.id}`}
·{" "}
<SearchHighlight
text={member.email ?? `ID ${member.id}`}
query={teamSearchQuery}
/>
</span>
</span>
</label>

View File

@ -13,6 +13,7 @@ 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 { formatAppDateTimeSeconds } from "../../../lib/datetime"
import { cn } from "../../../lib/utils"
import type { NotificationChannel } from "../../../types/notification.types"
import { UnassignedLabel } from "../../../lib/displayValue"
@ -107,14 +108,7 @@ export function BulkSendSummaryPanel({ summary, onDismiss }: BulkSendSummaryPane
: "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 completedLabel = formatAppDateTimeSeconds(summary.completedAt)
const progressTotal = isImmediate ? Math.max(summary.total, 1) : 1
@ -272,7 +266,7 @@ export function BulkSendSummaryPanel({ summary, onDismiss }: BulkSendSummaryPane
<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.
This summary is temporary. Dismiss it or use Clear to start a new notification.
</p>
<div className="flex flex-wrap gap-2">
{!isImmediate ? (

View File

@ -24,6 +24,7 @@ import { DisplayValue, NOT_ASSIGNED_LABEL, UnassignedLabel, displayValue, isUnas
import { getTeamMemberById, updateTeamMemberStatus } from "../../api/team.api"
import type { TeamMemberDetail } from "../../types/team.types"
import { ActivityLogListPanel } from "../user-log/components/ActivityLogListPanel"
import { formatAppDateTime, formatAppLongDate } from "../../lib/datetime"
function formatStatusLabel(status: string): string {
const value = status.trim()
@ -35,30 +36,14 @@ function formatStatusLabel(status: string): string {
}
function formatDate(dateStr: string | null | undefined): string {
if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL
const date = new Date(dateStr)
if (Number.isNaN(date.getTime())) return dateStr
return date.toLocaleDateString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
})
return formatAppLongDate(dateStr, NOT_ASSIGNED_LABEL)
}
function formatDateTime(
dateStr: string | null | undefined,
emptyLabel: string = NOT_ASSIGNED_LABEL,
): string {
if (!dateStr?.trim()) return emptyLabel
const date = new Date(dateStr)
if (Number.isNaN(date.getTime())) return dateStr
return date.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(dateStr, emptyLabel)
}
function getRelativeTime(dateStr: string | null | undefined): string {

View File

@ -29,6 +29,7 @@ import type { Role } from "../../types/rbac.types"
import { mapDeletionRequestApiItem } from "../../types/user.types"
import { UnassignedLabel } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight"
import { fromDatetimeLocalAppValue } from "../../lib/datetime"
const stateBadge: Record<string, string> = {
PENDING: "bg-amber-100 text-amber-700",
@ -90,12 +91,7 @@ export function DeletionRequestsPage() {
const statusMenuRef = useRef<HTMLDivElement | null>(null)
const stateMenuRef = useRef<HTMLDivElement | null>(null)
const toRfc3339 = (value: string) => {
if (!value) return undefined
const normalized = value.includes("T") ? value : value.replace(" ", "T")
const date = new Date(normalized)
return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
}
const toRfc3339 = (value: string) => fromDatetimeLocalAppValue(value)
const fetchData = useCallback(async () => {
setLoading(true)

View File

@ -47,6 +47,11 @@ import {
displayUserFavouriteTopic,
displayUserCountry,
} from "../../lib/userProfileFieldDisplay"
import {
formatAppDateTime,
formatAppLongDate,
formatAppRelativeDateTime,
} from "../../lib/datetime"
const activityIcons = {
completed: CheckCircle2,
@ -84,52 +89,15 @@ function formatStatusLabel(status: string): string {
}
function formatDate(dateStr: string | null | undefined): string {
if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL;
const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return dateStr;
return date.toLocaleDateString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
});
return formatAppLongDate(dateStr, NOT_ASSIGNED_LABEL)
}
function formatDateTime(value?: string | null, emptyLabel = NOT_ASSIGNED_LABEL): string {
if (!value?.trim()) return emptyLabel;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL;
return parsed.toLocaleString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
return formatAppDateTime(value, emptyLabel)
}
function formatActivityOccurredAt(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "unassigned";
const now = new Date();
const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
const startThat = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
const dayDiff = Math.round((startToday - startThat) / 86_400_000);
const timePart = d.toLocaleTimeString(undefined, {
hour: "numeric",
minute: "2-digit",
hour12: true,
});
if (dayDiff === 0) return `Today, ${timePart}`;
if (dayDiff === 1) return `Yesterday, ${timePart}`;
return d.toLocaleDateString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
});
return formatAppRelativeDateTime(iso)
}
function getAccountStatusClasses(status: string): string {

View File

@ -29,22 +29,7 @@ import { usersExportQuery } from "../../lib/csvExportFilters"
import { UnassignedLabel } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight"
import { displayUserRegion, displayUserCountry } from "../../lib/userProfileFieldDisplay"
function formatJoinedAt(iso: string): string {
if (!iso?.trim()) return "unassigned"
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return "unassigned"
return d.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })
}
/** Convert `<input type="datetime-local" />` value to RFC3339 for GET /users. */
function toRfc3339FromDatetimeLocal(value: string): string | undefined {
const t = value?.trim()
if (!t) return undefined
const d = new Date(t)
if (Number.isNaN(d.getTime())) return undefined
return d.toISOString()
}
import { APP_TIMEZONE_LABEL, formatAppDateTime, fromDatetimeLocalAppValue } from "../../lib/datetime"
/** Portaled menu — native `<select>` lists break inside `overflow-y-auto` shells (e.g. app main). */
function UserListFilterDropdown({
@ -184,8 +169,8 @@ export function UsersListPage() {
page,
page_size: pageSize,
query: search || undefined,
created_after: toRfc3339FromDatetimeLocal(createdAfterLocal),
created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal),
created_after: fromDatetimeLocalAppValue(createdAfterLocal),
created_before: fromDatetimeLocalAppValue(createdBeforeLocal),
country: countryFilter.trim() || undefined,
region:
(!countryFilter.trim() || countryFilter.trim().toLowerCase() === "ethiopia") &&
@ -352,8 +337,8 @@ export function UsersListPage() {
() =>
usersExportQuery({
query: search || undefined,
created_after: toRfc3339FromDatetimeLocal(createdAfterLocal),
created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal),
created_after: fromDatetimeLocalAppValue(createdAfterLocal),
created_before: fromDatetimeLocalAppValue(createdBeforeLocal),
country: countryFilter.trim() || undefined,
region:
(!countryFilter.trim() || countryFilter.trim().toLowerCase() === "ethiopia") &&
@ -497,7 +482,7 @@ export function UsersListPage() {
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
<div className="flex flex-col gap-1">
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500">
Created on or after
Created on or after ({APP_TIMEZONE_LABEL})
</label>
<input
id="filter-created-after"
@ -512,7 +497,7 @@ export function UsersListPage() {
</div>
<div className="flex flex-col gap-1">
<label htmlFor="filter-created-before" className="text-xs font-medium text-grayScale-500">
Created on or before
Created on or before ({APP_TIMEZONE_LABEL})
</label>
<input
id="filter-created-before"
@ -663,7 +648,7 @@ export function UsersListPage() {
{displayUserRegion(u.region)}
</TableCell>
<TableCell className="hidden md:table-cell text-sm text-grayScale-500 whitespace-nowrap">
{formatJoinedAt(u.createdAt)}
{formatAppDateTime(u.createdAt, "unassigned")}
</TableCell>
<TableCell className="hidden lg:table-cell align-top text-sm text-grayScale-600">
<span