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

View File

@ -10,6 +10,7 @@ import {
} from "../ui/dropdown-menu" } from "../ui/dropdown-menu"
import { cn } from "../../lib/utils" import { cn } from "../../lib/utils"
import { formatScheduledAtLabel, toRfc3339Utc } from "../../lib/notificationBulk" import { formatScheduledAtLabel, toRfc3339Utc } from "../../lib/notificationBulk"
import { APP_TIMEZONE_LABEL, getAppDateTimeParts, getAppNowCalendarDate } from "../../lib/datetime"
function digitsOnly(value: string, maxLength: number) { function digitsOnly(value: string, maxLength: number) {
return value.replace(/\D/g, "").slice(0, maxLength) return value.replace(/\D/g, "").slice(0, maxLength)
@ -37,17 +38,42 @@ export function NotificationSchedulePicker({
const label = useMemo(() => formatScheduledAtLabel(value), [value]) const label = useMemo(() => formatScheduledAtLabel(value), [value])
const clearFields = () => { const clearLocalFields = () => {
setYear("") setYear("")
setMonth("") setMonth("")
setDay("") setDay("")
setHour("") setHour("")
setMinute("") setMinute("")
}
const clearFields = () => {
clearLocalFields()
onChange("") 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 ( return (
<DropdownMenu open={open} onOpenChange={setOpen}> <DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<button <button
type="button" type="button"
@ -67,7 +93,9 @@ export function NotificationSchedulePicker({
</button> </button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-[320px] p-3"> <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 className="space-y-2">
<div> <div>
<label className="mb-1 block text-[11px] font-medium text-grayScale-500">Date</label> <label className="mb-1 block text-[11px] font-medium text-grayScale-500">Date</label>
@ -104,7 +132,9 @@ export function NotificationSchedulePicker({
</div> </div>
</div> </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"> <div className="flex items-center gap-1.5">
<Input <Input
type="text" type="text"
@ -136,10 +166,10 @@ export function NotificationSchedulePicker({
size="sm" size="sm"
className="h-8" className="h-8"
onClick={() => { onClick={() => {
const now = new Date() const [y, m, d] = getAppNowCalendarDate().split("-")
setYear(String(now.getUTCFullYear())) setYear(y)
setMonth(String(now.getUTCMonth() + 1).padStart(2, "0")) setMonth(m)
setDay(String(now.getUTCDate()).padStart(2, "0")) setDay(d)
}} }}
> >
Today Today
@ -156,7 +186,7 @@ export function NotificationSchedulePicker({
const rfc3339 = toRfc3339Utc(year, month, day, hour, minute) const rfc3339 = toRfc3339Utc(year, month, day, hour, minute)
if (!rfc3339) { if (!rfc3339) {
toast.error("Invalid schedule time", { 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 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 { Badge } from "../ui/badge"
import { cn } from "../../lib/utils" import { cn } from "../../lib/utils"
import { SpinnerIcon } from "../ui/spinner-icon" import { SpinnerIcon } from "../ui/spinner-icon"
import { ToggleSwitch } from "../ui/toggle-switch"
import { resolveNotificationDetail } from "../../api/notifications.api" import { resolveNotificationDetail } from "../../api/notifications.api"
import { useNotifications } from "../../hooks/useNotifications" import { useNotifications } from "../../hooks/useNotifications"
import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog" import { NotificationDetailDialog } from "../notifications/NotificationDetailDialog"
import { showNotificationRealtimePopup } from "../notifications/showNotificationRealtimePopup"
import { import {
DEFAULT_NOTIFICATION_TYPE_CONFIG, DEFAULT_NOTIFICATION_TYPE_CONFIG,
formatNotificationTimestamp, formatNotificationTimestamp,
NOTIFICATION_TYPE_CONFIG, NOTIFICATION_TYPE_CONFIG,
} from "../../lib/notificationDisplay" } from "../../lib/notificationDisplay"
import {
getNotificationPopupEnabled,
NOTIFICATION_POPUP_PREFERENCE_EVENT,
setNotificationPopupEnabled,
} from "../../lib/notificationPopupPreference"
import { NOTIFICATION_REALTIME_EVENT } from "../../lib/notificationsWebSocket"
import { import {
getNotificationMessage, getNotificationMessage,
getNotificationTitle, getNotificationTitle,
@ -148,6 +156,7 @@ function NotificationItem({
export function NotificationDropdown() { export function NotificationDropdown() {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [popupEnabled, setPopupEnabled] = useState(() => getNotificationPopupEnabled())
const [detailOpen, setDetailOpen] = useState(false) const [detailOpen, setDetailOpen] = useState(false)
const [detailLoading, setDetailLoading] = useState(false) const [detailLoading, setDetailLoading] = useState(false)
const [detailError, setDetailError] = useState(false) const [detailError, setDetailError] = useState(false)
@ -158,6 +167,7 @@ export function NotificationDropdown() {
const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null) const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null)
const slideTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map()) const slideTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())
const pendingDeleteRef = useRef<PendingDelete | null>(null) const pendingDeleteRef = useRef<PendingDelete | null>(null)
const popupShownIdsRef = useRef<Set<string>>(new Set())
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const navigate = useNavigate() const navigate = useNavigate()
const { const {
@ -300,6 +310,39 @@ export function NotificationDropdown() {
[loadNotificationDetail], [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(() => { useEffect(() => {
function handleMouseDown(e: MouseEvent) { function handleMouseDown(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) { if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
@ -343,19 +386,18 @@ export function NotificationDropdown() {
{open && ( {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="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 justify-between gap-3 border-b px-4 py-3">
<div className="flex items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<h3 className="text-sm font-semibold text-grayScale-800">Notifications</h3> <h3 className="text-sm font-semibold text-grayScale-800">Notifications</h3>
{unreadCount > 0 && ( {unreadCount > 0 && (
<Badge variant="default" className="px-1.5 py-0 text-[10px]"> <Badge variant="default" className="px-1.5 py-0 text-[10px]">
{unreadCount} {unreadCount}
</Badge> </Badge>
)} )}
</div>
{unreadCount > 0 && ( {unreadCount > 0 && (
<button <button
type="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" 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} onClick={markAllAsRead}
> >
<CheckCheck className="h-3.5 w-3.5" /> <CheckCheck className="h-3.5 w-3.5" />
@ -363,6 +405,19 @@ export function NotificationDropdown() {
</button> </button>
)} )}
</div> </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>
</div>
<div className="max-h-[480px] overflow-y-auto"> <div className="max-h-[480px] overflow-y-auto">
{loading ? ( {loading ? (

View File

@ -312,4 +312,207 @@
.yimaru-toast[data-sonner-toast][data-styled="true"] { .yimaru-toast[data-sonner-toast][data-styled="true"] {
padding-right: 2.25rem; 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, DateRevenue,
LabelCount, LabelCount,
} from "../types/analytics.types" } from "../types/analytics.types"
import { APP_TIMEZONE } from "./datetime"
/** Canonical subscription row statuses shown in analytics breakdowns. */ /** Canonical subscription row statuses shown in analytics breakdowns. */
export const SUBSCRIPTION_STATUS_BREAKDOWN = [ export const SUBSCRIPTION_STATUS_BREAKDOWN = [
@ -140,7 +141,7 @@ export function formatAnalyticsSeriesDate(dateStr: string): string {
return d.toLocaleDateString("en-US", { return d.toLocaleDateString("en-US", {
month: "short", month: "short",
day: "numeric", day: "numeric",
timeZone: "UTC", timeZone: APP_TIMEZONE,
}) })
} }
const d = new Date(dateStr) const d = new Date(dateStr)
@ -148,7 +149,7 @@ export function formatAnalyticsSeriesDate(dateStr: string): string {
return d.toLocaleDateString("en-US", { return d.toLocaleDateString("en-US", {
month: "short", month: "short",
day: "numeric", day: "numeric",
timeZone: "UTC", timeZone: APP_TIMEZONE,
}) })
} }
@ -161,7 +162,7 @@ function formatShortDate(iso: string) {
month: "short", month: "short",
day: "numeric", day: "numeric",
year: "numeric", year: "numeric",
timeZone: "UTC", timeZone: APP_TIMEZONE,
}) })
} }
const d = new Date(iso) const d = new Date(iso)
@ -169,7 +170,7 @@ function formatShortDate(iso: string) {
month: "short", month: "short",
day: "numeric", day: "numeric",
year: "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())) 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. */ /** Calendar YYYY-MM-DD of an instant in the app timezone. */
export function toAppCalendarDate(iso: string | Date): string | null { export function toAppCalendarDate(iso: string | Date): string | null {
const d = typeof iso === "string" ? new Date(iso) : iso 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( export function formatAppDateTime(
iso: string | null | undefined, iso: string | null | undefined,
emptyLabel = "—", 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( export function formatAppTime(
iso: string | null | undefined, iso: string | null | undefined,
emptyLabel = "—", emptyLabel = "—",

View File

@ -8,7 +8,7 @@ import type {
} from "../types/notification.types" } from "../types/notification.types"
import { getUsers } from "../api/users.api" import { getUsers } from "../api/users.api"
import { getTeamMembers } from "../api/team.api" import { getTeamMembers } from "../api/team.api"
import { formatAppDateTime } from "./datetime" import { formatAppDateTime, toRfc3339FromAppLocal } from "./datetime"
import { TEAM_ROLE_OPTIONS } from "./teamRoles" import { TEAM_ROLE_OPTIONS } from "./teamRoles"
export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [ 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 = export type NotificationAudienceMode =
| "platform_role"
| "platform_selected" | "platform_selected"
| "team_role"
| "team_selected" | "team_selected"
| "direct" | "direct"
@ -81,35 +79,7 @@ export function toRfc3339Utc(
hour: string, hour: string,
minute: string, minute: string,
): string | null { ): string | null {
const y = Number(year) return toRfc3339FromAppLocal(year, month, day, hour, minute)
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()
} }
export function parseDirectRecipients(raw: string): string[] { export function parseDirectRecipients(raw: string): string[] {
@ -205,7 +175,7 @@ export function isAudienceModeValidForChannel(
channel: string, channel: string,
): boolean { ): boolean {
if (mode === "direct") return channel === "sms" || channel === "email" if (mode === "direct") return channel === "sms" || channel === "email"
if (mode === "team_role" || mode === "team_selected") { if (mode === "team_selected") {
return channelSupportsTeamTargeting(channel) return channelSupportsTeamTargeting(channel)
} }
return true 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, buildSubscriptionStatusPie,
} from "../lib/analytics" } from "../lib/analytics"
import type { DashboardData, DashboardFilters } from "../types/analytics.types" import type { DashboardData, DashboardFilters } from "../types/analytics.types"
import { formatAppDateTime } from "../lib/datetime"
import { formatAverageStars } from "../lib/ratingsDisplay" import { formatAverageStars } from "../lib/ratingsDisplay"
import { formatPlanDuration } from "../lib/subscriptionPlans" import { formatPlanDuration } from "../lib/subscriptionPlans"
import type { SubscriptionPlan } from "../types/subscription.types" import type { SubscriptionPlan } from "../types/subscription.types"
@ -184,14 +185,7 @@ export function DashboardPage() {
? getSubscriptionMetrics(dashboard.subscriptions) ? getSubscriptionMetrics(dashboard.subscriptions)
: null : null
const generatedAt = dashboard const generatedAt = dashboard ? formatAppDateTime(dashboard.generated_at) : ""
? new Date(dashboard.generated_at).toLocaleString("en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
: ""
const registrationPeakIndex = registrationData.reduce((best, row, idx) => { const registrationPeakIndex = registrationData.reduce((best, row, idx) => {
return row.count > (registrationData[best]?.count ?? 0) ? idx : best 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 { ProfileAvatarUpload } from "../components/profile/ProfileAvatarUpload";
import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField"; import { PersonaProfilePictureUploadField } from "./personas/components/PersonaProfilePictureUploadField";
import { UnassignedLabel, isUnassignedLabel, DisplayValue } from "../lib/displayValue" import { UnassignedLabel, isUnassignedLabel, DisplayValue } from "../lib/displayValue"
import { formatAppDateTime, formatAppLongDate } from "../lib/datetime"
function formatDate(dateStr: string | null | undefined): string { function formatDate(dateStr: string | null | undefined): string {
if (!dateStr) return "unassigned"; return formatAppLongDate(dateStr, "unassigned")
const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return dateStr;
return date.toLocaleDateString(undefined, {
year: "numeric",
month: "long",
day: "numeric",
});
} }
function formatDateTime(dateStr: string | null | undefined): string { function formatDateTime(dateStr: string | null | undefined): string {
if (!dateStr) return "unassigned"; return formatAppDateTime(dateStr, "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",
});
} }
function formatRoleLabel(role: string): string { function formatRoleLabel(role: string): string {

View File

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

View File

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

View File

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

View File

@ -13,6 +13,7 @@ import { Badge } from "../../../components/ui/badge"
import { Button } from "../../../components/ui/button" import { Button } from "../../../components/ui/button"
import { Card, CardContent } from "../../../components/ui/card" import { Card, CardContent } from "../../../components/ui/card"
import { channelLabel, formatScheduledAtLabel } from "../../../lib/notificationBulk" import { channelLabel, formatScheduledAtLabel } from "../../../lib/notificationBulk"
import { formatAppDateTimeSeconds } from "../../../lib/datetime"
import { cn } from "../../../lib/utils" import { cn } from "../../../lib/utils"
import type { NotificationChannel } from "../../../types/notification.types" import type { NotificationChannel } from "../../../types/notification.types"
import { UnassignedLabel } from "../../../lib/displayValue" import { UnassignedLabel } from "../../../lib/displayValue"
@ -107,14 +108,7 @@ export function BulkSendSummaryPanel({ summary, onDismiss }: BulkSendSummaryPane
: "Notification sent successfully" : "Notification sent successfully"
: "Notification scheduled" : "Notification scheduled"
const completedLabel = new Date(summary.completedAt).toLocaleString("en-US", { const completedLabel = formatAppDateTimeSeconds(summary.completedAt)
month: "short",
day: "numeric",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
const progressTotal = isImmediate ? Math.max(summary.total, 1) : 1 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"> <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"> <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> </p>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{!isImmediate ? ( {!isImmediate ? (

View File

@ -24,6 +24,7 @@ import { DisplayValue, NOT_ASSIGNED_LABEL, UnassignedLabel, displayValue, isUnas
import { getTeamMemberById, updateTeamMemberStatus } from "../../api/team.api" import { getTeamMemberById, updateTeamMemberStatus } from "../../api/team.api"
import type { TeamMemberDetail } from "../../types/team.types" import type { TeamMemberDetail } from "../../types/team.types"
import { ActivityLogListPanel } from "../user-log/components/ActivityLogListPanel" import { ActivityLogListPanel } from "../user-log/components/ActivityLogListPanel"
import { formatAppDateTime, formatAppLongDate } from "../../lib/datetime"
function formatStatusLabel(status: string): string { function formatStatusLabel(status: string): string {
const value = status.trim() const value = status.trim()
@ -35,30 +36,14 @@ function formatStatusLabel(status: string): string {
} }
function formatDate(dateStr: string | null | undefined): string { function formatDate(dateStr: string | null | undefined): string {
if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL return formatAppLongDate(dateStr, 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",
})
} }
function formatDateTime( function formatDateTime(
dateStr: string | null | undefined, dateStr: string | null | undefined,
emptyLabel: string = NOT_ASSIGNED_LABEL, emptyLabel: string = NOT_ASSIGNED_LABEL,
): string { ): string {
if (!dateStr?.trim()) return emptyLabel return formatAppDateTime(dateStr, 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",
})
} }
function getRelativeTime(dateStr: string | null | undefined): string { 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 { mapDeletionRequestApiItem } from "../../types/user.types"
import { UnassignedLabel } from "../../lib/displayValue" import { UnassignedLabel } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight" import { SearchHighlight } from "../../components/SearchHighlight"
import { fromDatetimeLocalAppValue } from "../../lib/datetime"
const stateBadge: Record<string, string> = { const stateBadge: Record<string, string> = {
PENDING: "bg-amber-100 text-amber-700", PENDING: "bg-amber-100 text-amber-700",
@ -90,12 +91,7 @@ export function DeletionRequestsPage() {
const statusMenuRef = useRef<HTMLDivElement | null>(null) const statusMenuRef = useRef<HTMLDivElement | null>(null)
const stateMenuRef = useRef<HTMLDivElement | null>(null) const stateMenuRef = useRef<HTMLDivElement | null>(null)
const toRfc3339 = (value: string) => { const toRfc3339 = (value: string) => fromDatetimeLocalAppValue(value)
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 fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
setLoading(true) setLoading(true)

View File

@ -47,6 +47,11 @@ import {
displayUserFavouriteTopic, displayUserFavouriteTopic,
displayUserCountry, displayUserCountry,
} from "../../lib/userProfileFieldDisplay" } from "../../lib/userProfileFieldDisplay"
import {
formatAppDateTime,
formatAppLongDate,
formatAppRelativeDateTime,
} from "../../lib/datetime"
const activityIcons = { const activityIcons = {
completed: CheckCircle2, completed: CheckCircle2,
@ -84,52 +89,15 @@ function formatStatusLabel(status: string): string {
} }
function formatDate(dateStr: string | null | undefined): string { function formatDate(dateStr: string | null | undefined): string {
if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL; return formatAppLongDate(dateStr, 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",
});
} }
function formatDateTime(value?: string | null, emptyLabel = NOT_ASSIGNED_LABEL): string { function formatDateTime(value?: string | null, emptyLabel = NOT_ASSIGNED_LABEL): string {
if (!value?.trim()) return emptyLabel; return formatAppDateTime(value, 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",
});
} }
function formatActivityOccurredAt(iso: string): string { function formatActivityOccurredAt(iso: string): string {
const d = new Date(iso); return formatAppRelativeDateTime(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",
});
} }
function getAccountStatusClasses(status: string): string { function getAccountStatusClasses(status: string): string {

View File

@ -29,22 +29,7 @@ import { usersExportQuery } from "../../lib/csvExportFilters"
import { UnassignedLabel } from "../../lib/displayValue" import { UnassignedLabel } from "../../lib/displayValue"
import { SearchHighlight } from "../../components/SearchHighlight" import { SearchHighlight } from "../../components/SearchHighlight"
import { displayUserRegion, displayUserCountry } from "../../lib/userProfileFieldDisplay" import { displayUserRegion, displayUserCountry } from "../../lib/userProfileFieldDisplay"
import { APP_TIMEZONE_LABEL, formatAppDateTime, fromDatetimeLocalAppValue } from "../../lib/datetime"
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()
}
/** Portaled menu — native `<select>` lists break inside `overflow-y-auto` shells (e.g. app main). */ /** Portaled menu — native `<select>` lists break inside `overflow-y-auto` shells (e.g. app main). */
function UserListFilterDropdown({ function UserListFilterDropdown({
@ -184,8 +169,8 @@ export function UsersListPage() {
page, page,
page_size: pageSize, page_size: pageSize,
query: search || undefined, query: search || undefined,
created_after: toRfc3339FromDatetimeLocal(createdAfterLocal), created_after: fromDatetimeLocalAppValue(createdAfterLocal),
created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal), created_before: fromDatetimeLocalAppValue(createdBeforeLocal),
country: countryFilter.trim() || undefined, country: countryFilter.trim() || undefined,
region: region:
(!countryFilter.trim() || countryFilter.trim().toLowerCase() === "ethiopia") && (!countryFilter.trim() || countryFilter.trim().toLowerCase() === "ethiopia") &&
@ -352,8 +337,8 @@ export function UsersListPage() {
() => () =>
usersExportQuery({ usersExportQuery({
query: search || undefined, query: search || undefined,
created_after: toRfc3339FromDatetimeLocal(createdAfterLocal), created_after: fromDatetimeLocalAppValue(createdAfterLocal),
created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal), created_before: fromDatetimeLocalAppValue(createdBeforeLocal),
country: countryFilter.trim() || undefined, country: countryFilter.trim() || undefined,
region: region:
(!countryFilter.trim() || countryFilter.trim().toLowerCase() === "ethiopia") && (!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="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<label htmlFor="filter-created-after" className="text-xs font-medium text-grayScale-500"> <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> </label>
<input <input
id="filter-created-after" id="filter-created-after"
@ -512,7 +497,7 @@ export function UsersListPage() {
</div> </div>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<label htmlFor="filter-created-before" className="text-xs font-medium text-grayScale-500"> <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> </label>
<input <input
id="filter-created-before" id="filter-created-before"
@ -663,7 +648,7 @@ export function UsersListPage() {
{displayUserRegion(u.region)} {displayUserRegion(u.region)}
</TableCell> </TableCell>
<TableCell className="hidden md:table-cell text-sm text-grayScale-500 whitespace-nowrap"> <TableCell className="hidden md:table-cell text-sm text-grayScale-500 whitespace-nowrap">
{formatJoinedAt(u.createdAt)} {formatAppDateTime(u.createdAt, "unassigned")}
</TableCell> </TableCell>
<TableCell className="hidden lg:table-cell align-top text-sm text-grayScale-600"> <TableCell className="hidden lg:table-cell align-top text-sm text-grayScale-600">
<span <span