Align admin dates with EAT and refine analytics, payments, and toasts.

Use Africa/Addis_Ababa for display and filters, add payment method and date range controls, and restyle Sonner notifications to match the admin UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-08-04 15:23:15 +03:00
parent 47893a7838
commit 992ca85690
26 changed files with 703 additions and 269 deletions

View File

@ -1,9 +1,9 @@
import { Toaster } from 'sonner'
import { AppRoutes } from './app/AppRoutes'
import { useTheme } from './contexts/ThemeContext'
import { clearTeamSession } from './lib/teamAuthStorage'
import { Toaster } from "sonner"
import { AppRoutes } from "./app/AppRoutes"
import { useTheme } from "./contexts/ThemeContext"
import { clearTeamSession } from "./lib/teamAuthStorage"
const SESSION_KEY = 'yimaru_session_active'
const SESSION_KEY = "yimaru_session_active"
/**
* Clear persisted team tokens when this browser tab session is new.
@ -14,7 +14,7 @@ function bootstrapBrowserSession() {
try {
if (!sessionStorage.getItem(SESSION_KEY)) {
clearTeamSession()
sessionStorage.setItem(SESSION_KEY, '1')
sessionStorage.setItem(SESSION_KEY, "1")
}
} catch {
// sessionStorage unavailable (private mode quirks) — leave tokens alone
@ -29,15 +29,26 @@ function AppToaster() {
<Toaster
position="top-center"
theme={resolvedTheme}
closeButton
expand={false}
visibleToasts={4}
offset={20}
gap={12}
duration={4200}
toastOptions={{
className: 'font-sans',
style: {
padding: '14px 20px',
borderRadius: '12px',
fontSize: '14px',
classNames: {
toast: "yimaru-toast",
title: "yimaru-toast__title",
description: "yimaru-toast__description",
actionButton: "yimaru-toast__action",
cancelButton: "yimaru-toast__cancel",
closeButton: "yimaru-toast__close",
success: "yimaru-toast--success",
error: "yimaru-toast--error",
warning: "yimaru-toast--warning",
info: "yimaru-toast--info",
},
}}
richColors
/>
)
}

View File

@ -8,23 +8,34 @@ import type {
} from "../types/analytics.types";
function buildDashboardQueryParams(filters?: DashboardFilters): Record<string, string | number> {
const params: Record<string, string | number> = {};
if (filters?.payment_method?.trim()) {
params.payment_method = filters.payment_method.trim().toUpperCase();
}
if (!filters || filters.mode === "all_time") {
return {};
return params;
}
if (filters.mode === "year" && filters.year != null) {
return { year: filters.year };
params.year = filters.year;
return params;
}
if (filters.mode === "year_month" && filters.year != null && filters.month != null) {
return { year: filters.year, month: filters.month };
params.year = filters.year;
params.month = filters.month;
return params;
}
if (filters.mode === "custom" && filters.from && filters.to) {
return { from: filters.from, to: filters.to };
params.from = filters.from;
params.to = filters.to;
return params;
}
return {};
return params;
}
function isRecord(value: unknown): value is Record<string, unknown> {

View File

@ -91,6 +91,10 @@ function buildQueryParams(params: GetPaymentsParams): Record<string, string | nu
if (params.plan_category?.trim()) query.plan_category = params.plan_category.trim()
if (params.currency?.trim()) query.currency = params.currency.trim()
if (params.reference?.trim()) query.reference = params.reference.trim()
if (params.created_from?.trim()) query.created_from = params.created_from.trim()
if (params.created_to?.trim()) query.created_to = params.created_to.trim()
if (params.paid_from?.trim()) query.paid_from = params.paid_from.trim()
if (params.paid_to?.trim()) query.paid_to = params.paid_to.trim()
return query
}
@ -107,6 +111,10 @@ export function paymentsFilterParams(
if (params.plan_category?.trim()) next.plan_category = params.plan_category.trim()
if (params.currency?.trim()) next.currency = params.currency.trim()
if (params.reference?.trim()) next.reference = params.reference.trim()
if (params.created_from?.trim()) next.created_from = params.created_from.trim()
if (params.created_to?.trim()) next.created_to = params.created_to.trim()
if (params.paid_from?.trim()) next.paid_from = params.paid_from.trim()
if (params.paid_to?.trim()) next.paid_to = params.paid_to.trim()
return next
}

View File

@ -3,6 +3,8 @@ import { ChevronDown } from "lucide-react"
import { cn } from "../../lib/utils"
import { Input } from "../ui/input"
import { Button } from "../ui/button"
import { Select } from "../ui/select"
import { formatPaymentMethod } from "../../lib/payments"
import type { DashboardFilters } from "../../types/analytics.types"
const MONTH_LABELS = [
@ -22,6 +24,14 @@ const MONTH_LABELS = [
const MIN_SELECTABLE_YEAR = 2000
export const ANALYTICS_PAYMENT_METHOD_OPTIONS = [
{ value: "", label: "All methods" },
{ value: "CHAPA", label: "Chapa" },
{ value: "ARIFPAY", label: "Arifpay" },
{ value: "ADMIN_GRANT", label: "Admin grant" },
{ value: "ADMIN_EXTEND", label: "Admin extend" },
] as const
export function getYearOptions(): number[] {
const currentYear = new Date().getFullYear()
const years: number[] = []
@ -31,20 +41,38 @@ export function getYearOptions(): number[] {
return years
}
function withPaymentMethod(base: DashboardFilters, paymentMethod?: string): DashboardFilters {
const next = { ...base }
if (paymentMethod?.trim()) {
next.payment_method = paymentMethod.trim().toUpperCase()
} else {
delete next.payment_method
}
return next
}
export function getDashboardFilterLabel(filters: DashboardFilters): string {
let rangeLabel = "All Time"
if (filters.mode === "year" && filters.year != null) {
return String(filters.year)
rangeLabel = String(filters.year)
} else if (filters.mode === "year_month" && filters.year != null && filters.month != null) {
rangeLabel = `${MONTH_LABELS[filters.month - 1]} ${filters.year}`
} else if (filters.mode === "custom" && filters.from && filters.to) {
const opts: Intl.DateTimeFormatOptions = {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
}
const from = new Date(`${filters.from}T00:00:00Z`)
const to = new Date(`${filters.to}T00:00:00Z`)
rangeLabel = `${from.toLocaleDateString("en-US", opts)} – ${to.toLocaleDateString("en-US", opts)}`
}
if (filters.mode === "year_month" && filters.year != null && filters.month != null) {
return `${MONTH_LABELS[filters.month - 1]} ${filters.year}`
if (!filters.payment_method) {
return rangeLabel
}
if (filters.mode === "custom" && filters.from && filters.to) {
const from = new Date(`${filters.from}T00:00:00`)
const to = new Date(`${filters.to}T00:00:00`)
const opts: Intl.DateTimeFormatOptions = { month: "short", day: "numeric", year: "numeric" }
return `${from.toLocaleDateString("en-US", opts)} – ${to.toLocaleDateString("en-US", opts)}`
}
return "All Time"
return `${rangeLabel} · ${formatPaymentMethod(filters.payment_method)}`
}
type AnalyticsTimeRangeFilterProps = {
@ -64,6 +92,7 @@ export function AnalyticsTimeRangeFilter({ value, onChange, className }: Analyti
const containerRef = useRef<HTMLDivElement>(null)
const years = getYearOptions()
const paymentMethod = value.payment_method ?? ""
useEffect(() => {
if (value.year != null) {
@ -92,181 +121,200 @@ export function AnalyticsTimeRangeFilter({ value, onChange, className }: Analyti
}, [open])
const selectAllTime = () => {
onChange({ mode: "all_time" })
onChange(withPaymentMethod({ mode: "all_time" }, paymentMethod))
setOpen(false)
}
const selectYear = (year: number) => {
setContextYear(year)
onChange({ mode: "year", year })
onChange(withPaymentMethod({ mode: "year", year }, paymentMethod))
setOpen(false)
}
const selectMonth = (month: number) => {
onChange({ mode: "year_month", year: contextYear, month })
onChange(withPaymentMethod({ mode: "year_month", year: contextYear, month }, paymentMethod))
setOpen(false)
}
const applyCustomRange = () => {
if (!customFrom || !customTo) return
onChange({ mode: "custom", from: customFrom, to: customTo })
onChange(withPaymentMethod({ mode: "custom", from: customFrom, to: customTo }, paymentMethod))
setOpen(false)
}
const selectPaymentMethod = (nextMethod: string) => {
onChange(withPaymentMethod({ ...value }, nextMethod))
}
return (
<div ref={containerRef} className={cn("relative", className)}>
<button
type="button"
onClick={() => setOpen((prev) => !prev)}
className="inline-flex items-center gap-2 rounded-lg border border-grayScale-200 bg-white px-4 py-2 text-sm font-medium text-grayScale-700 shadow-sm transition-colors hover:bg-grayScale-50"
<div className={cn("flex flex-wrap items-center gap-2", className)}>
<Select
value={paymentMethod}
onChange={(e) => selectPaymentMethod(e.target.value)}
className="h-9 w-[150px] rounded-lg border-grayScale-200 py-1 text-sm font-medium"
aria-label="Payment method filter"
>
Time Range
<ChevronDown className={cn("h-4 w-4 text-grayScale-400 transition-transform", open && "rotate-180")} />
</button>
{ANALYTICS_PAYMENT_METHOD_OPTIONS.map((option) => (
<option key={option.value || "all"} value={option.value}>
{option.label}
</option>
))}
</Select>
{open && (
<div className="absolute right-0 z-50 mt-2 w-[220px] overflow-hidden rounded-xl border border-grayScale-100 bg-white py-2 shadow-lg">
<button
type="button"
onClick={selectAllTime}
className={cn(
"flex w-full px-4 py-2.5 text-left text-sm transition-colors hover:bg-grayScale-50",
value.mode === "all_time" ? "font-semibold text-grayScale-900" : "text-grayScale-700",
)}
>
All Time
</button>
<div ref={containerRef} className="relative">
<button
type="button"
onClick={() => setOpen((prev) => !prev)}
className="inline-flex items-center gap-2 rounded-lg border border-grayScale-200 bg-white px-4 py-2 text-sm font-medium text-grayScale-700 shadow-sm transition-colors hover:bg-grayScale-50"
>
Time Range
<ChevronDown className={cn("h-4 w-4 text-grayScale-400 transition-transform", open && "rotate-180")} />
</button>
<div className="border-t border-grayScale-100">
{open && (
<div className="absolute right-0 z-50 mt-2 w-[220px] overflow-hidden rounded-xl border border-grayScale-100 bg-white py-2 shadow-lg">
<button
type="button"
onClick={() => setYearOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
onClick={selectAllTime}
className={cn(
"flex w-full px-4 py-2.5 text-left text-sm transition-colors hover:bg-grayScale-50",
value.mode === "all_time" ? "font-semibold text-grayScale-900" : "text-grayScale-700",
)}
>
Year
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", yearOpen && "rotate-180")}
/>
All Time
</button>
{yearOpen && (
<div className="max-h-[220px] overflow-y-auto pb-1">
{years.map((year) => (
<button
key={year}
type="button"
onClick={() => selectYear(year)}
className={cn(
"flex w-full px-6 py-2 text-left text-sm transition-colors hover:bg-grayScale-50",
value.mode === "year" && value.year === year
? "font-semibold text-brand-600"
: "text-grayScale-600",
)}
>
{year}
</button>
))}
</div>
)}
</div>
<div className="border-t border-grayScale-100">
<button
type="button"
onClick={() => setMonthOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
>
Month
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", monthOpen && "rotate-180")}
/>
</button>
{monthOpen && (
<div className="max-h-[260px] overflow-y-auto pb-1">
<div className="flex max-h-[88px] flex-wrap gap-1 overflow-y-auto px-4 pb-2">
<div className="border-t border-grayScale-100">
<button
type="button"
onClick={() => setYearOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
>
Year
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", yearOpen && "rotate-180")}
/>
</button>
{yearOpen && (
<div className="max-h-[220px] overflow-y-auto pb-1">
{years.map((year) => (
<button
key={year}
type="button"
onClick={() => setContextYear(year)}
onClick={() => selectYear(year)}
className={cn(
"rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors",
contextYear === year
? "bg-brand-100 text-brand-700"
: "text-grayScale-500 hover:bg-grayScale-100",
"flex w-full px-6 py-2 text-left text-sm transition-colors hover:bg-grayScale-50",
value.mode === "year" && value.year === year
? "font-semibold text-brand-600"
: "text-grayScale-600",
)}
>
{year}
</button>
))}
</div>
{MONTH_LABELS.map((label, index) => {
const month = index + 1
const isSelected =
value.mode === "year_month" && value.year === contextYear && value.month === month
)}
</div>
return (
<button
key={label}
type="button"
onClick={() => selectMonth(month)}
className={cn(
"flex w-full px-6 py-2 text-left text-sm transition-colors hover:bg-grayScale-50",
isSelected ? "font-semibold text-brand-600" : "text-grayScale-600",
)}
>
{label}
</button>
)
})}
</div>
)}
</div>
<div className="border-t border-grayScale-100">
<button
type="button"
onClick={() => setMonthOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
>
Month
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", monthOpen && "rotate-180")}
/>
</button>
{monthOpen && (
<div className="max-h-[260px] overflow-y-auto pb-1">
<div className="flex max-h-[88px] flex-wrap gap-1 overflow-y-auto px-4 pb-2">
{years.map((year) => (
<button
key={year}
type="button"
onClick={() => setContextYear(year)}
className={cn(
"rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors",
contextYear === year
? "bg-brand-100 text-brand-700"
: "text-grayScale-500 hover:bg-grayScale-100",
)}
>
{year}
</button>
))}
</div>
{MONTH_LABELS.map((label, index) => {
const month = index + 1
const isSelected =
value.mode === "year_month" && value.year === contextYear && value.month === month
<div className="border-t border-grayScale-100">
<button
type="button"
onClick={() => setCustomOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
>
Date Range
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", customOpen && "rotate-180")}
/>
</button>
{customOpen && (
<div className="space-y-2 px-4 pb-3">
<div className="space-y-1">
<label className="text-[11px] font-medium text-grayScale-500">From</label>
<Input
type="date"
value={customFrom}
onChange={(e) => setCustomFrom(e.target.value)}
className="h-8 text-xs"
/>
return (
<button
key={label}
type="button"
onClick={() => selectMonth(month)}
className={cn(
"flex w-full px-6 py-2 text-left text-sm transition-colors hover:bg-grayScale-50",
isSelected ? "font-semibold text-brand-600" : "text-grayScale-600",
)}
>
{label}
</button>
)
})}
</div>
<div className="space-y-1">
<label className="text-[11px] font-medium text-grayScale-500">To</label>
<Input
type="date"
value={customTo}
onChange={(e) => setCustomTo(e.target.value)}
className="h-8 text-xs"
/>
)}
</div>
<div className="border-t border-grayScale-100">
<button
type="button"
onClick={() => setCustomOpen((prev) => !prev)}
className="flex w-full items-center justify-between px-4 py-2.5 text-left text-sm font-medium text-grayScale-800 hover:bg-grayScale-50"
>
Date Range
<ChevronDown
className={cn("h-4 w-4 text-grayScale-400 transition-transform", customOpen && "rotate-180")}
/>
</button>
{customOpen && (
<div className="space-y-2 px-4 pb-3">
<div className="space-y-1">
<label className="text-[11px] font-medium text-grayScale-500">From</label>
<Input
type="date"
value={customFrom}
onChange={(e) => setCustomFrom(e.target.value)}
className="h-8 text-xs"
/>
</div>
<div className="space-y-1">
<label className="text-[11px] font-medium text-grayScale-500">To</label>
<Input
type="date"
value={customTo}
onChange={(e) => setCustomTo(e.target.value)}
className="h-8 text-xs"
/>
</div>
<Button
type="button"
size="sm"
className="h-8 w-full text-xs"
disabled={!customFrom || !customTo}
onClick={applyCustomRange}
>
Apply
</Button>
</div>
<Button
type="button"
size="sm"
className="h-8 w-full text-xs"
disabled={!customFrom || !customTo}
onClick={applyCustomRange}
>
Apply
</Button>
</div>
)}
)}
</div>
</div>
</div>
)}
)}
</div>
</div>
)
}

View File

@ -11,7 +11,7 @@ import { aggregateRevenueByMonth, formatRevenueAxisTick } from "../../lib/analyt
import type { DateRevenue } from "../../types/analytics.types"
import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"
export function RevenueTrendCard() {
export function RevenueTrendCard({ paymentMethod }: { paymentMethod?: string }) {
const currentYear = new Date().getFullYear()
const [year, setYear] = useState(currentYear)
const [totalRevenue, setTotalRevenue] = useState(0)
@ -26,7 +26,11 @@ export function RevenueTrendCard() {
const fetchRevenueTrend = async () => {
setLoading(true)
try {
const res = await getDashboard({ mode: "year", year })
const res = await getDashboard({
mode: "year",
year,
...(paymentMethod ? { payment_method: paymentMethod } : {}),
})
if (cancelled) return
setTotalRevenue(res.data.payments.total_revenue)
setDailyRevenue(res.data.payments.revenue_last_30_days)
@ -44,7 +48,7 @@ export function RevenueTrendCard() {
return () => {
cancelled = true
}
}, [year])
}, [year, paymentMethod])
const chartData = useMemo(
() => aggregateRevenueByMonth(dailyRevenue, year),

View File

@ -175,4 +175,141 @@
.scrollbar-none::-webkit-scrollbar {
display: none;
}
/* Sonner toast — polished admin notifications */
[data-sonner-toaster] {
--width: min(420px, calc(100vw - 2rem));
font-family: inherit;
}
[data-sonner-toaster][data-y-position="top"] {
top: 1.25rem;
}
.yimaru-toast[data-sonner-toast] {
--yimaru-toast-accent: #9e2891;
width: var(--width);
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 1rem 0.875rem 1rem;
border-radius: 0.75rem;
border: 1px solid var(--gs-200);
border-left: 3px solid var(--yimaru-toast-accent);
background: var(--gs-50);
color: hsl(var(--foreground));
box-shadow:
0 1px 2px rgba(15, 23, 42, 0.04),
0 12px 32px rgba(15, 23, 42, 0.1);
font-size: 0.875rem;
line-height: 1.4;
letter-spacing: -0.01em;
}
html.dark .yimaru-toast[data-sonner-toast] {
box-shadow:
0 1px 2px rgba(0, 0, 0, 0.25),
0 16px 40px rgba(0, 0, 0, 0.45);
}
.yimaru-toast[data-sonner-toast] [data-icon] {
margin-top: 0.1rem;
width: 1.125rem;
height: 1.125rem;
flex-shrink: 0;
color: var(--yimaru-toast-accent);
}
.yimaru-toast[data-sonner-toast] [data-icon] svg {
width: 1.125rem;
height: 1.125rem;
}
.yimaru-toast[data-sonner-toast] [data-content] {
flex: 1;
min-width: 0;
gap: 0.2rem;
}
.yimaru-toast__title {
font-size: 0.875rem;
font-weight: 600;
color: hsl(var(--foreground));
letter-spacing: -0.015em;
}
.yimaru-toast__description {
font-size: 0.8125rem;
font-weight: 400;
color: var(--gs-500);
line-height: 1.45;
}
.yimaru-toast__close {
position: absolute !important;
top: 0.55rem !important;
right: 0.55rem !important;
left: auto !important;
transform: none !important;
width: 1.5rem !important;
height: 1.5rem !important;
border-radius: 0.375rem !important;
border: 1px solid transparent !important;
background: transparent !important;
color: var(--gs-400) !important;
opacity: 0.85;
transition:
background-color 0.15s ease,
color 0.15s ease,
border-color 0.15s ease;
}
.yimaru-toast__close:hover {
background: var(--gs-100) !important;
border-color: var(--gs-200) !important;
color: var(--gs-600) !important;
opacity: 1;
}
.yimaru-toast__action {
margin-top: 0.35rem;
height: 1.75rem;
padding: 0 0.75rem;
border-radius: 0.375rem;
background: #9e2891;
color: #fff;
font-size: 0.75rem;
font-weight: 600;
}
.yimaru-toast__cancel {
margin-top: 0.35rem;
height: 1.75rem;
padding: 0 0.75rem;
border-radius: 0.375rem;
background: var(--gs-100);
color: var(--gs-600);
font-size: 0.75rem;
font-weight: 500;
}
.yimaru-toast--success {
--yimaru-toast-accent: #059669;
}
.yimaru-toast--error {
--yimaru-toast-accent: #dc2626;
}
.yimaru-toast--warning {
--yimaru-toast-accent: #d97706;
}
.yimaru-toast--info {
--yimaru-toast-accent: #9e2891;
}
.yimaru-toast[data-sonner-toast][data-styled="true"] {
padding-right: 2.25rem;
}
}

View File

@ -1,5 +1,6 @@
import { getTeamMemberById } from "../api/team.api"
import { getUserById } from "../api/users.api"
import { formatAppDate } from "./datetime"
import { TEAM_ROLE_OPTIONS, formatTeamRoleLabel } from "./teamRoles"
import type { TeamMember, TeamMemberDetail } from "../types/team.types"
import type { UserProfileData } from "../types/user.types"
@ -149,11 +150,5 @@ export async function fetchActorProfile(
}
export function formatActorDate(iso: string): string {
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
return d.toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
})
return formatAppDate(iso, iso)
}

View File

@ -1,4 +1,10 @@
import type { ActivityLog, ActivityLogActorKind } from "../types/activity-log.types"
import {
formatAppDate,
formatAppTime,
toAppDayEndISO,
toAppDayStartISO,
} from "./datetime"
export type ActorDisplay = {
name: string
@ -355,19 +361,11 @@ export function activityLogResourcePath(
}
export function formatActivityDate(dateStr: string): string {
return new Date(dateStr).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
})
return formatAppDate(dateStr, "—")
}
export function formatActivityTime(dateStr: string): string {
return new Date(dateStr).toLocaleTimeString(undefined, {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
})
return formatAppTime(dateStr, "—")
}
export function getRelativeActivityTime(dateStr: string): string {
@ -386,9 +384,9 @@ export function getRelativeActivityTime(dateStr: string): string {
}
export function toRfc3339StartOfDay(dateValue: string): string {
return new Date(`${dateValue}T00:00:00`).toISOString()
return toAppDayStartISO(dateValue)
}
export function toRfc3339EndOfDay(dateValue: string): string {
return new Date(`${dateValue}T23:59:59.999`).toISOString()
return toAppDayEndISO(dateValue)
}

View File

@ -121,9 +121,56 @@ const MONTH_SHORT = [
"Dec",
] as const
/** Calendar Y-M-D from an analytics series date (API encodes civil days as UTC midnight). */
export function analyticsSeriesYmd(dateStr: string): string | null {
const match = /^(\d{4}-\d{2}-\d{2})/.exec(String(dateStr ?? "").trim())
return match ? match[1] : null
}
/**
* Format a daily analytics series date for charts.
* Uses the civil YYYY-MM-DD from the API — never the browser local timezone —
* so EAT buckets stay aligned with payments/Chapa.
*/
export function formatAnalyticsSeriesDate(dateStr: string): string {
const ymd = analyticsSeriesYmd(dateStr)
if (ymd) {
const [year, month, day] = ymd.split("-").map(Number)
const d = new Date(Date.UTC(year, month - 1, day))
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
})
}
const d = new Date(dateStr)
if (Number.isNaN(d.getTime())) return String(dateStr)
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
timeZone: "UTC",
})
}
function formatShortDate(iso: string) {
const ymd = analyticsSeriesYmd(iso)
if (ymd) {
const [year, month, day] = ymd.split("-").map(Number)
const d = new Date(Date.UTC(year, month - 1, day))
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
})
}
const d = new Date(iso)
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
return d.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
})
}
function formatBreakdownLabel(label: string) {
@ -154,8 +201,14 @@ export function aggregateRevenueByMonth(daily: DateRevenue[], year: number): Mon
}))
for (const { date, revenue } of daily) {
const parsed = new Date(date)
if (parsed.getUTCFullYear() !== year) continue
const ymd = analyticsSeriesYmd(date)
const parsed = ymd
? (() => {
const [year, month, day] = ymd.split("-").map(Number)
return new Date(Date.UTC(year, month - 1, day))
})()
: new Date(date)
if (Number.isNaN(parsed.getTime()) || parsed.getUTCFullYear() !== year) continue
monthly[parsed.getUTCMonth()].revenue += revenue
}

View File

@ -4,6 +4,7 @@ import type {
AppVersion,
AppVersionStatus,
} from "../types/app-version.types"
import { formatAppDateTime } from "./datetime"
export const APP_PLATFORMS: { value: AppPlatform; label: string }[] = [
{ value: "ANDROID", label: "Android" },
@ -65,13 +66,7 @@ export function formatAppVersionCreatedAt(raw: string): string {
const datePart = raw.split(" ")[0]
return datePart || raw
}
return d.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(normalized)
}
export function versionLabel(version: Pick<AppVersion, "version_name" | "version_code">): string {

View File

@ -1,6 +1,7 @@
import type { GetUsersParams } from "../api/users.api"
import { buildUsersListQuery } from "../api/users.api"
import { paymentsFilterParams } from "../api/payments.api"
import { nextCalendarDay } from "./payments"
import type { ActivityLogFilters } from "../types/activity-log.types"
import type { QueryParams } from "./csv-export"
@ -10,13 +11,21 @@ export function paymentListFiltersToExportQuery(filters: {
planCategory?: string
currency?: string
reference?: string
/** Inclusive YYYY-MM-DD; mapped to created_from. */
dateFrom?: string
/** Inclusive YYYY-MM-DD; mapped to exclusive created_to. */
dateTo?: string
}): QueryParams {
const dateFrom = filters.dateFrom?.trim()
const dateTo = filters.dateTo?.trim()
return paymentsFilterParams({
...(filters.status ? { status: filters.status } : {}),
...(filters.provider ? { provider: filters.provider } : {}),
...(filters.planCategory ? { plan_category: filters.planCategory } : {}),
...(filters.currency ? { currency: filters.currency } : {}),
...(filters.reference ? { reference: filters.reference } : {}),
...(dateFrom ? { created_from: dateFrom } : {}),
...(dateTo ? { created_to: nextCalendarDay(dateTo) } : {}),
})
}

96
src/lib/datetime.ts Normal file
View File

@ -0,0 +1,96 @@
/** Default business timezone for Yimaru (East Africa Time, UTC+3, no DST). */
export const APP_TIMEZONE = "Africa/Addis_Ababa"
export const APP_TIMEZONE_LABEL = "EAT"
/** Fixed offset used when building RFC3339 bounds from calendar days. */
export const APP_TIMEZONE_OFFSET = "+03:00"
export function isValidDateInput(value: string | null | undefined): value is string {
return Boolean(value && /^\d{4}-\d{2}-\d{2}/.test(value.trim()))
}
/** 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
if (Number.isNaN(d.getTime())) return null
return new Intl.DateTimeFormat("en-CA", {
timeZone: APP_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(d)
}
export function formatAppDate(
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: "short",
day: "numeric",
})
}
export function formatAppDateTime(
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",
hour12: false,
})
}
export function formatAppTime(
iso: string | null | undefined,
emptyLabel = "—",
): string {
if (!iso) return emptyLabel
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return emptyLabel
return d.toLocaleTimeString("en-GB", {
timeZone: APP_TIMEZONE,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
}
/** Midnight EAT for a YYYY-MM-DD calendar day, as RFC3339. */
export function toAppDayStartISO(ymd: string): string {
const day = ymd.trim().slice(0, 10)
return `${day}T00:00:00${APP_TIMEZONE_OFFSET}`
}
/** End of EAT calendar day (inclusive-style), as RFC3339. */
export function toAppDayEndISO(ymd: string): string {
const day = ymd.trim().slice(0, 10)
return `${day}T23:59:59.999${APP_TIMEZONE_OFFSET}`
}
/** Next calendar day (UTC date arithmetic on Y-M-D components). */
export function nextAppCalendarDay(ymd: string): string {
const [year, month, day] = ymd.trim().slice(0, 10).split("-").map(Number)
if (!year || !month || !day) return ymd
const dt = new Date(Date.UTC(year, month - 1, day))
dt.setUTCDate(dt.getUTCDate() + 1)
return dt.toISOString().slice(0, 10)
}
/** Exclusive upper bound: next EAT midnight after ymd. */
export function toAppNextDayStartISO(ymd: string): string {
return toAppDayStartISO(nextAppCalendarDay(ymd))
}

View File

@ -1,3 +1,5 @@
import { formatAppDateTime } from "./datetime"
const SAMPLE_VALUES: Record<string, string> = {
OTP: "123456",
FirstName: "Alex",
@ -42,10 +44,7 @@ export function formatEmailTemplateDate(raw: string | null | undefined) {
if (Number.isNaN(parsed.getTime())) {
return text.split(" +")[0]?.trim() || text
}
return parsed.toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
})
return formatAppDateTime(text)
}
export function emailTemplateStatusBadgeVariant(status: string) {

View File

@ -1,4 +1,5 @@
import type { FAQ, FAQStatus } from "../types/faq.types"
import { formatAppDateTime } from "./datetime"
export function faqStatusBadgeVariant(status: string): "success" | "secondary" {
const normalized = status.toUpperCase()
@ -22,10 +23,7 @@ export function formatFaqDate(raw: string | null | undefined): string {
if (Number.isNaN(parsed.getTime())) {
return text.split(" +")[0]?.trim() || text
}
return parsed.toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
})
return formatAppDateTime(text)
}
export function deriveFaqCategories(faqs: FAQ[]): string[] {

View File

@ -8,6 +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 { TEAM_ROLE_OPTIONS } from "./teamRoles"
export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [
@ -122,13 +123,7 @@ export function formatScheduledAtLabel(value: string): string {
if (!value) return "Set date & time"
const parsed = new Date(value)
if (Number.isNaN(parsed.getTime())) return value
return parsed.toLocaleString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(value)
}
export function scheduledStatusBadgeVariant(

View File

@ -10,6 +10,7 @@ import {
Video,
ShieldAlert,
} from "lucide-react"
import { formatAppDate, formatAppDateTime } from "./datetime"
export const NOTIFICATION_TYPE_CONFIG: Record<
string,
@ -67,11 +68,7 @@ export function formatNotificationTimestamp(ts: string) {
if (diffHr < 24) return `${diffHr}h ago`
if (diffDay < 7) return `${diffDay}d ago`
return date.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: date.getFullYear() !== now.getFullYear() ? "numeric" : undefined,
})
return formatAppDate(ts)
}
export function formatNotificationTypeLabel(type: string) {
@ -82,15 +79,7 @@ export function formatNotificationTypeLabel(type: string) {
}
export function formatNotificationDateTime(ts: string) {
const date = new Date(ts)
if (Number.isNaN(date.getTime())) return "unassigned"
return date.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(ts, "unassigned")
}
export function isMeaningfulExpiry(expires: string) {

View File

@ -1,4 +1,10 @@
import { formatPlanCategory } from "./subscriptionPlans"
import {
APP_TIMEZONE,
formatAppDateTime,
nextAppCalendarDay,
toAppCalendarDate,
} from "./datetime"
import type { Payment } from "../types/payment.types"
export function formatPaymentAmount(payment: Pick<Payment, "amount" | "currency">): string {
@ -9,17 +15,39 @@ export function formatPaymentAmount(payment: Pick<Payment, "amount" | "currency"
return `${formatted} ${payment.currency || "ETB"}`
}
/** @deprecated Prefer APP_TIMEZONE from datetime.ts */
export const PAYMENT_DATE_TIMEZONE = APP_TIMEZONE
export function formatPaymentDate(iso: string | null | undefined): string {
if (!iso) return "unassigned"
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
return d.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(iso, "unassigned")
}
/** YYYY-MM-DD of paid_at (or created_at if unpaid) in EAT. */
export function paymentEventDateEAT(payment: Pick<Payment, "paid_at" | "created_at">): string | null {
const raw = payment.paid_at || payment.created_at
if (!raw) return null
return toAppCalendarDate(raw)
}
/** Inclusive YYYY-MM-DD range against the payment event date in EAT. */
export function paymentMatchesDateRange(
payment: Pick<Payment, "paid_at" | "created_at">,
from?: string,
to?: string,
): boolean {
const fromDay = from?.trim()
const toDay = to?.trim()
if (!fromDay && !toDay) return true
const day = paymentEventDateEAT(payment)
if (!day) return false
if (fromDay && day < fromDay) return false
if (toDay && day > toDay) return false
return true
}
/** Next calendar day as YYYY-MM-DD (for exclusive API upper bounds). */
export function nextCalendarDay(ymd: string): string {
return nextAppCalendarDay(ymd)
}
export function formatPaymentStatus(status: string): string {

View File

@ -2,6 +2,7 @@ import type {
GetPersonasResponse,
PersonaListItem,
} from "../types/persona.types"
import { formatAppDate } from "./datetime"
import amanuelAvatar from "../assets/personas/amanuel.png"
import aseffaAvatar from "../assets/personas/aseffa.png"
import bethelAvatar from "../assets/personas/bethel.png"
@ -91,13 +92,7 @@ export function mapPersonaToCard(persona: PersonaListItem): PersonaCardModel {
export function formatPersonaDate(dateStr: string | null | undefined): string {
if (!dateStr?.trim()) return "unassigned"
const d = new Date(dateStr)
if (Number.isNaN(d.getTime())) return dateStr
return d.toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
})
return formatAppDate(dateStr, dateStr)
}
export function personaStatusLabel(isActive: boolean): string {

View File

@ -1,4 +1,5 @@
import type { RatingTargetType } from "../types/ratings.types"
import { formatAppDate, formatAppDateTime } from "./datetime"
export function formatAverageStars(value: number): string {
if (!Number.isFinite(value) || value <= 0) return "0.0"
@ -6,25 +7,11 @@ export function formatAverageStars(value: number): string {
}
export function formatRatingDate(dateStr: string): string {
const d = new Date(dateStr)
if (Number.isNaN(d.getTime())) return dateStr || "unassigned"
return d.toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
})
return formatAppDate(dateStr, dateStr || "unassigned")
}
export function formatRatingDateTime(dateStr: string): string {
const d = new Date(dateStr)
if (Number.isNaN(d.getTime())) return dateStr || "unassigned"
return d.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
return formatAppDateTime(dateStr, dateStr || "unassigned")
}
export function targetTypeLabel(type: RatingTargetType): string {

View File

@ -4,6 +4,7 @@ import type {
SubscriptionPlanDurationUnit,
UpdateSubscriptionPlanPayload,
} from "../types/subscription.types"
import { formatAppDate } from "./datetime"
export const SUBSCRIPTION_PLAN_CATEGORIES: {
value: SubscriptionPlanCategory
@ -78,13 +79,7 @@ export function formatPlanCategory(category: string): string {
}
export function formatPlanCreatedAt(iso: string): string {
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
return d.toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
})
return formatAppDate(iso, iso)
}
export function planToUpdatePayload(

View File

@ -1,4 +1,5 @@
import type { VerifyInvitationData } from "../types/teamInvitation.types"
import { formatAppDateTime } from "./datetime"
export function formatTeamRoleLabel(role: string | undefined): string {
if (!role) return "unassigned"
@ -9,7 +10,7 @@ export function formatInvitationExpiry(raw: string | undefined): string | null {
if (!raw) return null
const d = new Date(raw)
if (Number.isNaN(d.getTime())) return raw
return d.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })
return formatAppDateTime(raw)
}
/** User-facing title when verify returns valid: false. */

View File

@ -48,6 +48,7 @@ import { useEffect, useState, type ReactNode } from "react"
import { Link } from "react-router-dom"
import { AnalyticsTimeRangeFilter, getDashboardFilterLabel } from "../components/analytics/AnalyticsTimeRangeFilter"
import {
formatAnalyticsSeriesDate,
getPrimaryQuestionTypeSummary,
getSeriesPeriodLabel,
getSubscriptionMetrics,
@ -76,8 +77,7 @@ function DashboardSectionTitle({ children }: { children: ReactNode }) {
}
function formatDate(dateStr: string) {
const d = new Date(dateStr)
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" })
return formatAnalyticsSeriesDate(dateStr)
}
const DEFAULT_FILTERS: DashboardFilters = { mode: "all_time" }
@ -465,7 +465,7 @@ export function DashboardPage() {
<section className="space-y-4">
<DashboardSectionTitle>Revenue &amp; subscriptions</DashboardSectionTitle>
<div className="grid gap-4">
<RevenueTrendCard />
<RevenueTrendCard paymentMethod={filters.payment_method} />
<div className="grid gap-4 lg:grid-cols-2">
<ActivePlansBreakdownCard

View File

@ -68,6 +68,7 @@ import {
formatPercentRate,
buildSubscriptionStatusPie,
aggregateRevenueByMonth,
formatAnalyticsSeriesDate,
formatRevenueAxisTick,
} from "../../lib/analytics"
import type { DashboardData, DashboardFilters, LabelCount } from "../../types/analytics.types"
@ -75,8 +76,7 @@ import type { DashboardData, DashboardFilters, LabelCount } from "../../types/an
const PIE_COLORS = ["#9E2891", "#FFD23F", "#1DE9B6", "#C26FC0", "#6366F1", "#F97316", "#14B8A6", "#EF4444", "#8B5CF6", "#EC4899", "#06B6D4", "#84CC16"]
function formatDate(dateStr: string) {
const d = new Date(dateStr)
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" })
return formatAnalyticsSeriesDate(dateStr)
}
function formatNumber(n: number) {

View File

@ -48,6 +48,7 @@ import {
formatPaymentStatus,
computePaymentAggregateStats,
paymentCustomerName,
paymentMatchesDateRange,
paymentStatusBadgeVariant,
type PaymentAggregateStats,
} from "../../lib/payments"
@ -82,6 +83,8 @@ type PaymentListFilters = {
provider: PaymentProvider | ""
planCategory: PaymentPlanCategory | ""
currency: string
dateFrom: string
dateTo: string
}
function paymentMatchesSearch(payment: Payment, query: string): boolean {
@ -143,6 +146,8 @@ export function PaymentsPage() {
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
const [currencyFilter, setCurrencyFilter] = useState("")
const [dateFrom, setDateFrom] = useState("")
const [dateTo, setDateTo] = useState("")
const [selected, setSelected] = useState<Payment | null>(null)
const listFilters: PaymentListFilters = {
@ -150,10 +155,20 @@ export function PaymentsPage() {
provider: providerFilter,
planCategory: planCategoryFilter,
currency: currencyFilter,
dateFrom,
dateTo,
}
const exportParams = useMemo(
() => paymentListFiltersToExportQuery(listFilters),
() =>
paymentListFiltersToExportQuery({
status: listFilters.status || undefined,
provider: listFilters.provider || undefined,
planCategory: listFilters.planCategory || undefined,
currency: listFilters.currency || undefined,
dateFrom: listFilters.dateFrom || undefined,
dateTo: listFilters.dateTo || undefined,
}),
[listFilters],
)
@ -162,6 +177,8 @@ export function PaymentsPage() {
{ value: providerFilter },
{ value: planCategoryFilter },
{ value: currencyFilter },
{ value: dateFrom },
{ value: dateTo },
])
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim())
@ -188,7 +205,16 @@ export function PaymentsPage() {
useEffect(() => {
setPage(1)
}, [searchQuery, statusFilter, providerFilter, planCategoryFilter, currencyFilter, pageSize])
}, [
searchQuery,
statusFilter,
providerFilter,
planCategoryFilter,
currencyFilter,
dateFrom,
dateTo,
pageSize,
])
const filteredPayments = useMemo(() => {
return payments.filter((payment) => {
@ -206,6 +232,7 @@ export function PaymentsPage() {
) {
return false
}
if (!paymentMatchesDateRange(payment, dateFrom, dateTo)) return false
return paymentMatchesSearch(payment, searchQuery)
})
}, [
@ -214,6 +241,8 @@ export function PaymentsPage() {
providerFilter,
planCategoryFilter,
currencyFilter,
dateFrom,
dateTo,
searchQuery,
])
@ -250,6 +279,8 @@ export function PaymentsPage() {
setProviderFilter("")
setPlanCategoryFilter("")
setCurrencyFilter("")
setDateFrom("")
setDateTo("")
setSearchQuery("")
setPage(1)
}
@ -438,6 +469,45 @@ export function PaymentsPage() {
))}
</Select>
</div>
<div className="flex flex-wrap items-end gap-3">
<div className="space-y-1.5">
<label
htmlFor="payments-date-from"
className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400"
>
From
</label>
<Input
id="payments-date-from"
type="date"
value={dateFrom}
max={dateTo || undefined}
onChange={(e) => setDateFrom(e.target.value)}
disabled={loading}
className="h-9 rounded-[6px] text-sm"
/>
</div>
<div className="space-y-1.5">
<label
htmlFor="payments-date-to"
className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400"
>
To
</label>
<Input
id="payments-date-to"
type="date"
value={dateTo}
min={dateFrom || undefined}
onChange={(e) => setDateTo(e.target.value)}
disabled={loading}
className="h-9 rounded-[6px] text-sm"
/>
</div>
<p className="pb-2 text-[11px] text-grayScale-400">
Dates use EAT (Africa/Addis_Ababa)
</p>
</div>
</AdminFiltersPanel>
{loading ? (

View File

@ -180,6 +180,7 @@ export type DashboardDateFilterMode = "all_time" | "year" | "year_month" | "cust
export interface DashboardDateFilter {
mode: DashboardDateFilterMode
timezone?: string
year?: number
month?: number
from?: string
@ -189,6 +190,7 @@ export interface DashboardDateFilter {
series_start?: string
series_end?: string
ref_date?: string
payment_method?: string
}
export type DashboardFilterMode = DashboardDateFilterMode
@ -199,6 +201,8 @@ export interface DashboardFilters {
month?: number
from?: string
to?: string
/** Optional payment/revenue filter (e.g. CHAPA, ARIFPAY, ADMIN_GRANT). */
payment_method?: string
}
export interface DashboardData {

View File

@ -63,6 +63,14 @@ export interface GetPaymentsParams {
currency?: string
/** Partial match on session_id, nonce, or transaction_id. */
reference?: string
/** Inclusive lower bound on created_at (RFC3339 or YYYY-MM-DD). */
created_from?: string
/** Exclusive upper bound on created_at (RFC3339 or YYYY-MM-DD). */
created_to?: string
/** Inclusive lower bound on paid_at (RFC3339 or YYYY-MM-DD). */
paid_from?: string
/** Exclusive upper bound on paid_at (RFC3339 or YYYY-MM-DD). */
paid_to?: string
limit?: number
offset?: number
}