changed dashboard
This commit is contained in:
213
src/features/dashboard/api/analyticsApi.ts
Normal file
213
src/features/dashboard/api/analyticsApi.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Shared ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AnalyticsParams {
|
||||
/** YYYY-MM-DD, inclusive */
|
||||
from: string;
|
||||
/** YYYY-MM-DD, inclusive */
|
||||
to: string;
|
||||
}
|
||||
|
||||
export interface CountItem {
|
||||
key: string;
|
||||
count: number;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
/** Localized name stored as JSON on the backend, e.g. { tm, ru, en }. */
|
||||
export type LocalizedName = Partial<Record<"tm" | "ru" | "en", string>>;
|
||||
|
||||
export type OrderType = "loan" | "loan_paid_off_letter" | "card" | "card_pin" | "card_rekwizit" | "visa_master";
|
||||
|
||||
// ─── /finance ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PaymentTotals {
|
||||
count: number;
|
||||
amountTmt: number;
|
||||
bankFeeTmt: number;
|
||||
gbusFeeTmt: number;
|
||||
tvebFeeTmt: number;
|
||||
totalTmt: number;
|
||||
avgTotalTmt: number;
|
||||
}
|
||||
|
||||
export interface FinanceMonth {
|
||||
month: string; // YYYY-MM
|
||||
count: number;
|
||||
totalTmt: number;
|
||||
bankFeeTmt: number;
|
||||
}
|
||||
|
||||
export interface LoanRequested {
|
||||
count: number;
|
||||
totalTmt: number;
|
||||
avgTmt: number;
|
||||
unparsed: number;
|
||||
}
|
||||
|
||||
export interface FinanceData {
|
||||
payments: PaymentTotals;
|
||||
gateway: CountItem[];
|
||||
gatewaySuccessRate: number | null;
|
||||
monthly: FinanceMonth[];
|
||||
loanRequested: LoanRequested;
|
||||
}
|
||||
|
||||
// ─── /backlog ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface BacklogItem {
|
||||
type: OrderType;
|
||||
open: number;
|
||||
under1Day: number;
|
||||
from1To3Days: number;
|
||||
over3Days: number;
|
||||
oldestOpenAt: string | null;
|
||||
oldestOpenDays: number | null;
|
||||
finished: number;
|
||||
avgProcessHours: number | null;
|
||||
}
|
||||
|
||||
export interface VisaMasterTiming {
|
||||
orders: number;
|
||||
avgMinutes: number | null;
|
||||
p90Minutes: number | null;
|
||||
maxMinutes: number | null;
|
||||
}
|
||||
|
||||
export interface BacklogData {
|
||||
items: BacklogItem[];
|
||||
visaMasterTiming: VisaMasterTiming;
|
||||
}
|
||||
|
||||
// ─── /branches ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface BranchStat {
|
||||
branchId: number;
|
||||
name: LocalizedName;
|
||||
region: string;
|
||||
orders: Partial<Record<OrderType, number>>;
|
||||
total: number;
|
||||
open: number;
|
||||
approved: number;
|
||||
rejected: number;
|
||||
approvalRate: number | null;
|
||||
avgProcessHours: number | null;
|
||||
}
|
||||
|
||||
export interface BranchesData {
|
||||
branches: BranchStat[];
|
||||
regions: CountItem[];
|
||||
}
|
||||
|
||||
// ─── /products ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface NamedCount {
|
||||
id: number;
|
||||
name: LocalizedName;
|
||||
count: number;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export interface ProductsData {
|
||||
loanSources: CountItem[];
|
||||
loanTypes: NamedCount[];
|
||||
cardTypes: NamedCount[];
|
||||
cardOrderPay: CountItem[];
|
||||
}
|
||||
|
||||
// ─── /customers ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ApprovalCount {
|
||||
key: string;
|
||||
count: number;
|
||||
percent: number;
|
||||
approved: number;
|
||||
rejected: number;
|
||||
/** Not decided yet (new / in review). */
|
||||
open: number;
|
||||
approvalRate: number | null;
|
||||
}
|
||||
|
||||
export interface CustomersData {
|
||||
total: number;
|
||||
approved: number;
|
||||
rejected: number;
|
||||
open: number;
|
||||
approvalRate: number | null;
|
||||
ageGroups: ApprovalCount[];
|
||||
education: ApprovalCount[];
|
||||
marriageStatus: ApprovalCount[];
|
||||
guarantors: ApprovalCount[];
|
||||
}
|
||||
|
||||
// ─── /system ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface RegistrationFunnel {
|
||||
started: number;
|
||||
completed: number;
|
||||
abandoned: number;
|
||||
waitingCode: number;
|
||||
wrongCodeTries: number;
|
||||
conversionPct: number | null;
|
||||
}
|
||||
|
||||
export interface OperatorActivity {
|
||||
userId: number;
|
||||
name: string;
|
||||
actions: number;
|
||||
errors: number;
|
||||
lastSeen: string | null;
|
||||
}
|
||||
|
||||
export interface ModuleError {
|
||||
module: string;
|
||||
requests: number;
|
||||
errors: number;
|
||||
errorRate: number;
|
||||
}
|
||||
|
||||
/** weekday: Monday=1 .. Sunday=7; hour 0..23 (Asia/Ashgabat). */
|
||||
export interface HeatmapCell {
|
||||
weekday: number;
|
||||
hour: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface CardBalanceStats {
|
||||
statuses: CountItem[];
|
||||
failureRate: number | null;
|
||||
expiringIn30d: number;
|
||||
}
|
||||
|
||||
export interface SystemData {
|
||||
registration: RegistrationFunnel | null;
|
||||
operators: OperatorActivity[];
|
||||
moduleErrors: ModuleError[];
|
||||
peakHours: HeatmapCell[];
|
||||
cardBalances: CardBalanceStats | null;
|
||||
}
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const BASE = "/dashboard/analytics";
|
||||
|
||||
async function getAnalytics<T>(path: string, params: AnalyticsParams, signal?: AbortSignal): Promise<T> {
|
||||
const { data } = await apiClient.get<T>(`${BASE}/${path}`, { params, signal });
|
||||
return data;
|
||||
}
|
||||
|
||||
export const getAnalyticsFinance = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<FinanceData>("finance", params, signal);
|
||||
|
||||
export const getAnalyticsBacklog = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<BacklogData>("backlog", params, signal);
|
||||
|
||||
export const getAnalyticsBranches = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||
getAnalytics<BranchesData>("branches", params, signal);
|
||||
|
||||
export const getAnalyticsProducts = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||
getAnalytics<ProductsData>("products", params, signal);
|
||||
|
||||
export const getAnalyticsCustomers = (params: AnalyticsParams, signal?: AbortSignal) =>
|
||||
getAnalytics<CustomersData>("customers", params, signal);
|
||||
|
||||
export const getAnalyticsSystem = (params: AnalyticsParams, signal?: AbortSignal) => getAnalytics<SystemData>("system", params, signal);
|
||||
56
src/features/dashboard/components/analyticsFormat.ts
Normal file
56
src/features/dashboard/components/analyticsFormat.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { REGION_LABELS } from "@/constants/regionCodes";
|
||||
import type { LocalizedName, OrderType } from "@/features/dashboard/api/analyticsApi";
|
||||
|
||||
// ─── Formatting ───────────────────────────────────────────────────────────────
|
||||
|
||||
export function formatNumber(value: number | null | undefined, digits = 0): string {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return "—";
|
||||
return value.toLocaleString(undefined, { maximumFractionDigits: digits, minimumFractionDigits: 0 });
|
||||
}
|
||||
|
||||
export function formatTmt(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined) return "—";
|
||||
return `${formatNumber(value, 2)} TMT`;
|
||||
}
|
||||
|
||||
export function formatPercent(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined) return "—";
|
||||
return `${formatNumber(value, 1)}%`;
|
||||
}
|
||||
|
||||
/** Hours → "45 min", "5.5 sag", "2.1 gün" style. */
|
||||
export function formatDuration(hours: number | null | undefined, t: TFunction): string {
|
||||
if (hours === null || hours === undefined || !Number.isFinite(hours)) return "—";
|
||||
const minutes = Math.round(hours * 60);
|
||||
if (minutes < 60) return `${minutes} ${t("analytics.unit.min", "min")}`;
|
||||
if (hours < 48) return `${formatNumber(hours, 1)} ${t("analytics.unit.hours", "sag")}`;
|
||||
return `${formatNumber(hours / 24, 1)} ${t("analytics.unit.days", "gün")}`;
|
||||
}
|
||||
|
||||
/** Picks the current UI language from a backend { tm, ru, en } name. */
|
||||
export function useLocalizedName() {
|
||||
const { i18n } = useTranslation();
|
||||
const short = i18n.language?.slice(0, 2);
|
||||
const lang = (short === "tk" ? "tm" : short) as keyof LocalizedName;
|
||||
return useCallback((name: LocalizedName | null | undefined): string => name?.[lang] || name?.tm || name?.ru || name?.en || "—", [lang]);
|
||||
}
|
||||
|
||||
export function orderTypeLabel(type: OrderType | string, t: TFunction): string {
|
||||
const fallback: Record<string, string> = {
|
||||
loan: "Karz sargytlary",
|
||||
loan_paid_off_letter: "Karzyň ýapylandygy",
|
||||
card: "Täze kart",
|
||||
card_pin: "Kart pin",
|
||||
card_rekwizit: "Kart rekwizit",
|
||||
visa_master: "Visa/Master",
|
||||
};
|
||||
return t(`analytics.orderType.${type}`, fallback[type] ?? type);
|
||||
}
|
||||
|
||||
export function regionLabel(code: string, t: TFunction): string {
|
||||
if (code === "unknown") return t("analytics.unknown", "Näbelli");
|
||||
return t(`loanOrders.regions.${code}`, REGION_LABELS[code] ?? code);
|
||||
}
|
||||
191
src/features/dashboard/components/analyticsShared.tsx
Normal file
191
src/features/dashboard/components/analyticsShared.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, RefreshCw } from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ElementType, ReactNode } from "react";
|
||||
import { formatNumber } from "./analyticsFormat";
|
||||
|
||||
// ─── Section card with its own loading / error state ─────────────────────────
|
||||
|
||||
interface SectionCardProps {
|
||||
title: string;
|
||||
description?: string;
|
||||
isLoading?: boolean;
|
||||
isError?: boolean;
|
||||
onRetry?: () => void;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
action?: ReactNode;
|
||||
skeletonHeight?: number;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export function SectionCard({
|
||||
title,
|
||||
description,
|
||||
isLoading,
|
||||
isError,
|
||||
onRetry,
|
||||
className,
|
||||
contentClassName,
|
||||
action,
|
||||
skeletonHeight = 200,
|
||||
children,
|
||||
}: SectionCardProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card className={className}>
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
|
||||
<div className="space-y-1">
|
||||
<CardTitle>{title}</CardTitle>
|
||||
{description && <CardDescription>{description}</CardDescription>}
|
||||
</div>
|
||||
{action}
|
||||
</CardHeader>
|
||||
<CardContent className={contentClassName}>
|
||||
{isLoading ? (
|
||||
<Skeleton className="w-full rounded-lg" style={{ height: skeletonHeight }} />
|
||||
) : isError ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-8 text-center" style={{ minHeight: skeletonHeight }}>
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
|
||||
<AlertCircle className="h-5 w-5" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t("dashboard.errorTitle", "Maglumatlary ýükläp bolmady")}</p>
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="sm" className="gap-2" onClick={onRetry}>
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
{t("common.retry", "Täzeden synanyş")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ height = 160 }: { height?: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center justify-center text-xs text-muted-foreground" style={{ height }}>
|
||||
{t("dashboard.noData", "Maglumat ýok")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── KPI tile ─────────────────────────────────────────────────────────────────
|
||||
|
||||
interface KpiTileProps {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: string;
|
||||
icon: ElementType;
|
||||
accent: string;
|
||||
tone?: "default" | "good" | "warn" | "bad";
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export function KpiTile({ label, value, hint, icon: Icon, accent, tone = "default", isLoading }: KpiTileProps) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0 pb-2">
|
||||
<CardTitle className="min-w-0 text-sm font-medium text-muted-foreground">{label}</CardTitle>
|
||||
<div className={cn("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg", accent)}>
|
||||
<Icon size={16} />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="@container/kpi">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Skeleton className="h-8 w-28" />
|
||||
<Skeleton className="mt-2 h-3 w-36" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xl font-semibold tracking-tight tabular-nums @[14rem]/kpi:text-2xl @[18rem]/kpi:text-3xl",
|
||||
tone === "good" && "text-emerald-600 dark:text-emerald-400",
|
||||
tone === "warn" && "text-amber-600 dark:text-amber-400",
|
||||
tone === "bad" && "text-destructive",
|
||||
)}
|
||||
>
|
||||
{value}
|
||||
</p>
|
||||
{hint && (
|
||||
<p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="inline-block h-1.5 w-1.5 rounded-full bg-muted-foreground/40" />
|
||||
{hint}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Horizontal bar list (label · bar · value) ───────────────────────────────
|
||||
|
||||
export interface BarListRow {
|
||||
key: string;
|
||||
label: string;
|
||||
value: number;
|
||||
/** Text on the right; defaults to the formatted value. */
|
||||
valueText?: ReactNode;
|
||||
/** Secondary text under the label, e.g. approval rate. */
|
||||
sub?: ReactNode;
|
||||
/** Bar width as a share of the whole (0–100). Without it, bars are scaled to the largest row. */
|
||||
share?: number;
|
||||
}
|
||||
|
||||
interface BarListProps {
|
||||
rows: BarListRow[];
|
||||
color?: string;
|
||||
/** Collapse rows with value 0 into one muted line instead of listing them. */
|
||||
hideEmpty?: boolean;
|
||||
}
|
||||
|
||||
export function BarList({ rows, color = "var(--chart-1)", hideEmpty }: BarListProps) {
|
||||
const { t } = useTranslation();
|
||||
const visible = hideEmpty ? rows.filter((r) => r.value > 0) : rows;
|
||||
const hidden = rows.length - visible.length;
|
||||
const max = Math.max(1, ...rows.map((r) => r.value));
|
||||
if (visible.length === 0) return <EmptyState height={120} />;
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{visible.map((row) => (
|
||||
<div key={row.key} className="space-y-1">
|
||||
<div className="flex items-baseline justify-between gap-3 text-sm">
|
||||
<span className="min-w-0 truncate text-foreground" title={row.label}>
|
||||
{row.label}
|
||||
</span>
|
||||
<span className="shrink-0 tabular-nums">{row.valueText ?? formatNumber(row.value)}</span>
|
||||
</div>
|
||||
<div className="h-2 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full transition-[width] duration-500"
|
||||
style={{ width: `${row.share ?? (row.value / max) * 100}%`, background: color }}
|
||||
/>
|
||||
</div>
|
||||
{row.sub && <div className="text-xs text-muted-foreground">{row.sub}</div>}
|
||||
</div>
|
||||
))}
|
||||
{hidden > 0 && (
|
||||
<p
|
||||
className="border-t pt-2 text-xs text-muted-foreground"
|
||||
title={rows
|
||||
.filter((r) => r.value === 0)
|
||||
.map((r) => r.label)
|
||||
.join(", ")}
|
||||
>
|
||||
{t("analytics.emptyRows", "+{{count}} görnüşde sargyt ýok", { count: hidden })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
338
src/features/dashboard/components/productsCustomersSection.tsx
Normal file
338
src/features/dashboard/components/productsCustomersSection.tsx
Normal file
@@ -0,0 +1,338 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Info } from "lucide-react";
|
||||
import { Cell, Pie, PieChart } from "recharts";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type { ApprovalCount, CountItem, CustomersData, ProductsData } from "../api/analyticsApi";
|
||||
import { BarList, EmptyState, SectionCard, type BarListRow } from "./analyticsShared";
|
||||
import { formatNumber, formatPercent, useLocalizedName } from "./analyticsFormat";
|
||||
|
||||
interface QueryProps<T> {
|
||||
data?: T;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
onRetry: () => void;
|
||||
}
|
||||
|
||||
// One meaning per color across the dashboard: blue = loans, green = cards / good, amber = waiting, red = rejected.
|
||||
const LOAN_COLOR = "var(--chart-1)";
|
||||
const CARD_COLOR = "var(--chart-2)";
|
||||
const GOOD_COLOR = "var(--chart-2)";
|
||||
const WAIT_COLOR = "var(--chart-4)";
|
||||
const BAD_COLOR = "var(--chart-5)";
|
||||
|
||||
/** Below this many decided orders an approval rate is shown but flagged as unreliable. */
|
||||
const MIN_DECIDED = 5;
|
||||
|
||||
/** "3 sargyt · 60%" — count first, share muted. */
|
||||
function CountShare({ count, percent }: { count: number; percent: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<span className="font-semibold">
|
||||
{formatNumber(count)} {t("analytics.kpi.orders", "sargyt")}
|
||||
</span>
|
||||
<span className="text-muted-foreground"> · {formatNumber(percent, 1)}%</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoHint({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="inline-flex cursor-help text-muted-foreground hover:text-foreground">
|
||||
<Info className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs leading-relaxed">{children}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Donut with the total in the middle ──────────────────────────────────────
|
||||
|
||||
interface DonutRow {
|
||||
key: string;
|
||||
label: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
function TotalDonut({ items, rows: rowDefs }: { items: CountItem[]; rows: DonutRow[] }) {
|
||||
const { t } = useTranslation();
|
||||
const byKey = new Map(items.map((it) => [it.key, it]));
|
||||
// Fixed row order and colors, so "unpaid" is always amber and never swaps with "paid".
|
||||
const known = new Set(rowDefs.map((r) => r.key));
|
||||
const extra = items.filter((it) => !known.has(it.key)).map((it) => ({ key: it.key, label: it.key, color: "var(--muted-foreground)" }));
|
||||
const rows = [...rowDefs, ...extra].map((r) => ({
|
||||
...r,
|
||||
count: byKey.get(r.key)?.count ?? 0,
|
||||
percent: byKey.get(r.key)?.percent ?? 0,
|
||||
}));
|
||||
const total = rows.reduce((s, r) => s + r.count, 0);
|
||||
if (total === 0) return <EmptyState height={140} />;
|
||||
const config = Object.fromEntries(rows.map((r) => [r.label, { label: r.label, color: r.color }]));
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="relative h-[132px] w-[132px] shrink-0">
|
||||
<ChartContainer config={config} className="h-full w-full">
|
||||
<PieChart>
|
||||
<Pie data={rows} dataKey="count" nameKey="label" innerRadius={44} outerRadius={64} strokeWidth={2} stroke="var(--card)">
|
||||
{rows.map((r) => (
|
||||
<Cell key={r.key} fill={r.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<ChartTooltip content={<ChartTooltipContent nameKey="label" hideLabel />} />
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
|
||||
<span className="text-2xl font-semibold tabular-nums leading-none">{formatNumber(total)}</span>
|
||||
<span className="mt-1 text-[11px] text-muted-foreground">{t("analytics.kpi.orders", "sargyt")}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-3">
|
||||
{rows.map((r) => (
|
||||
<div key={r.key} className="space-y-0.5">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: r.color }} />
|
||||
<span className="truncate">{r.label}</span>
|
||||
</div>
|
||||
<div className="pl-[18px] text-sm tabular-nums">
|
||||
<CountShare count={r.count} percent={r.percent} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Products ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function ProductsSection({ data, isLoading, isError, onRetry }: QueryProps<ProductsData>) {
|
||||
const { t } = useTranslation();
|
||||
const localized = useLocalizedName();
|
||||
const common = { isLoading, isError, onRetry, skeletonHeight: 150 };
|
||||
|
||||
const toRows = (items: ProductsData["loanTypes"]): BarListRow[] =>
|
||||
items.map((it) => ({
|
||||
key: String(it.id),
|
||||
label: localized(it.name),
|
||||
value: it.count,
|
||||
share: it.percent,
|
||||
valueText: <CountShare count={it.count} percent={it.percent} />,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<SectionCard
|
||||
title={t("analytics.products.sources", "Karz: Web we mobil")}
|
||||
description={t("analytics.products.sourcesDesc", "Karz sargytlary nireden iberildi")}
|
||||
{...common}
|
||||
>
|
||||
<TotalDonut
|
||||
items={data?.loanSources ?? []}
|
||||
rows={[
|
||||
{ key: "mobile", label: t("analytics.source.mobile", "Mobil"), color: LOAN_COLOR },
|
||||
{ key: "web", label: t("analytics.source.web", "Web"), color: "var(--chart-3)" },
|
||||
]}
|
||||
/>
|
||||
</SectionCard>
|
||||
<SectionCard
|
||||
title={t("analytics.products.cardPaid", "Kart sargytlary: töleg")}
|
||||
description={t("analytics.products.cardPaidDesc", "Kart sargytlarynyň näçesi tölendi")}
|
||||
{...common}
|
||||
>
|
||||
<TotalDonut
|
||||
items={data?.cardOrderPay ?? []}
|
||||
rows={[
|
||||
{ key: "paid", label: t("analytics.paid", "Tölenen"), color: GOOD_COLOR },
|
||||
{ key: "unpaid", label: t("analytics.unpaid", "Tölenmedik"), color: WAIT_COLOR },
|
||||
]}
|
||||
/>
|
||||
</SectionCard>
|
||||
<SectionCard
|
||||
title={t("analytics.products.loanTypes", "Karz görnüşleri")}
|
||||
description={t("analytics.products.loanTypesDesc", "Her görnüşiň ähli karz sargytlaryndaky paýy")}
|
||||
{...common}
|
||||
>
|
||||
<BarList rows={toRows(data?.loanTypes ?? [])} color={LOAN_COLOR} hideEmpty />
|
||||
</SectionCard>
|
||||
<SectionCard
|
||||
title={t("analytics.products.cardTypes", "Kart görnüşleri")}
|
||||
description={t("analytics.products.cardTypesDesc", "Her görnüşiň ähli kart sargytlaryndaky paýy")}
|
||||
{...common}
|
||||
>
|
||||
<BarList rows={toRows(data?.cardTypes ?? [])} color={CARD_COLOR} hideEmpty />
|
||||
</SectionCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Customers ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Approved / rejected / waiting counts as colored dots, then the approval rate. */
|
||||
function Outcome({ item, t }: { item: ApprovalCount; t: TFunction }) {
|
||||
const decided = item.approved + item.rejected;
|
||||
const parts = [
|
||||
{ n: item.approved, color: GOOD_COLOR, label: t("analytics.outcome.approved", "tassyklandy") },
|
||||
{ n: item.rejected, color: BAD_COLOR, label: t("analytics.outcome.rejected", "ret edildi") },
|
||||
{ n: item.open, color: WAIT_COLOR, label: t("analytics.outcome.open", "garaşýar") },
|
||||
].filter((p) => p.n > 0);
|
||||
|
||||
const fewData = decided > 0 && decided < MIN_DECIDED;
|
||||
|
||||
// Two fixed columns: counts on the left, approval rate pinned right — so every row lines up the same way.
|
||||
return (
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3">
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-0.5">
|
||||
{parts.map((p) => (
|
||||
<span key={p.label} className="inline-flex items-center gap-1 whitespace-nowrap">
|
||||
<span className="h-1.5 w-1.5 rounded-full" style={{ background: p.color }} />
|
||||
{formatNumber(p.n)} {p.label}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
{decided === 0 ? (
|
||||
<span className="whitespace-nowrap">{t("analytics.outcome.noDecision", "Karar entek ýok")}</span>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex cursor-help items-baseline gap-1 whitespace-nowrap tabular-nums">
|
||||
<span
|
||||
className={
|
||||
fewData
|
||||
? "font-medium text-muted-foreground underline decoration-dotted underline-offset-2"
|
||||
: "font-semibold text-foreground"
|
||||
}
|
||||
>
|
||||
{formatPercent(item.approvalRate)}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{formatNumber(item.approved)}/{formatNumber(decided)}
|
||||
</span>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs leading-relaxed">
|
||||
{fewData
|
||||
? t("analytics.outcome.fewDataHint", "Az maglumat: diňe {{count}} karar bar, göterim takyk däl", { count: decided })
|
||||
: t("analytics.outcome.rateHint", "Tassyklama derejesi: tassyklanan / karar berlen")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function approvalRows(items: ApprovalCount[], labelFor: (key: string) => string, t: TFunction): BarListRow[] {
|
||||
return items.map((it) => ({
|
||||
key: it.key,
|
||||
label: labelFor(it.key),
|
||||
value: it.count,
|
||||
share: it.percent,
|
||||
valueText: <CountShare count={it.count} percent={it.percent} />,
|
||||
sub: <Outcome item={it} t={t} />,
|
||||
}));
|
||||
}
|
||||
|
||||
function SummaryStat({ label, value, color, hint }: { label: string; value: string; color?: string; hint?: ReactNode }) {
|
||||
return (
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{color && <span className="h-2 w-2 shrink-0 rounded-full" style={{ background: color }} />}
|
||||
<span className="truncate">{label}</span>
|
||||
{hint && <InfoHint>{hint}</InfoHint>}
|
||||
</p>
|
||||
<p className="text-2xl font-semibold tabular-nums tracking-tight">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomersSummary({ data, isLoading }: { data?: CustomersData; isLoading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const rateHint = t(
|
||||
"analytics.customers.approvalHint",
|
||||
"Tassyklama derejesi = tassyklanan ÷ (tassyklanan + ret edilen). Garaşýan sargytlar hasaba alynmaýar.",
|
||||
);
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3 lg:grid-cols-5">
|
||||
{isLoading ? (
|
||||
Array.from({ length: 5 }, (_, i) => <Skeleton key={i} className="h-12 w-full" />)
|
||||
) : (
|
||||
<>
|
||||
<SummaryStat label={t("analytics.customers.totalOrders", "Jemi karz sargytlary")} value={formatNumber(data?.total)} />
|
||||
<SummaryStat
|
||||
label={t("analytics.outcome.approvedTitle", "Tassyklandy")}
|
||||
value={formatNumber(data?.approved)}
|
||||
color={GOOD_COLOR}
|
||||
/>
|
||||
<SummaryStat
|
||||
label={t("analytics.outcome.rejectedTitle", "Ret edildi")}
|
||||
value={formatNumber(data?.rejected)}
|
||||
color={BAD_COLOR}
|
||||
/>
|
||||
<SummaryStat label={t("analytics.outcome.openTitle", "Garaşýar")} value={formatNumber(data?.open)} color={WAIT_COLOR} />
|
||||
<SummaryStat
|
||||
label={t("analytics.customers.approvalRate", "Tassyklama derejesi")}
|
||||
value={formatPercent(data?.approvalRate)}
|
||||
hint={rateHint}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function CustomersSection({ data, isLoading, isError, onRetry }: QueryProps<CustomersData>) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// One error card instead of four identical ones.
|
||||
if (isError) {
|
||||
return <SectionCard title={t("analytics.customers.title", "Müşderiler")} isError onRetry={onRetry} skeletonHeight={160} />;
|
||||
}
|
||||
|
||||
const unknown = t("analytics.unknown", "Näbelli");
|
||||
const humanize = (k: string) => k.charAt(0).toUpperCase() + k.slice(1).toLowerCase().replace(/_/g, " ");
|
||||
const ageLabel = (k: string) =>
|
||||
k === "under25" ? t("analytics.age.under25", "25 ýaşdan kiçi") : k === "unknown" ? unknown : `${k} ${t("analytics.age.years", "ýaş")}`;
|
||||
const educationLabel = (k: string) => (k === "unknown" ? unknown : t(`options.education.${k}`, humanize(k)));
|
||||
const marriageLabel = (k: string) => (k === "unknown" ? unknown : t(`options.marriage.${k}`, humanize(k)));
|
||||
const guarantorLabel = (k: string) =>
|
||||
({
|
||||
none: t("analytics.guarantors.none", "Zamunsyz"),
|
||||
one: t("analytics.guarantors.one", "1 zamun"),
|
||||
two: t("analytics.guarantors.two", "2 zamun"),
|
||||
})[k] ?? k;
|
||||
|
||||
const cards: { title: string; items?: ApprovalCount[]; label: (k: string) => string }[] = [
|
||||
{ title: t("analytics.customers.age", "Ýaş toparlary"), items: data?.ageGroups, label: ageLabel },
|
||||
{ title: t("analytics.customers.education", "Bilimi"), items: data?.education, label: educationLabel },
|
||||
{ title: t("analytics.customers.marriage", "Maşgala ýagdaýy"), items: data?.marriageStatus, label: marriageLabel },
|
||||
{ title: t("analytics.customers.guarantors", "Zamunlar"), items: data?.guarantors, label: guarantorLabel },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("analytics.customers.desc", "Saýlanan döwürde karz sargydyny berenleriň profili")}
|
||||
</p>
|
||||
<CustomersSummary data={data} isLoading={isLoading} />
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 2xl:grid-cols-4">
|
||||
{cards.map((c) => (
|
||||
<SectionCard key={c.title} title={c.title} isLoading={isLoading} skeletonHeight={180}>
|
||||
<BarList rows={approvalRows(c.items ?? [], c.label, t)} color={LOAN_COLOR} />
|
||||
</SectionCard>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
33
src/features/dashboard/hooks/useAnalytics.ts
Normal file
33
src/features/dashboard/hooks/useAnalytics.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
getAnalyticsBacklog,
|
||||
getAnalyticsBranches,
|
||||
getAnalyticsCustomers,
|
||||
getAnalyticsFinance,
|
||||
getAnalyticsProducts,
|
||||
getAnalyticsSystem,
|
||||
type AnalyticsParams,
|
||||
} from "../api/analyticsApi";
|
||||
|
||||
export const ANALYTICS_KEY = "dashboard-analytics";
|
||||
|
||||
const STALE_TIME = 60 * 1000;
|
||||
|
||||
function useAnalyticsQuery<T>(
|
||||
name: string,
|
||||
fetcher: (params: AnalyticsParams, signal?: AbortSignal) => Promise<T>,
|
||||
params: AnalyticsParams,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [ANALYTICS_KEY, name, params],
|
||||
queryFn: ({ signal }) => fetcher(params, signal),
|
||||
staleTime: STALE_TIME,
|
||||
});
|
||||
}
|
||||
|
||||
export const useAnalyticsFinance = (params: AnalyticsParams) => useAnalyticsQuery("finance", getAnalyticsFinance, params);
|
||||
export const useAnalyticsBacklog = (params: AnalyticsParams) => useAnalyticsQuery("backlog", getAnalyticsBacklog, params);
|
||||
export const useAnalyticsBranches = (params: AnalyticsParams) => useAnalyticsQuery("branches", getAnalyticsBranches, params);
|
||||
export const useAnalyticsProducts = (params: AnalyticsParams) => useAnalyticsQuery("products", getAnalyticsProducts, params);
|
||||
export const useAnalyticsCustomers = (params: AnalyticsParams) => useAnalyticsQuery("customers", getAnalyticsCustomers, params);
|
||||
export const useAnalyticsSystem = (params: AnalyticsParams) => useAnalyticsQuery("system", getAnalyticsSystem, params);
|
||||
Reference in New Issue
Block a user