Files
tbbank-frontend/src/pages/dashboard/index.tsx
T
2026-10-23 23:21:33 +05:00

232 lines
9.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useMemo, useState, type ElementType } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { AlertCircle, ArrowDownRight, ArrowUpRight, CreditCard, DollarSign, FileText, RefreshCw, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { StatItem } from "@/features/dashboard/api/dashboardApi";
import { DASHBOARD_OVERVIEW_KEY, useDashboardOverview } from "@/features/dashboard/hooks/useDashboard";
import { ANALYTICS_KEY, useAnalyticsCustomers, useAnalyticsProducts } from "@/features/dashboard/hooks/useAnalytics";
import { CustomersSection } from "@/features/dashboard/components/productsCustomersSection";
import { formatNumber } from "@/features/dashboard/components/analyticsFormat";
/**
* KPI register cell dividers: a 2×2 grid on small screens, one row of four on lg.
* Each cell owns its own rules, so the panel never needs a negative-margin trick.
*/
const KPI_CELL_BORDERS = [
"border-b border-r border-border lg:border-b-0",
"border-b border-border lg:border-b-0 lg:border-r",
"border-r border-border",
"",
];
// ─── Stat cell ────────────────────────────────────────────────────────────────
interface StatCellProps {
title: string;
stat?: StatItem;
icon: ElementType;
footnote: string;
comparedTo: string;
className?: string;
}
function StatCell({ title, stat, icon: Icon, footnote, comparedTo, className }: StatCellProps) {
const change = stat?.changePercent;
const hasChange = change !== null && change !== undefined;
const positive = (change ?? 0) >= 0;
return (
<div className={cn("px-5 py-5 lg:px-7 lg:py-6", className)}>
<div className="flex items-start justify-between gap-3">
<p className="text-[13px] font-medium text-muted-foreground">{title}</p>
<Icon className="size-[18px] shrink-0 text-muted-foreground/60" aria-hidden="true" />
</div>
<p className="mt-3.5 text-[34px] font-semibold leading-none tracking-tight tabular-nums">{formatNumber(stat?.count ?? 0)}</p>
{hasChange ? (
<p
className={cn(
"mt-3 flex flex-wrap items-center gap-x-1 text-[12.5px] font-medium",
positive ? "text-positive" : "text-destructive",
)}
>
{positive ? (
<ArrowUpRight className="size-3 shrink-0" aria-hidden="true" />
) : (
<ArrowDownRight className="size-3 shrink-0" aria-hidden="true" />
)}
<span className="tabular-nums">{formatNumber(Math.abs(change), 1)}%</span>
<span className="font-normal text-muted-foreground">{comparedTo}</span>
</p>
) : (
<p className="mt-3 flex items-center gap-2 text-[12.5px] text-muted-foreground">
<span className="inline-block size-2 shrink-0 rounded-full bg-muted-foreground/40" aria-hidden="true" />
{footnote}
</p>
)}
</div>
);
}
function StatCellSkeleton({ className }: { className?: string }) {
return (
<div className={cn("px-5 py-5 lg:px-7 lg:py-6", className)}>
<div className="flex items-start justify-between gap-3">
<Skeleton className="h-3.5 w-24" />
<Skeleton className="size-[18px] rounded-sm" />
</div>
<Skeleton className="mt-3.5 h-7 w-24" />
<Skeleton className="mt-2.5 h-3 w-32" />
</div>
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function DashboardPage({ isLoading: propLoading = false }: { isLoading?: boolean }) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const currentYear = new Date().getFullYear();
const [selectedYear, setSelectedYear] = useState<number>(currentYear);
const analyticsParams = useMemo(() => ({ from: `${selectedYear}-01-01`, to: `${selectedYear}-12-31` }), [selectedYear]);
const overview = useDashboardOverview({ year: selectedYear });
const customers = useAnalyticsCustomers(analyticsParams);
const products = useAnalyticsProducts(analyticsParams);
const isFetching = overview.isFetching || customers.isFetching || products.isFetching;
const showStatSkeleton = propLoading || overview.isLoading;
const handleRefresh = () => {
void queryClient.invalidateQueries({ queryKey: [DASHBOARD_OVERVIEW_KEY] });
void queryClient.invalidateQueries({ queryKey: [ANALYTICS_KEY] });
};
const yearOptions = [currentYear - 2, currentYear - 1, currentYear];
const comparedTo = t("dashboard.comparedToLastMonth", "geçen aýa garanyňda");
const stats = overview.data?.stats;
const statCards: Omit<StatCellProps, "comparedTo" | "className">[] = [
{
title: t("dashboard.loanOrders", "Karz sargytlary"),
stat: stats?.loanOrders,
icon: FileText,
footnote: t("dashboard.totalLoanOrders", "Jemi karz sargytlar"),
},
{
title: t("dashboard.activeCards", "Işjeň kartlar"),
stat: stats?.activeCards,
icon: CreditCard,
footnote: t("dashboard.totalActiveCards", "Işjeň kartlaryň sany"),
},
{
title: t("dashboard.activeClients", "Işjeň müşderiler"),
stat: stats?.activeCustomers,
icon: Users,
footnote: t("dashboard.totalActiveCustomers", "Hasaba alnan müşderiler"),
},
{
title: t("dashboard.onlinePayments", "Onlaýn tölegler"),
stat: stats?.onlinePayments,
icon: DollarSign,
footnote: t("dashboard.totalOnlinePayments", "Amala aşyrylan tölegler"),
},
];
return (
<div className="w-full space-y-3.5">
{/* Header */}
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-end">
<div>
<h1 className="text-[28px] font-semibold tracking-tight">{t("dashboard.title", "Baş sahypa")}</h1>
<p className="mt-2 text-[13.5px] text-muted-foreground">{t("dashboard.overviewSubtitle", "Ähli amallaryň gysgaça görünüşi")}</p>
</div>
<div className="flex items-center self-start rounded-md border border-border bg-card p-0.5 sm:self-auto">
<Select value={String(selectedYear)} onValueChange={(val) => setSelectedYear(Number(val))}>
<SelectTrigger
aria-label={t("common.year", "ýyl")}
className="h-9 w-[110px] cursor-pointer rounded-[5px] border-0 bg-transparent px-2.5 text-[13.5px] shadow-none focus-visible:border-transparent focus-visible:ring-0"
>
<SelectValue />
<span className="text-[11.5px] text-muted-foreground" aria-hidden="true">
{t("common.year", "ýyl")}
</span>
</SelectTrigger>
<SelectContent align="end">
{yearOptions.map((y) => (
<SelectItem key={y} value={String(y)} className="cursor-pointer tabular-nums">
{y}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="h-4 w-px bg-border" aria-hidden="true" />
<Button
variant="ghost"
size="icon-sm"
onClick={handleRefresh}
disabled={isFetching}
aria-label={t("common.refresh", "Täzele")}
title={t("common.refresh", "Täzele")}
className="rounded-[5px]"
>
<RefreshCw className={cn("size-4", isFetching && "animate-spin")} />
</Button>
</div>
</div>
{/* KPI register */}
{overview.isError && !showStatSkeleton ? (
<div className="flex w-full flex-col items-center justify-center space-y-4 rounded-panel border border-border bg-card p-12 text-center">
<div className="flex size-12 items-center justify-center rounded-full bg-destructive/10 text-destructive">
<AlertCircle className="size-6" aria-hidden="true" />
</div>
<div>
<h3 className="text-lg font-semibold">{t("dashboard.errorTitle", "Maglumatlary ýükläp bolmady")}</h3>
<p className="mt-1 max-w-md text-sm text-muted-foreground">
{overview.error instanceof Error && overview.error.message
? overview.error.message
: t("dashboard.errorMessage", "Serwer bilen baglanyşykda säwlik ýüze çykdy.")}
</p>
</div>
<Button onClick={() => overview.refetch()} variant="outline" className="gap-2">
<RefreshCw className="size-4" aria-hidden="true" />
{t("common.retry", "Täzeden synanyş")}
</Button>
</div>
) : (
<div className="grid grid-cols-2 overflow-hidden rounded-panel border border-border bg-card lg:grid-cols-4">
{showStatSkeleton
? Array.from({ length: 4 }, (_, i) => <StatCellSkeleton key={i} className={KPI_CELL_BORDERS[i]} />)
: statCards.map((card, i) => <StatCell key={card.title} {...card} comparedTo={comparedTo} className={KPI_CELL_BORDERS[i]} />)}
</div>
)}
{/* Customers analytics */}
<CustomersSection
data={customers.data}
isLoading={customers.isLoading}
isError={customers.isError}
onRetry={() => customers.refetch()}
products={{
data: products.data,
isLoading: products.isLoading,
isError: products.isError,
onRetry: () => products.refetch(),
}}
/>
</div>
);
}