connected api with card balance and and requisites
This commit is contained in:
1 parent
7dfac2bd59
commit
d8e903f24c
24 files changed
+2540
-2628
No files matched your search
@@ -1,114 +1,232 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download } from "lucide-react";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useCardBalances, useDeleteCardBalance, useDownloadCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCardBalances, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import type { CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
import { useInfiniteUsers } from "@/features/allUsers/hooks/useAllUsers";
|
||||
|
||||
const PER_PAGE = 25;
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "passportNumber", "cardLast4", "expiry", "balance", "status", "createdBy", "createdAt"] as const;
|
||||
|
||||
export default function CardBalancesPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const { data, isLoading } = useCardBalances({ page, per_page: perPage, search });
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const downloadMutation = useDownloadCardBalance();
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "created_by", value: "" },
|
||||
]);
|
||||
|
||||
// ── Columns ───────────────────────────────────────────────────────────────
|
||||
// ── Infinite user dropdown for created_by filter ────────────────────────────
|
||||
|
||||
const columns: ColumnDef<CardBalance>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button className="text-primary font-medium hover:underline" onClick={() => navigate(`/card-balances/${row.original.id}`)}>
|
||||
{row.original.id}
|
||||
</button>
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
data: usersInfiniteData,
|
||||
fetchNextPage: fetchNextUsers,
|
||||
hasNextPage: hasNextUsers,
|
||||
isFetchingNextPage: isFetchingNextUsers,
|
||||
isLoading: isUsersLoading,
|
||||
} = useInfiniteUsers(userSearch);
|
||||
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
(usersInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.users ?? []).map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || u.username || String(u.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "passport_series",
|
||||
accessorKey: "passport_series",
|
||||
header: t("Passport series", "PASPORT SERIYASY"),
|
||||
cell: ({ row }) => <span>{row.original.passport_series}</span>,
|
||||
},
|
||||
{
|
||||
id: "passport_number",
|
||||
accessorKey: "passport_number",
|
||||
header: t("Passport number", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span>{row.original.passport_number}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_number",
|
||||
accessorKey: "card_number",
|
||||
header: t("Card number", "KART BELGISI"),
|
||||
cell: ({ row }) => <span className="font-mono">{row.original.card_number}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_expiry_month",
|
||||
accessorKey: "card_expiry_month",
|
||||
header: t("Expiry month", "KART MÖHLETI (AÝ)"),
|
||||
cell: ({ row }) => <span>{row.original.card_expiry_month}</span>,
|
||||
},
|
||||
{
|
||||
id: "card_expiry_year",
|
||||
accessorKey: "card_expiry_year",
|
||||
header: t("Expiry year", "KART MÖHLETI (ÝYL)"),
|
||||
cell: ({ row }) => <span>{row.original.card_expiry_year}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[{ icon: Download, title: t("Download", "Ýükle"), onClick: () => downloadMutation.mutate(row.original.id) }]}
|
||||
onView={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
[usersInfiniteData],
|
||||
);
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
page,
|
||||
limit: perPage,
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
created_by: filterMap.created_by ? Number(filterMap.created_by) : undefined,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
const { data, isLoading } = useCardBalances(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardBalance.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardBalance.status.approved", "Tassyklanan") },
|
||||
{ value: "rejected", label: t("cardBalance.status.rejected", "Ret edilen") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback((id: number) => {
|
||||
setDeleteId(id);
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (deleteId === null) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns = useMemo<ColumnDef<CardBalance>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "passportNumber",
|
||||
accessorKey: "passportNumber",
|
||||
header: t("Passport number", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.passportNumber}</span>,
|
||||
},
|
||||
{
|
||||
id: "cardLast4",
|
||||
accessorKey: "cardLast4",
|
||||
header: t("Card last 4", "KART BELGISI (SOŇKY 4)"),
|
||||
cell: ({ row }) => <span className="font-mono">•••• •••• •••• {row.original.cardLast4}</span>,
|
||||
},
|
||||
{
|
||||
id: "expiry",
|
||||
accessorKey: "expiryMonth",
|
||||
header: t("Expiry", "KART MÖHLETI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground whitespace-nowrap">
|
||||
{String(row.original.expiryMonth).padStart(2, "0")}/{row.original.expiryYear}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "balance",
|
||||
accessorKey: "balanceAmount",
|
||||
header: t("Balance", "GALYNDY"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground font-medium whitespace-nowrap">
|
||||
{row.original.balanceAmount} {row.original.balanceCurrency}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardBalanceStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "createdBy",
|
||||
accessorKey: "createdBy",
|
||||
header: t("Created by", "DÖREDEN"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">{row.original.createdBy?.name || row.original.createdBy?.username || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm whitespace-nowrap">{new Date(row.original.createdAt).toLocaleString()}</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/card-balances/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-balances/${row.original.id}/edit`)}
|
||||
onDelete={() => handleDelete(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardBalance.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("Status", "STATUS"),
|
||||
options: statusOptions,
|
||||
},
|
||||
{
|
||||
id: "created_by",
|
||||
label: t("Created by", "DÖREDEN"),
|
||||
type: "infinite-select",
|
||||
options: userOptions,
|
||||
loading: isUsersLoading,
|
||||
isLoadingMore: isFetchingNextUsers,
|
||||
hasNextPage: hasNextUsers,
|
||||
onLoadMore: fetchNextUsers,
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
},
|
||||
],
|
||||
[t, statusOptions, userOptions, isUsersLoading, isFetchingNextUsers, hasNextUsers, userSearch],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card balances", "Kart galyndylary")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("cardBalance.title", "Kart galyndylary")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -116,25 +234,30 @@ export default function CardBalancesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
||||
/>
|
||||
<CreateButton label={t("Create card balance", "Kart galyndysy dörediň")} onClick={() => navigate("/card-balances/create")} />
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
searchPlaceholder={t("cardBalance.searchPlaceholder", "Pasport belgisi boýunça gözle")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
@@ -143,9 +266,10 @@ export default function CardBalancesPage() {
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardBalances ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -160,14 +284,15 @@ export default function CardBalancesPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
}}
|
||||
title={t("Are you sure?", "Eminsiňizmi?")}
|
||||
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
onConfirm={handleDelete}
|
||||
title={t("cardBalance.deleteConfirm", "Bu ýazgy pozulsynmy?")}
|
||||
description={t("cardBalance.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
onConfirm={confirmDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, Trash2, Pencil } from "lucide-react";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
@@ -14,25 +14,9 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
useCardBalance,
|
||||
useDeleteCardBalance,
|
||||
useDownloadCardBalance,
|
||||
} from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { InfoRow, CollapsibleSection, StatusBadge, EmptyState } from "@/components/viewPageComponents";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
|
||||
// ─── Types for operations table ───────────────────────────────────────────────
|
||||
|
||||
interface Operation {
|
||||
id: number;
|
||||
action_name: string;
|
||||
performed_by: string;
|
||||
target: string;
|
||||
status: "FINISHED" | "PENDING" | "FAILED";
|
||||
date: string;
|
||||
}
|
||||
import { useCardBalance, useDeleteCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { InfoRow } from "@/components/viewPageComponents";
|
||||
import { CardBalanceStatusBadge } from "@/features/cardBalance/components/cardBalanceStatusBadge";
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -42,67 +26,10 @@ export default function CardBalanceViewPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [opsSearch, setOpsSearch] = useState("");
|
||||
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useCardBalance(numericId);
|
||||
const deleteMutation = useDeleteCardBalance();
|
||||
const downloadMutation = useDownloadCardBalance();
|
||||
|
||||
// Placeholder operations — in real app fetch from API using numericId
|
||||
const operations: Operation[] = [];
|
||||
|
||||
const filteredOperations = operations.filter(
|
||||
(op) =>
|
||||
op.action_name.toLowerCase().includes(opsSearch.toLowerCase()) ||
|
||||
op.target.toLowerCase().includes(opsSearch.toLowerCase()),
|
||||
);
|
||||
|
||||
// ── Operations columns ──────────────────────────────────────────────────
|
||||
|
||||
const operationColumns: ColumnDef<Operation>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-primary font-semibold text-sm">
|
||||
{row.original.id}
|
||||
</span>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
accessorKey: "action_name",
|
||||
header: t("Action name", "AMALYŇ ADY"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.action_name}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "performed_by",
|
||||
header: t("Performed by", "KIM TARAPYNDAN"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.performed_by}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "target",
|
||||
header: t("Target", "AMALYŇ NYŞANY (TARGEDI)"),
|
||||
cell: ({ row }) => <span className="text-sm">{row.original.target}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("Status", "AMALYŇ STATUSY"),
|
||||
cell: ({ row }) => <StatusBadge status={row.original.status} />,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: t("Date", "SENE"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.date}
|
||||
</span>
|
||||
),
|
||||
size: 160,
|
||||
},
|
||||
];
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(numericId);
|
||||
@@ -114,7 +41,7 @@ export default function CardBalanceViewPage() {
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-7 w-64" />
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
@@ -126,11 +53,7 @@ export default function CardBalanceViewPage() {
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="text-center py-24 text-muted-foreground">
|
||||
{t("Not found", "Tapylmady")}
|
||||
</div>
|
||||
);
|
||||
return <div className="text-center py-24 text-muted-foreground">{t("Not found", "Tapylmady")}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -138,17 +61,9 @@ export default function CardBalanceViewPage() {
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("Card balance detail", "Kart galyndysy giňişleýin")}:
|
||||
{t("Card balance detail", "Kart galyndysy giňişleýin")}: #{data.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => downloadMutation.mutate(numericId)}
|
||||
disabled={downloadMutation.isPending}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -168,80 +83,37 @@ export default function CardBalanceViewPage() {
|
||||
{/* Detail card */}
|
||||
<div className="rounded-lg border border-border bg-card overflow-hidden">
|
||||
<InfoRow label={t("ID", "ID")} value={data.id} />
|
||||
<InfoRow label={t("Passport number", "Pasport belgisi")} value={data.passportNumber} />
|
||||
<InfoRow label={t("Card last 4", "Kart belgisi (soňky 4)")} value={data.cardLast4} />
|
||||
<InfoRow label={t("Card expiry", "Kart möhleti")} value={`${String(data.expiryMonth).padStart(2, "0")}/${data.expiryYear}`} />
|
||||
<InfoRow label={t("Balance amount", "Galyndy möçberi")} value={`${data.balanceAmount} ${data.balanceCurrency}`} />
|
||||
<InfoRow label={t("Status", "Status")}>
|
||||
<CardBalanceStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("Checked at", "Barlan wagty")} value={new Date(data.checkedAt).toLocaleString()} />
|
||||
<InfoRow
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={data.passport_series}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={data.passport_number}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={data.card_number}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||
value={data.card_expiry_month}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={data.card_expiry_year}
|
||||
label={t("Created by", "Döreden")}
|
||||
value={data.createdBy?.name || data.createdBy?.username || undefined}
|
||||
isLink
|
||||
href={data.createdBy?.id != null ? `/all-users/${data.createdBy.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("Created at", "Döredilen wagty")} value={new Date(data.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("Updated at", "Täzelenen wagty")} value={new Date(data.updatedAt).toLocaleString()} />
|
||||
</div>
|
||||
|
||||
{/* Ammallar (Operations) collapsible section */}
|
||||
<CollapsibleSection title={t("Operations", "Ammallar")}>
|
||||
<DataTableToolbar
|
||||
searchValue={opsSearch}
|
||||
onSearchChange={setOpsSearch}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={[]}
|
||||
columnVisibility={{}}
|
||||
onColumnVisibilityChange={() => {}}
|
||||
columnOrder={[]}
|
||||
onColumnOrderChange={() => {}}
|
||||
/>
|
||||
{filteredOperations.length === 0 ? (
|
||||
<EmptyState
|
||||
label={t(
|
||||
"No operations found",
|
||||
"Berlen kriterýalara Amal gabat gelmedi.",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<DataTable
|
||||
columns={operationColumns}
|
||||
data={filteredOperations}
|
||||
getRowId={(r) => String(r.id)}
|
||||
enableRowSelection
|
||||
/>
|
||||
)}
|
||||
</CollapsibleSection>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("Are you sure?", "Eminsiňizmi?")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("Are you sure?", "Eminsiňizmi?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t(
|
||||
"This action cannot be undone.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.",
|
||||
)}
|
||||
{t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart galyndysy hemişelik öçüriler.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t("Cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending
|
||||
? t("Deleting...", "Öçürilýär...")
|
||||
: t("Delete", "Öçür")}
|
||||
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
|
||||
{deleteMutation.isPending ? t("Deleting...", "Öçürilýär...") : t("Delete", "Öçür")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
|
||||
@@ -1,155 +1,353 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Download, AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ColumnMeta } from "@/components/dataTableToolbar";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { useCardRequisites, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useCardRequisites, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisite, CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useInfiniteCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { useInfiniteClients } from "@/features/clients/hooks/useClients";
|
||||
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_CONFIG: Record<CardRequisiteStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
pending: { label: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { label: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { label: "Ret edilen", variant: "error", icon: XCircle },
|
||||
const STATUS_CONFIG: Record<
|
||||
CardRequisiteStatus,
|
||||
{ labelKey: string; fallback: string; variant: StatusBadgeVariant; icon: React.ElementType }
|
||||
> = {
|
||||
pending: { labelKey: "cardRequisites.status.pending", fallback: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
approved: { labelKey: "cardRequisites.status.approved", fallback: "Tassyklanan", variant: "success", icon: CheckCircle2 },
|
||||
rejected: { labelKey: "cardRequisites.status.rejected", fallback: "Ret edilen", variant: "error", icon: XCircle },
|
||||
};
|
||||
|
||||
function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) {
|
||||
const cfg = STATUS_CONFIG[status];
|
||||
function CardRequisiteStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status as CardRequisiteStatus];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
return <StatusBadge label={t(cfg.labelKey, cfg.fallback)} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const PER_PAGE = 25;
|
||||
const COLUMN_IDS = ["id", "uniqueId", "cardType", "customer", "user", "region", "branch", "status"] as const;
|
||||
|
||||
// ─── Filter constants ─────────────────────────────────────────────────────────
|
||||
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
export default function CardRequisitesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
|
||||
const { data, isLoading } = useCardRequisites({
|
||||
page,
|
||||
per_page: perPage,
|
||||
search,
|
||||
});
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const downloadMutation = useDownloadCardRequisite();
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "region", value: "" },
|
||||
{ fieldId: "branch_id", value: "" },
|
||||
{ fieldId: "card_type_id", value: "" },
|
||||
{ fieldId: "user_id", value: "" },
|
||||
]);
|
||||
|
||||
// ── Columns ──────────────────────────────────────────────────────────────────
|
||||
// ── Infinite dropdown hooks ─────────────────────────────────────────────────
|
||||
|
||||
const columns: ColumnDef<CardRequisite>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left"
|
||||
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm || String(b.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "card_type",
|
||||
accessorKey: "card_type",
|
||||
header: t("Card type", "GÖRNÜŞI"),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.original.card_type}</span>,
|
||||
},
|
||||
{
|
||||
id: "created_at",
|
||||
accessorKey: "created_at",
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.created_at}</span>,
|
||||
},
|
||||
{
|
||||
id: "province_name",
|
||||
accessorKey: "province_name",
|
||||
header: t("Province", "WELAÝAT"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.province_name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "branch_name",
|
||||
accessorKey: "branch_name",
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.original.branch_name ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "first_name",
|
||||
accessorKey: "first_name",
|
||||
header: t("First name", "ADY"),
|
||||
cell: ({ row }) => <span>{row.original.first_name}</span>,
|
||||
},
|
||||
{
|
||||
id: "last_name",
|
||||
accessorKey: "last_name",
|
||||
header: t("Last name", "FAMILIÝASY"),
|
||||
cell: ({ row }) => <span>{row.original.last_name}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardRequisiteStatusBadge status={row.original.status} />,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[{ icon: Download, title: t("Download", "Ýükle"), onClick: () => downloadMutation.mutate(row.original.id) }]}
|
||||
onView={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
const [cardTypeSearch, setCardTypeSearch] = useState("");
|
||||
const {
|
||||
data: cardTypesInfiniteData,
|
||||
fetchNextPage: fetchNextCardTypes,
|
||||
hasNextPage: hasNextCardTypes,
|
||||
isFetchingNextPage: isFetchingNextCardTypes,
|
||||
isLoading: isCardTypesLoading,
|
||||
} = useInfiniteCardTypes(cardTypeSearch);
|
||||
|
||||
const cardTypeOptions = useMemo(
|
||||
() =>
|
||||
(cardTypesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.paymentCards ?? []).map((ct) => ({
|
||||
value: String(ct.id),
|
||||
label: ct.title[lang] || ct.title.tm || String(ct.id),
|
||||
})),
|
||||
),
|
||||
},
|
||||
];
|
||||
[cardTypesInfiniteData, lang],
|
||||
);
|
||||
|
||||
// ── Column meta for toolbar ───────────────────────────────────────────────────
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const {
|
||||
data: clientsInfiniteData,
|
||||
fetchNextPage: fetchNextClients,
|
||||
hasNextPage: hasNextClients,
|
||||
isFetchingNextPage: isFetchingNextClients,
|
||||
isLoading: isClientsLoading,
|
||||
} = useInfiniteClients(userSearch);
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
const clientOptions = useMemo(
|
||||
() =>
|
||||
(clientsInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.users ?? []).map((u) => ({
|
||||
value: String(u.id),
|
||||
label: u.name || u.username || String(u.id),
|
||||
})),
|
||||
),
|
||||
[clientsInfiniteData],
|
||||
);
|
||||
|
||||
// ── Pagination ────────────────────────────────────────────────────────────────
|
||||
// ── Query params & data ─────────────────────────────────────────────────────
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
search: search || undefined,
|
||||
status: filterMap.status || undefined,
|
||||
region: filterMap.region || undefined,
|
||||
branch_id: filterMap.branch_id ? Number(filterMap.branch_id) : undefined,
|
||||
card_type_id: filterMap.card_type_id ? Number(filterMap.card_type_id) : undefined,
|
||||
user_id: filterMap.user_id ? Number(filterMap.user_id) : undefined,
|
||||
page,
|
||||
limit: perPage,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
await deleteMutation.mutateAsync(deleteId);
|
||||
const { data, isLoading } = useCardRequisites(queryParams);
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardRequisites.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardRequisites.status.approved", "Tassyklanan") },
|
||||
{ value: "rejected", label: t("cardRequisites.status.rejected", "Ret edilen") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback((id: number) => {
|
||||
setDeleteId(id);
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (deleteId === null) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns = useMemo<ColumnDef<CardRequisite>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left cursor-pointer"
|
||||
onClick={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("Unique ID", "Unikal ID"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono">{row.original.uniqueId || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "cardType",
|
||||
accessorKey: "cardType",
|
||||
header: t("Card type", "GÖRNÜŞI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-primary font-medium">{resolveLocalizedName(row.original.cardType?.name, lang) || "—"}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "customer",
|
||||
accessorKey: "customerName",
|
||||
header: t("Customer", "MÜŞDERI"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">
|
||||
{row.original.customerSurname} {row.original.customerName}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
accessorKey: "user",
|
||||
header: t("User", "ULANYJY"),
|
||||
cell: ({ row }) => <span className="text-foreground">{row.original.user?.name || row.original.user?.username || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("Region", "WELAÝAT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-foreground">
|
||||
{row.original.region ? t(`loanOrders.regions.${row.original.region}`, row.original.region) : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
accessorKey: "branch",
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-foreground">{resolveLocalizedName(row.original.branch?.name, lang) || "—"}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <CardRequisiteStatusBadge status={row.original.status} />,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/card-requisites/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-requisites/${row.original.id}/edit`)}
|
||||
onDelete={() => handleDelete(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, lang, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`cardRequisites.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("Status", "STATUS"),
|
||||
options: statusOptions,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
label: t("Region", "WELAÝAT"),
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "branch_id",
|
||||
label: t("Branch", "ŞAHAMÇA"),
|
||||
type: "infinite-select",
|
||||
options: branchOptions,
|
||||
loading: isBranchesLoading,
|
||||
isLoadingMore: isFetchingNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
onLoadMore: fetchNextBranches,
|
||||
searchValue: branchSearch,
|
||||
onSearchChange: setBranchSearch,
|
||||
},
|
||||
{
|
||||
id: "card_type_id",
|
||||
label: t("Card type", "KART GÖRNÜŞI"),
|
||||
type: "infinite-select",
|
||||
options: cardTypeOptions,
|
||||
loading: isCardTypesLoading,
|
||||
isLoadingMore: isFetchingNextCardTypes,
|
||||
hasNextPage: hasNextCardTypes,
|
||||
onLoadMore: fetchNextCardTypes,
|
||||
searchValue: cardTypeSearch,
|
||||
onSearchChange: setCardTypeSearch,
|
||||
},
|
||||
{
|
||||
id: "user_id",
|
||||
label: t("User", "ULANYJY"),
|
||||
type: "infinite-select",
|
||||
options: clientOptions,
|
||||
loading: isClientsLoading,
|
||||
isLoadingMore: isFetchingNextClients,
|
||||
hasNextPage: hasNextClients,
|
||||
onLoadMore: fetchNextClients,
|
||||
searchValue: userSearch,
|
||||
onSearchChange: setUserSearch,
|
||||
},
|
||||
],
|
||||
[
|
||||
t,
|
||||
statusOptions,
|
||||
regionOptions,
|
||||
branchOptions,
|
||||
isBranchesLoading,
|
||||
isFetchingNextBranches,
|
||||
hasNextBranches,
|
||||
branchSearch,
|
||||
cardTypeOptions,
|
||||
isCardTypesLoading,
|
||||
isFetchingNextCardTypes,
|
||||
hasNextCardTypes,
|
||||
cardTypeSearch,
|
||||
clientOptions,
|
||||
isClientsLoading,
|
||||
isFetchingNextClients,
|
||||
hasNextClients,
|
||||
userSearch,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card requisites", "Kart rekwizitler")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("cardRequisites.title", "Kart rekwizitler")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
<TableSearchInput
|
||||
value={search}
|
||||
@@ -157,28 +355,33 @@ export default function CardRequisitesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("cardRequisites.createTitle", "Kart rekwiziti üçin sargyt dörediň")}
|
||||
onClick={() => navigate("/card-requisites/create")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={columnMeta}
|
||||
searchPlaceholder={t("cardRequisites.searchPlaceholder", "Gözlemek")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
@@ -190,29 +393,30 @@ export default function CardRequisitesPage() {
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardRekwizitOrders ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => row.id}
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Delete dialog */}
|
||||
<DeleteDialog
|
||||
open={deleteId !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
}}
|
||||
title={t("Are you sure?", "Eminsiňizmi?")}
|
||||
description={t("This action cannot be undone.", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
|
||||
onConfirm={handleDelete}
|
||||
title={t("cardRequisites.deleteConfirm", "Bu sargyt pozulsynmy?")}
|
||||
description={t("cardRequisites.deleteDescription", "Bu amal yzyna gaýtarylmaz. Kart rekwiziti hemişelik öçüriler.")}
|
||||
onConfirm={confirmDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { CardRequisiteForm } from '@/features/cardRequisites/components/cardRequisiteForm'
|
||||
import { useCardRequisite } from '@/features/cardRequisites/hooks/useCardRequisites'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageSpinner } from "@/components/pageSpinner";
|
||||
import { PageError } from "@/components/pageError";
|
||||
import { CardRequisiteForm } from "@/features/cardRequisites/components/cardRequisiteForm";
|
||||
import { useCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
|
||||
export default function CardRequisiteEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading } = useCardRequisite(id ?? '')
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { t } = useTranslation();
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useCardRequisite(numericId);
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (!data) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
if (isLoading) return <PageSpinner />;
|
||||
if (!data) return <PageError message={t("common.notFound", "Tapylmady")} />;
|
||||
|
||||
return <CardRequisiteForm mode="edit" initialData={data} />
|
||||
return <CardRequisiteForm mode="edit" initialData={data} />;
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useCardRequisite, useDeleteCardRequisite, useDownloadCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ArrowLeft, Pencil, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil, Trash2, Download } from "lucide-react";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -15,6 +14,9 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { useCardRequisite, useDeleteCardRequisite } from "@/features/cardRequisites/hooks/useCardRequisites";
|
||||
import type { CardRequisiteStatus } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { resolveLocalizedName } from "@/features/cardRequisites/api/cardRequisitesApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents";
|
||||
@@ -33,12 +35,13 @@ const STATUS_ICON: Record<CardRequisiteStatus, React.ElementType> = {
|
||||
rejected: XCircle,
|
||||
};
|
||||
|
||||
function CardRequisiteStatusBadge({ status }: { status: CardRequisiteStatus }) {
|
||||
function CardRequisiteStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const variant = STATUS_VARIANT[status];
|
||||
const Icon = STATUS_ICON[status];
|
||||
const key = status as CardRequisiteStatus;
|
||||
const variant = STATUS_VARIANT[key];
|
||||
const Icon = STATUS_ICON[key];
|
||||
if (!variant) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(`cardRequisite.status.${status}`)} variant={variant} icon={Icon} />;
|
||||
return <StatusBadge label={t(`cardRequisite.status.${key}`)} variant={variant} icon={Icon} />;
|
||||
}
|
||||
|
||||
// ─── Skeleton ─────────────────────────────────────────────────────────────────
|
||||
@@ -61,6 +64,13 @@ function CardRequisiteViewSkeleton() {
|
||||
);
|
||||
}
|
||||
|
||||
function formatDate(value?: string): string {
|
||||
if (!value) return "";
|
||||
const d = new Date(value);
|
||||
if (isNaN(d.getTime())) return value;
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function CardRequisiteViewPage() {
|
||||
@@ -68,9 +78,10 @@ export default function CardRequisiteViewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data, isLoading, isError } = useCardRequisite(id ?? "");
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading, isError } = useCardRequisite(numericId);
|
||||
const deleteMutation = useDeleteCardRequisite();
|
||||
const downloadMutation = useDownloadCardRequisite();
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
if (isLoading) {
|
||||
return <CardRequisiteViewSkeleton />;
|
||||
@@ -80,26 +91,29 @@ export default function CardRequisiteViewPage() {
|
||||
return <div className="flex items-center justify-center py-24 text-muted-foreground">{t("common.notFound", "Maglumat tapylmady")}</div>;
|
||||
}
|
||||
|
||||
const fullName = [data.customerName, data.customerPatronicName, data.customerSurname].filter(Boolean).join(" ");
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex flex-col gap-6">
|
||||
{/* ── Page header ──────────────────────────────────────────────────── */}
|
||||
<div className="flex items-start justify-between">
|
||||
<h1 className="text-xl font-bold text-foreground">
|
||||
{t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8"
|
||||
onClick={() => downloadMutation.mutate(data.id)}
|
||||
disabled={downloadMutation.isPending}
|
||||
>
|
||||
<Download size={15} />
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => navigate("/card-requisites")}>
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<h1 className="text-xl font-bold text-foreground">
|
||||
{t("cardRequisite.viewTitle", "Kart rekwizit giňişleýin")}: {data.id}
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogTitle asChild>
|
||||
<Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
</AlertDialogTitle>
|
||||
@@ -133,60 +147,78 @@ export default function CardRequisiteViewPage() {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard title={t("cardRequisite.metaSection", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
<InfoRow label={t("cardRequisite.createdAt", "Döredilen wagty")} value={data.created_at} />
|
||||
<InfoRow label={t("Unique ID", "Unikal ID")} value={data.uniqueId || undefined} />
|
||||
<InfoRow label={t("cardRequisite.createdAt", "Döredilen wagty")} value={new Date(data.createdAt).toLocaleString()} />
|
||||
<InfoRow label={t("cardRequisite.status", "Status")}>
|
||||
<CardRequisiteStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("cardRequisite.note", "Bellik")} value={data.note || undefined} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.createdBy", "Sargyt eden")}
|
||||
value={data.first_name && data.last_name ? `${data.last_name}_${data.first_name}` : undefined}
|
||||
isLink
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.note", "Bellik")} value={data.notes || undefined} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.cardSection", "Kart")}>
|
||||
<InfoRow label={t("cardRequisite.cardNumber", "Kart belgisi")} value={data.card_number} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireMonth", "Kart Möhleti (aý)")} value={data.card_expiry_month} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireYear", "Kart Möhleti (ýyl)")} value={data.card_expiry_year} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.cardType", "Kart görnüşi")}
|
||||
value={resolveLocalizedName(data.cardType?.name) || undefined}
|
||||
isLink
|
||||
href={data.cardType?.id != null ? `/settings/card/card-types/${data.cardType.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.cardNumber", "Kart belgisi")} value={data.cardNumber || undefined} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireMonth", "Kart Möhleti (aý)")} value={data.cardMonth || undefined} />
|
||||
<InfoRow label={t("cardRequisite.cardExpireYear", "Kart Möhleti (ýyl)")} value={data.cardYear || undefined} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.locationSection", "Lokasiýa")}>
|
||||
<InfoRow label={t("cardRequisite.province", "Welaýat")} value={data.province_name ?? undefined} />
|
||||
<InfoRow label={t("cardRequisite.branch", "Şahamça")} value={data.branch_name ?? undefined} isLink />
|
||||
<InfoRow label={t("cardRequisite.region", "Welaýat")} value={data.region || undefined} />
|
||||
<InfoRow
|
||||
label={t("cardRequisite.branch", "Şahamça")}
|
||||
value={resolveLocalizedName(data.branch?.name) || undefined}
|
||||
isLink
|
||||
href={data.branch?.id != null ? `/settings/location/branches/${data.branch.id}` : undefined}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Şahsy + Pasport maglumatlary ──────────────────────────── */}
|
||||
{/* ── Row 2: Şahsy + Ulanyjy + Pasport maglumatlary ─────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardRequisite.personalSection", "Şahsy maglumatlar")}>
|
||||
<InfoRow
|
||||
label={t("cardRequisite.fullName", "Doly ady")}
|
||||
value={[data.first_name, data.last_name, data.middle_name].filter(Boolean).join(" ")}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.birthDate", "Doglan güni")} value={data.birth_date} />
|
||||
<InfoRow label={t("cardRequisite.fullName", "Doly ady")} value={fullName} />
|
||||
<InfoRow label={t("cardRequisite.birthDate", "Doglan güni")} value={formatDate(data.bornAt)} />
|
||||
<InfoRow label={t("cardRequisite.phone", "Telefon")} value={data.phone} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardRequisite.passportSection", "Pasport")}>
|
||||
<InfoRow label={t("cardRequisite.passportSeries", "Pasport seriýasy")} value={data.passport_series} />
|
||||
<InfoRow label={t("cardRequisite.passportNumber", "Pasport belgisi")} value={data.passport_number} />
|
||||
<BentoCard title={t("cardRequisite.userSection", "Ulanyjy")}>
|
||||
<InfoRow
|
||||
label={t("cardRequisite.userName", "Ulanyjy ady")}
|
||||
value={data.user?.name || data.user?.username || undefined}
|
||||
isLink
|
||||
href={data.user?.id != null ? `/clients/${data.user.id}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardRequisite.userPhone", "Ulanyjy telefon")} value={data.user?.phone || undefined} />
|
||||
<InfoRow label={t("cardRequisite.userEmail", "Ulanyjy e-poçta")} value={data.user?.email || undefined} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Passport images ────────────────────────────────────────── */}
|
||||
{/* ── Row 3: Pasport maglumatlary ───────────────────────────────────── */}
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard title={t("cardRequisite.passportSection", "Pasport")}>
|
||||
<InfoRow label={t("cardRequisite.passportSeries", "Pasport seriýasy")} value={data.passportSerie} />
|
||||
<InfoRow label={t("cardRequisite.passportNumber", "Pasport belgisi")} value={data.passportId} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 4: Passport images ────────────────────────────────────────── */}
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard title={t("cardRequisite.passportFile1", "Sahypa 1")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile1", "Pasport (sahypa 1)")} src={data.passport_page1_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile1", "Pasport (sahypa 1)")} src={data.passportOne} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile2", "Sahypa 2-3")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile2", "Pasport (2-3-nji sahypa)")} src={data.passport_page2_3_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile2", "Pasport (2-3-nji sahypa)")} src={data.passportTwo} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile3", "Sahypa 8-9")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile3", "Pasport (8-9 sahypa)")} src={data.passport_page8_9_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile3", "Pasport (8-9 sahypa)")} src={data.passportThree} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardRequisite.passportFile4", "Sahypa 32")}>
|
||||
<PassportImage label={t("cardRequisite.passportFile4", "Pasport (32-nji sahypa)")} src={data.passport_page32_url} />
|
||||
<PassportImage label={t("cardRequisite.passportFile4", "Pasport (32-nji sahypa)")} src={data.passportFour} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle, CheckCircle2, XCircle, CheckCheck } from "lucide-react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import { useLoanOrderMobiles, useDeleteLoanOrderMobile } from "@/features/loanOrderMobiles/hooks/useLoanOrderMobiles";
|
||||
import type { LoanOrderMobile, LoanOrderMobileStatus } from "@/features/loanOrderMobiles/api/loanOrderMobilesApi";
|
||||
import { useInfiniteBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { getStatusLabel, getStatusOptions, STATUS_BADGE_VARIANTS, type StatusValue } from "@/constants";
|
||||
|
||||
@@ -30,24 +32,43 @@ function LoanOrderStatusBadge({ status }: { status: LoanOrderMobileStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Column IDs ────────────────────────────────────────────────────────────────
|
||||
// ─── Column meta for toggle dropdown ─────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "loanType", "createdAt", "region", "branch", "firstName", "lastName", "phone", "status"] as const;
|
||||
|
||||
// ─── Filter options ────────────────────────────────────────────────────────────
|
||||
// ─── Filter fields ────────────────────────────────────────────────────────────
|
||||
|
||||
// ─── Filter options (Internal keys/values) ───────────────────────────────────
|
||||
const REGION_OPTIONS = ["Balkan", "Ahal", "Daşoguz", "Lebap", "Mary", "Aşgabat"];
|
||||
const REGION_CODES = ["AG", "AH", "BN", "DZ", "LB", "MR"] as const;
|
||||
|
||||
// ─── Page Component ────────────────────────────────────────────────────────────
|
||||
// ─── Page Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export default function LoanOrderMobilesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteLoanOrderMobile();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [branchSearch, setBranchSearch] = useState("");
|
||||
const {
|
||||
data: branchesInfiniteData,
|
||||
fetchNextPage: fetchNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
isFetchingNextPage: isFetchingNextBranches,
|
||||
isLoading: isBranchesLoading,
|
||||
} = useInfiniteBranches(branchSearch);
|
||||
|
||||
const branchOptions = useMemo(
|
||||
() =>
|
||||
(branchesInfiniteData?.pages ?? []).flatMap((page) =>
|
||||
(page?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
),
|
||||
[branchesInfiniteData, lang],
|
||||
);
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
@@ -60,7 +81,6 @@ export default function LoanOrderMobilesPage() {
|
||||
{ fieldId: "archived", value: "" },
|
||||
]);
|
||||
|
||||
// ── Query params ───────────────────────────────────────────────────────────
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
@@ -77,7 +97,8 @@ export default function LoanOrderMobilesPage() {
|
||||
const { data, isLoading } = useLoanOrderMobiles(queryParams);
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const regionOptions = useMemo(() => REGION_CODES.map((code) => ({ value: code, label: t(`loanOrders.regions.${code}`, code) })), [t]);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
@@ -98,68 +119,69 @@ export default function LoanOrderMobilesPage() {
|
||||
setDeleteId(null);
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ────────────────────────────────────────────────────────────────
|
||||
const columns = useMemo<ColumnDef<LoanOrderMobile>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("loanOrderMobiles.columns.id", "ID"),
|
||||
header: t("ID", "ID"),
|
||||
cell: ({ row }) => <span className="text-xs font-mono text-muted-foreground">{row.original.id}</span>,
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: "loanType",
|
||||
accessorKey: "loanType",
|
||||
header: t("loanOrderMobiles.columns.loanType", "KARZ GÖRNÜŞI"),
|
||||
header: t("Loan type", "KARZ GÖRNÜŞI"),
|
||||
cell: ({ row }) => <span className="text-sm font-medium text-primary hover:underline cursor-pointer">{row.original.loanType}</span>,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("loanOrderMobiles.columns.createdAt", "DÖREDILEN WAGTY"),
|
||||
header: t("Created at", "DÖREDILEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground whitespace-nowrap">{row.original.createdAt}</span>,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("loanOrderMobiles.columns.region", "WELAÝAT"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
header: t("Region", "WELAÝAT"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">{t(`loanOrders.regions.${row.original.region}`, row.original.region)}</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
accessorKey: "branch",
|
||||
header: t("loanOrderMobiles.columns.branch", "ŞAHAMÇA"),
|
||||
header: t("Branch", "ŞAHAMÇA"),
|
||||
cell: ({ row }) => <span className="text-sm text-emerald-500 font-medium">{row.original.branch}</span>,
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
id: "firstName",
|
||||
accessorKey: "firstName",
|
||||
header: t("loanOrderMobiles.columns.firstName", "ADY"),
|
||||
header: t("Name", "ADY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.firstName}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "lastName",
|
||||
accessorKey: "lastName",
|
||||
header: t("loanOrderMobiles.columns.lastName", "FAMILIÝASY"),
|
||||
header: t("Surname", "FAMILIÝASY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.lastName}</span>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("loanOrderMobiles.columns.phone", "TELEFON"),
|
||||
header: t("Phone", "TELEFON"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.phone}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("loanOrderMobiles.columns.status", "STATUS"),
|
||||
header: t("Status", "STATUS"),
|
||||
cell: ({ row }) => <LoanOrderStatusBadge status={row.original.status} />,
|
||||
size: 180,
|
||||
},
|
||||
@@ -178,47 +200,51 @@ export default function LoanOrderMobilesPage() {
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, handleDelete, deleteMutation.isPending, navigate],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
// ── Column meta for toolbar ────────────────────────────────────────────────
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrderMobiles.columns.${id}`, id) })), [t]);
|
||||
const toggleableColumns = useMemo(() => COLUMN_IDS.map((id) => ({ id, label: t(`loanOrders.columns.${id}`, id) })), [t]);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "region",
|
||||
label: t("loanOrderMobiles.filters.region", "WELAÝAT"),
|
||||
options: REGION_OPTIONS.map((v) => ({ value: v, label: t(v) })),
|
||||
label: t("Region", "WELAÝAT"),
|
||||
options: regionOptions,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
label: t("loanOrderMobiles.filters.status", "STATUS"),
|
||||
label: t("Status", "STATUS"),
|
||||
options: getStatusOptions(t, "loanOrderStatus"),
|
||||
},
|
||||
{
|
||||
id: "branch",
|
||||
label: t("loanOrderMobiles.filters.branch", "ŞAHAMÇA"),
|
||||
options: [],
|
||||
label: t("Branch", "ŞAHAMÇA"),
|
||||
type: "infinite-select",
|
||||
options: branchOptions,
|
||||
loading: isBranchesLoading,
|
||||
isLoadingMore: isFetchingNextBranches,
|
||||
hasNextPage: hasNextBranches,
|
||||
onLoadMore: fetchNextBranches,
|
||||
searchValue: branchSearch,
|
||||
onSearchChange: setBranchSearch,
|
||||
},
|
||||
{
|
||||
id: "archived",
|
||||
label: t("loanOrderMobiles.filters.archived", "ARHIWLENEN"),
|
||||
label: t("loanOrders.filters.archived", "ARHIWLENEN"),
|
||||
options: [
|
||||
{ value: "true", label: t("common.yes", "Hawa") },
|
||||
{ value: "false", label: t("common.no", "Ýok") },
|
||||
],
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, regionOptions, branchOptions, isBranchesLoading, isFetchingNextBranches, hasNextBranches, branchSearch],
|
||||
);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("loanOrderMobiles.title", "Karz sargytlary")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("loanOrderMobiles.title", "Karz sargytlary (Mobile)")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
@@ -228,23 +254,24 @@ export default function LoanOrderMobilesPage() {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
placeholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton
|
||||
label={t("loanOrderMobiles.createButton", "Karz sargyt dörediň")}
|
||||
label={t("loanOrderMobiles.createButton", "Karz sargyt dörediñ")}
|
||||
onClick={() => navigate("/loan-order-mobiles/create")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Table Card */}
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
<DataTableToolbar
|
||||
hideSearch
|
||||
hideAction
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
setSearch(v);
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
searchPlaceholder={t("loanOrderMobiles.searchPlaceholder", "Gözlemek")}
|
||||
columns={toggleableColumns}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -260,8 +287,6 @@ export default function LoanOrderMobilesPage() {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
|
||||
+65
-26
@@ -24,7 +24,7 @@ import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import { useInfinitePermissions } from "@/features/permissions/hooks/usePermissions";
|
||||
import { useInfiniteBranches } from "@/features/shared/hooks/useSharedBranchUsers";
|
||||
import { useInfiniteStaff } from "@/features/operators/hooks/useOperators";
|
||||
import { useAssignRoleToUser, useAssignPermissionToUser, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import { useAssignRoleToUser, useAssignPermissionToRole, useAssignBranchToUser } from "@/features/shared/hooks/useSharedUserAssignments";
|
||||
import type { LocalizedText } from "@/features/branches/api/branchesApi";
|
||||
|
||||
type AssignDialogKind = "role" | "permission" | "branch";
|
||||
@@ -43,6 +43,7 @@ export default function ProfilePage() {
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const branches = user?.branches ?? [];
|
||||
const permissions = user?.permissions ?? [];
|
||||
|
||||
// ── Form State for Editing ──
|
||||
const [formData, setFormData] = useState({
|
||||
@@ -233,7 +234,22 @@ export default function ProfilePage() {
|
||||
</InfoRow>
|
||||
|
||||
<InfoRow label={t("users.sections.permissions", "Rugsatlar")}>
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
{permissions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{permissions.map((p) => (
|
||||
<Link
|
||||
key={p.id}
|
||||
to={`/settings/users/permissions/${p.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs border border-border rounded-md px-2 py-1 hover:bg-muted transition-colors"
|
||||
>
|
||||
<KeyRound size={11} className="text-muted-foreground" />
|
||||
<span className="text-foreground font-medium">{p.name || p.code || p.id}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
</BentoCard>
|
||||
|
||||
@@ -336,26 +352,31 @@ const ASSIGN_DIALOG_FIELD_LABELS: Record<AssignDialogKind, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Dialog for assigning a role / permission / branch to a staff user.
|
||||
* Two selects: target user (GET /users/staff) and the resource to assign.
|
||||
* Dialog for assigning a role / branch to a staff user, or assigning a permission to a role.
|
||||
*/
|
||||
function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () => void }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as keyof LocalizedText;
|
||||
|
||||
const [userSearch, setUserSearch] = useState("");
|
||||
const [userValue, setUserValue] = useState("");
|
||||
const isPermission = kind === "permission";
|
||||
|
||||
const [targetSearch, setTargetSearch] = useState("");
|
||||
const [targetValue, setTargetValue] = useState("");
|
||||
const [resourceSearch, setResourceSearch] = useState("");
|
||||
const [resourceValue, setResourceValue] = useState("");
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
|
||||
const staffQuery = useInfiniteStaff(userSearch);
|
||||
// Target query: Staff users when assigning role/branch to a user; Roles when assigning permission to a role.
|
||||
const staffQuery = useInfiniteStaff(targetSearch);
|
||||
const targetRolesQuery = useInfiniteRoles(targetSearch, isPermission);
|
||||
|
||||
// Resource query:
|
||||
const rolesQuery = useInfiniteRoles(resourceSearch, kind === "role");
|
||||
const permissionsQuery = useInfinitePermissions(resourceSearch, kind === "permission");
|
||||
const branchesQuery = useInfiniteBranches(resourceSearch, kind === "branch");
|
||||
|
||||
const roleMutation = useAssignRoleToUser();
|
||||
const permissionMutation = useAssignPermissionToUser();
|
||||
const permissionMutation = useAssignPermissionToRole();
|
||||
const branchMutation = useAssignBranchToUser();
|
||||
const isPending = roleMutation.isPending || permissionMutation.isPending || branchMutation.isPending;
|
||||
|
||||
@@ -370,6 +391,24 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
[staffQuery.data],
|
||||
);
|
||||
|
||||
const targetRoleOptions: InfiniteSelectOption[] = useMemo(
|
||||
() =>
|
||||
(targetRolesQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p?.roles ?? [])
|
||||
.map((r) => ({ value: String(r.id), label: r.name || r.code || String(r.id) })),
|
||||
[targetRolesQuery.data],
|
||||
);
|
||||
|
||||
const targetOptions = isPermission ? targetRoleOptions : staffOptions;
|
||||
const targetLabel = isPermission ? t("users.fields.role", "Rol") : t("profile.assign.userLabel", "Ulanyjy (staff)");
|
||||
const targetLoading = isPermission ? targetRolesQuery.isLoading : staffQuery.isLoading;
|
||||
const targetLoadingMore = isPermission ? targetRolesQuery.isFetchingNextPage : staffQuery.isFetchingNextPage;
|
||||
const targetHasNextPage = isPermission ? !!targetRolesQuery.hasNextPage : !!staffQuery.hasNextPage;
|
||||
const loadMoreTargets = () => {
|
||||
if (isPermission) targetRolesQuery.fetchNextPage();
|
||||
else staffQuery.fetchNextPage();
|
||||
};
|
||||
|
||||
const resourceOptions: InfiniteSelectOption[] = useMemo(() => {
|
||||
if (kind === "role") {
|
||||
return (rolesQuery.data?.pages ?? [])
|
||||
@@ -406,23 +445,23 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!userValue || !resourceValue) {
|
||||
if (!targetValue || !resourceValue) {
|
||||
setError(t("common.errors.required", "Meýdança hökmany doldurylmaly"));
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
const userId = Number(userValue);
|
||||
const resourceId = Number(resourceValue);
|
||||
const firstId = Number(targetValue);
|
||||
const secondId = Number(resourceValue);
|
||||
const onSuccess = () => {
|
||||
setUserValue("");
|
||||
setTargetValue("");
|
||||
setResourceValue("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (kind === "role") roleMutation.mutate({ userId, roleId: resourceId }, { onSuccess });
|
||||
else if (kind === "permission") permissionMutation.mutate({ userId, permissionId: resourceId }, { onSuccess });
|
||||
else branchMutation.mutate({ userId, branchId: resourceId }, { onSuccess });
|
||||
if (kind === "role") roleMutation.mutate({ userId: firstId, roleId: secondId }, { onSuccess });
|
||||
else if (kind === "permission") permissionMutation.mutate({ roleId: firstId, permissionId: secondId }, { onSuccess });
|
||||
else branchMutation.mutate({ userId: firstId, branchId: secondId }, { onSuccess });
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -438,20 +477,20 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
<div className="space-y-3">
|
||||
<InfiniteSelect
|
||||
required
|
||||
label={t("profile.assign.userLabel", "Ulanyjy (staff)")}
|
||||
value={userValue}
|
||||
label={targetLabel}
|
||||
value={targetValue}
|
||||
onChange={(v) => {
|
||||
setUserValue(v);
|
||||
setTargetValue(v);
|
||||
if (error) setError(undefined);
|
||||
}}
|
||||
options={staffOptions}
|
||||
options={targetOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
loading={staffQuery.isLoading}
|
||||
isLoadingMore={staffQuery.isFetchingNextPage}
|
||||
hasNextPage={!!staffQuery.hasNextPage}
|
||||
onLoadMore={() => staffQuery.fetchNextPage()}
|
||||
searchValue={userSearch}
|
||||
onSearchChange={setUserSearch}
|
||||
loading={targetLoading}
|
||||
isLoadingMore={targetLoadingMore}
|
||||
hasNextPage={targetHasNextPage}
|
||||
onLoadMore={loadMoreTargets}
|
||||
searchValue={targetSearch}
|
||||
onSearchChange={setTargetSearch}
|
||||
/>
|
||||
|
||||
<InfiniteSelect
|
||||
@@ -478,7 +517,7 @@ function AssignDialog({ kind, onClose }: { kind: AssignDialogKind; onClose: () =
|
||||
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
|
||||
{t("common.cancel", "Yza")}
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSubmit} disabled={!userValue || !resourceValue || isPending}>
|
||||
<Button size="sm" onClick={handleSubmit} disabled={!targetValue || !resourceValue || isPending}>
|
||||
{t("common.save", "Ýatda sakla")}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
|
||||
Reference in new issue
Block a user