50 lines
2.4 KiB
TypeScript
50 lines
2.4 KiB
TypeScript
import { useCallback } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import type { TFunction } from "i18next";
|
|
import { REGION_LABELS } from "@/constants/regionCodes";
|
|
import { getOrderTypeLabel } from "@/constants/orderTypes";
|
|
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 {
|
|
return getOrderTypeLabel(type, t);
|
|
}
|
|
|
|
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);
|
|
}
|