updated login, added client, staff api, forget and register api

This commit is contained in:
Jelaletdin12 committed 2026-08-14 22:48:57 +05:00
1 parent 5073166931
commit 0e75c85fe1
16 files changed
+1501 -980

No files matched your search

+442 -50
View File
@@ -3,12 +3,20 @@ import BankImage from "@/assets/bank-img.png";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useLogin } from "@/features/auth/hooks/useLogin";
import { useRegister, useRegisterVerify } from "@/features/auth/hooks/useRegister";
import { useForgotPassword, useForgotPasswordVerify } from "@/features/auth/hooks/useForgotPassword";
import { useThemeStore } from "@/app/store/themeStore";
import { useTranslation } from "react-i18next";
import { Sun, Moon, Globe } from "lucide-react";
import { Sun, Moon, Globe, MessageSquare } from "lucide-react";
import { toast } from "sonner";
import { cleanPhoneNumber } from "@/lib/utils";
import { cn } from "@/lib/utils";
type AuthView = "login" | "register" | "reset-password";
// ─── Auth view type ───────────────────────────────────────────────────────────
type AuthView = "login" | "register" | "register-verify" | "forgot-password" | "forgot-password-verify";
// ─── LeftPanel ─────────────────────f───────────────────────────────────────────
function LeftPanel() {
return (
@@ -18,6 +26,8 @@ function LeftPanel() {
);
}
// ─── Header ───────────────────────────────────────────────────────────────────
function Header() {
const { theme, toggleTheme } = useThemeStore();
const { i18n } = useTranslation();
@@ -62,13 +72,15 @@ function Header() {
);
}
interface FormInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange" | "value"> {
// ─── Simple FormInput (used in login / reset-password) ────────────────────────
interface SimpleFormInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange" | "value"> {
label: string;
value: string;
onChange: (val: string) => void;
}
function FormInput({ label, value, onChange, ...props }: FormInputProps) {
function FormInput({ label, value, onChange, ...props }: SimpleFormInputProps) {
return (
<div className="mb-4">
<label className="block text-[13px] font-medium text-foreground mb-1.5">{label}</label>
@@ -82,30 +94,256 @@ function FormInput({ label, value, onChange, ...props }: FormInputProps) {
);
}
// ─── PhoneInput (matches the existing formInput.tsx component pattern) ────────
interface PhoneInputFieldProps {
label: string;
value: string;
onChange: (val: string) => void;
disabled?: boolean;
}
function PhoneInputField({ label, value, onChange, disabled }: PhoneInputFieldProps) {
const cleanedDigits = cleanPhoneNumber(value);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const digits = e.target.value.replace(/\D/g, "").slice(0, 8);
if (digits.length <= 2) {
onChange(digits);
} else {
onChange(`${digits.slice(0, 2)} ${digits.slice(2)}`);
}
};
const formattedDisplayValue = cleanedDigits.length <= 2 ? cleanedDigits : `${cleanedDigits.slice(0, 2)} ${cleanedDigits.slice(2)}`;
return (
<div className="mb-4">
<label className="block text-[13px] font-medium text-foreground mb-1.5">{label}</label>
<div
className={cn(
"flex h-11 w-full rounded-md border bg-background overflow-hidden",
"ring-offset-background transition-colors duration-150",
"focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-0",
"border-input",
disabled && "opacity-50 cursor-not-allowed",
)}
>
<div className="flex items-center px-3 bg-muted/50 border-r border-input text-sm font-medium text-muted-foreground shrink-0 select-none">
+993
</div>
<input
type="tel"
value={formattedDisplayValue}
onChange={handleChange}
placeholder="61 097651"
disabled={disabled}
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none disabled:cursor-not-allowed"
/>
</div>
</div>
);
}
// ─── AuthPage ─────────────────────────────────────────────────────────────────
export default function AuthPage() {
const { t } = useTranslation();
// Mutations
const loginMutation = useLogin();
const registerMutation = useRegister();
const registerVerifyMutation = useRegisterVerify();
const forgotPasswordMutation = useForgotPassword();
const forgotPasswordVerifyMutation = useForgotPasswordVerify();
// View
const [view, setView] = useState<AuthView>("login");
const [username, setUsername] = useState("");
// Login fields
const [identifier, setIdentifier] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [phone, setPhone] = useState("");
const [fullName, setFullName] = useState("");
// Register fields
const [regName, setRegName] = useState("");
const [regPhone, setRegPhone] = useState("");
const [regUsername, setRegUsername] = useState("");
const [regPassword, setRegPassword] = useState("");
const [regPasswordConfirm, setRegPasswordConfirm] = useState("");
// SMS verification
const [smsCode, setSmsCode] = useState("");
// Forgot password fields
const [forgotName, setForgotName] = useState("");
const [forgotCode, setForgotCode] = useState("");
const [forgotPassword, setForgotPassword] = useState("");
const [forgotPasswordConfirm, setForgotPasswordConfirm] = useState("");
// ── Login ──────────────────────────────────────────────────────────────────
// Returns true if the identifier looks like a phone number (only digits / spaces)
const identifierIsPhone = (val: string) => /^[\d\s]*$/.test(val) && val.replace(/\D/g, "").length > 0;
const handleIdentifierChange = (raw: string) => {
// If the new value is all digits/spaces → apply phone formatting (XX XXXXXX, max 8 digits)
if (/^[\d\s]*$/.test(raw)) {
const digits = raw.replace(/\D/g, "").slice(0, 8);
if (digits.length <= 2) {
setIdentifier(digits);
} else {
setIdentifier(`${digits.slice(0, 2)} ${digits.slice(2)}`);
}
} else {
// Username mode — allow any chars but strip leading/trailing spaces
setIdentifier(raw);
}
};
const handleLogin = () => {
if (!username || !password) {
if (!identifier || !password) {
toast.error(t("Write a correct data please", "Please enter valid data"));
return;
}
loginMutation.mutate({ email: username, password });
const digits = identifier.replace(/\D/g, "");
const isPhone = identifierIsPhone(identifier);
loginMutation.mutate(isPhone ? { phone: `+993${digits}`, password } : { name: identifier.trim(), password });
};
// Mock submit for other views
const handleOtherSubmit = async () => {
toast.info(t("featureNotImplemented", "This feature is not implemented yet"));
// ── Register step 1 ────────────────────────────────────────────────────────
const handleRegister = () => {
const digits = cleanPhoneNumber(regPhone);
if (!regName || !regPhone || !regUsername || !regPassword || !regPasswordConfirm) {
toast.error(t("Please fill in all fields", "Ähli meýdançalary dolduryň"));
return;
}
if (digits.length !== 8) {
toast.error(t("Phone number must be 8 digits", "Telefon belgisi 8 san bolmaly"));
return;
}
if (regPassword !== regPasswordConfirm) {
toast.error(t("Passwords do not match", "Açar sözler gabat gelmeýär"));
return;
}
registerMutation.mutate(
{
name: regName,
username: regUsername,
phone: `+993${digits}`,
password: regPassword,
passwordConfirm: regPasswordConfirm,
},
{
onSuccess: () => {
toast.success(t("SMS code sent", "SMS kody iberildi"));
setView("register-verify");
},
onError: () => {
toast.error(t("Registration failed", "Hasaba alyş başa barmady"));
},
},
);
};
// ── Register step 2: SMS verify ────────────────────────────────────────────
const handleVerify = () => {
const digits = cleanPhoneNumber(regPhone);
if (!smsCode) {
toast.error(t("Please enter the SMS code", "SMS kodyny giriziň"));
return;
}
registerVerifyMutation.mutate(
{ code: smsCode, phone: `+993${digits}` },
{
onSuccess: () => {
toast.success(t("Registration successful!", "Hasaba alyş üstünlikli!"));
// Reset register state and go to login
setRegName("");
setRegPhone("");
setRegUsername("");
setRegPassword("");
setRegPasswordConfirm("");
setSmsCode("");
setView("login");
},
onError: () => {
toast.error(t("Invalid SMS code", "SMS kody ýalňyş"));
},
},
);
};
// ── Forgot password step 1 ────────────────────────────────────────────────
const handleForgotPassword = () => {
if (!forgotName) {
toast.error(t("Please enter your username", "Ulanyjy adyňyzy giriziň"));
return;
}
forgotPasswordMutation.mutate(
{ name: forgotName },
{
onSuccess: () => {
toast.success(t("SMS code sent", "SMS kody iberildi"));
setView("forgot-password-verify");
},
onError: () => {
toast.error(t("User not found", "Ulanyjy tapylmady"));
},
},
);
};
// ── Forgot password step 2: new password ──────────────────────────────────
const handleForgotPasswordVerify = () => {
if (!forgotCode || !forgotPassword || !forgotPasswordConfirm) {
toast.error(t("Please fill in all fields", "Ähli meýdançalary dolduryň"));
return;
}
if (forgotPassword !== forgotPasswordConfirm) {
toast.error(t("Passwords do not match", "Açar sözler gabat gelmeýär"));
return;
}
forgotPasswordVerifyMutation.mutate(
{
code: forgotCode,
name: forgotName,
password: forgotPassword,
passwordConfirm: forgotPasswordConfirm,
},
{
onSuccess: () => {
toast.success(t("Password reset successful!", "Açar söz üstünlikli üýtgedildi!"));
setForgotName("");
setForgotCode("");
setForgotPassword("");
setForgotPasswordConfirm("");
setView("login");
},
onError: () => {
toast.error(t("Invalid code or data", "Ýalňyş kod ýa-da maglumat"));
},
},
);
};
// ── Privacy policy link ────────────────────────────────────────────────────
const PrivacyLink = () => (
<div className="text-center mt-8">
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
{t("Privacy Policy")}
</span>
</div>
);
return (
<div className="flex flex-col h-screen bg-background text-foreground font-sans">
<Header />
@@ -115,6 +353,7 @@ export default function AuthPage() {
<div className="w-full md:w-[45%] flex flex-col bg-background">
<div className="flex-1 flex flex-col justify-center items-center px-8 sm:px-12 py-10 overflow-y-auto">
<div className="w-full max-w-[400px]">
{/* ── LOGIN ── */}
{view === "login" && (
<>
<h2 className="text-[22px] font-normal text-foreground text-center mb-2 tracking-wide uppercase">
@@ -122,12 +361,38 @@ export default function AuthPage() {
</h2>
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
<FormInput
label={t("Phone or username", "Telefon ýada ulanyjy ady")}
value={username}
onChange={setUsername}
placeholder="65999990 ýada ulanyjy_ady"
/>
{/* Smart phone / username input */}
<div className="mb-4">
<label className="block text-[13px] font-medium text-foreground mb-1.5">
{t("Phone or name", "Telefon ýa-da ulanyjy ady")}
</label>
<div
className={cn(
"flex h-11 w-full rounded-md border bg-background overflow-hidden",
"ring-offset-background transition-colors duration-150",
"focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-0 border-input",
loginMutation.isPending && "opacity-50 cursor-not-allowed",
)}
>
{identifierIsPhone(identifier) && (
<div className="flex items-center px-3 bg-muted/50 border-r border-input text-sm font-medium text-muted-foreground shrink-0 select-none transition-all">
+993
</div>
)}
<input
type="text"
inputMode={identifierIsPhone(identifier) ? "numeric" : "text"}
value={identifier}
onChange={(e) => handleIdentifierChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleLogin();
}}
placeholder={t("61 097651 or name", "61 097651 ýa-da ulanyjy_ady")}
disabled={loginMutation.isPending}
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none disabled:cursor-not-allowed"
/>
</div>
</div>
<FormInput
label={t("Password")}
type="password"
@@ -136,10 +401,11 @@ export default function AuthPage() {
onKeyDown={(e) => {
if (e.key === "Enter") handleLogin();
}}
disabled={loginMutation.isPending}
/>
<div className="text-right mb-6 -mt-2">
<span onClick={() => setView("reset-password")} className="text-[13px] text-primary cursor-pointer hover:underline">
<span onClick={() => setView("forgot-password")} className="text-[13px] text-primary cursor-pointer hover:underline">
{t("Forgot your password?")}
</span>
</div>
@@ -153,65 +419,191 @@ export default function AuthPage() {
</Button>
</div>
<div className="text-center mt-8">
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
{t("Privacy Policy")}
</span>
</div>
<PrivacyLink />
</>
)}
{/* ── REGISTER (step 1) ── */}
{view === "register" && (
<>
<h2 className="text-xl font-normal text-foreground text-center mb-2">{t("Online panel", "Onlaýn kabulhana")}</h2>
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
<FormInput label={t("Full Name")} value={fullName} onChange={setFullName} />
<FormInput label={t("Phone")} value={phone} onChange={setPhone} />
<FormInput label={t("Username")} value={username} onChange={setUsername} />
<FormInput label={t("Password")} type="password" value={password} onChange={setPassword} />
<FormInput label={t("Confirm Password")} type="password" value={confirmPassword} onChange={setConfirmPassword} />
<FormInput
label={t("Full Name")}
value={regName}
onChange={setRegName}
placeholder={t("Full Name", "Doly adyňyz")}
disabled={registerMutation.isPending}
/>
<PhoneInputField label={t("Phone")} value={regPhone} onChange={setRegPhone} disabled={registerMutation.isPending} />
<FormInput
label={t("Username")}
value={regUsername}
onChange={setRegUsername}
placeholder={t("Username", "Ulanyjy ady")}
disabled={registerMutation.isPending}
/>
<FormInput
label={t("Password")}
type="password"
value={regPassword}
onChange={setRegPassword}
disabled={registerMutation.isPending}
/>
<FormInput
label={t("Confirm Password")}
type="password"
value={regPasswordConfirm}
onChange={setRegPasswordConfirm}
disabled={registerMutation.isPending}
/>
<div className="flex flex-col gap-3 mt-4">
<Button onClick={handleOtherSubmit} className="h-11">
{t("Register")}
<Button onClick={handleRegister} disabled={registerMutation.isPending} className="h-11">
{registerMutation.isPending ? t("Loading") + "..." : t("Register")}
</Button>
<Button variant="outline" onClick={() => setView("login")} className="h-11">
<Button variant="outline" onClick={() => setView("login")} disabled={registerMutation.isPending} className="h-11">
{t("Go to login page")}
</Button>
</div>
<div className="text-center mt-8">
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
{t("Privacy Policy")}
</span>
</div>
<PrivacyLink />
</>
)}
{view === "reset-password" && (
{/* ── REGISTER VERIFY (step 2 – SMS OTP) ── */}
{view === "register-verify" && (
<>
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">
{t("Enter your username to continue")}
</h2>
<div className="flex flex-col items-center mb-6">
<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-3">
<MessageSquare size={22} className="text-primary" />
</div>
<h2 className="text-xl font-normal text-foreground text-center mb-1">{t("SMS Verification", "SMS Tassyklamasy")}</h2>
<p className="text-[13px] text-muted-foreground text-center">
{t("Enter the code sent to", "Iberilen kody giriziň")}{" "}
<span className="font-semibold text-foreground">+993 {regPhone}</span>
</p>
</div>
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
<FormInput label={t("Username")} value={username} onChange={setUsername} />
<FormInput
label={t("SMS Code", "SMS Kody")}
value={smsCode}
onChange={setSmsCode}
placeholder="______"
maxLength={6}
disabled={registerVerifyMutation.isPending}
onKeyDown={(e) => {
if (e.key === "Enter") handleVerify();
}}
/>
<div className="flex flex-col gap-3 mt-4">
<Button onClick={handleVerify} disabled={registerVerifyMutation.isPending} className="h-11">
{registerVerifyMutation.isPending ? t("Loading") + "..." : t("Verify", "Tassykla")}
</Button>
<Button
variant="outline"
onClick={() => setView("register")}
disabled={registerVerifyMutation.isPending}
className="h-11"
>
{t("Back", "Yza")}
</Button>
</div>
<PrivacyLink />
</>
)}
{/* ── FORGOT PASSWORD (step 1) ── */}
{view === "forgot-password" && (
<>
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">{t("Forgot your password?")}</h2>
<p className="text-[13px] text-muted-foreground text-center mb-5">
{t("Enter your username to receive a reset code", "Täzeden açar söz üçin ulanyjy adyňyzy giriziň")}
</p>
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
<FormInput
label={t("Username")}
value={forgotName}
onChange={setForgotName}
disabled={forgotPasswordMutation.isPending}
onKeyDown={(e) => {
if (e.key === "Enter") handleForgotPassword();
}}
/>
<div className="mt-4 flex flex-col gap-3">
<Button onClick={handleOtherSubmit} className="h-11">
{t("Submit")}
<Button onClick={handleForgotPassword} disabled={forgotPasswordMutation.isPending} className="h-11">
{forgotPasswordMutation.isPending ? t("Loading") + "..." : t("Submit")}
</Button>
<Button variant="outline" onClick={() => setView("login")} className="h-11">
<Button variant="outline" onClick={() => setView("login")} disabled={forgotPasswordMutation.isPending} className="h-11">
{t("Go to login page")}
</Button>
</div>
<div className="text-center mt-8">
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
{t("Privacy Policy")}
</span>
<PrivacyLink />
</>
)}
{/* ── FORGOT PASSWORD VERIFY (step 2) ── */}
{view === "forgot-password-verify" && (
<>
<div className="flex flex-col items-center mb-6">
<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-3">
<MessageSquare size={22} className="text-primary" />
</div>
<h2 className="text-xl font-normal text-foreground text-center mb-1">{t("Reset Password", "Açar sözi täzele")}</h2>
<p className="text-[13px] text-muted-foreground text-center">
{t("Enter the SMS code and your new password", "SMS kodyny we täze açar söziňizi giriziň")}
</p>
</div>
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
<FormInput
label={t("SMS Code", "SMS Kody")}
value={forgotCode}
onChange={setForgotCode}
placeholder="______"
maxLength={6}
disabled={forgotPasswordVerifyMutation.isPending}
/>
<FormInput
label={t("New Password", "Täze açar söz")}
type="password"
value={forgotPassword}
onChange={setForgotPassword}
disabled={forgotPasswordVerifyMutation.isPending}
/>
<FormInput
label={t("Confirm New Password", "Täze açar sözi tassykla")}
type="password"
value={forgotPasswordConfirm}
onChange={setForgotPasswordConfirm}
disabled={forgotPasswordVerifyMutation.isPending}
onKeyDown={(e) => {
if (e.key === "Enter") handleForgotPasswordVerify();
}}
/>
<div className="mt-4 flex flex-col gap-3">
<Button onClick={handleForgotPasswordVerify} disabled={forgotPasswordVerifyMutation.isPending} className="h-11">
{forgotPasswordVerifyMutation.isPending ? t("Loading") + "..." : t("Reset Password", "Açar sözi täzele")}
</Button>
<Button
variant="outline"
onClick={() => setView("forgot-password")}
disabled={forgotPasswordVerifyMutation.isPending}
className="h-11"
>
{t("Back", "Yza")}
</Button>
</div>
<PrivacyLink />
</>
)}
</div>
+6 -10
View File
@@ -27,14 +27,14 @@ export default function ClientsPage() {
const { data, isLoading } = useClients({
page,
perPage,
limit: perPage,
search: search || undefined,
isActive: isActiveFilter || undefined,
});
const clients = data?.data ?? [];
const totalPages = data?.meta.totalPages ?? 1;
const totalCount = data?.meta.totalCount ?? 0;
const clients = data?.users ?? [];
const totalCount = data?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(totalCount / perPage));
const columns: ColumnDef<Client>[] = [
{
@@ -71,14 +71,10 @@ export default function ClientsPage() {
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
},
{
accessorKey: "isActive",
accessorKey: "active",
header: t("clients.fields.isActive", "IŞJEŇ"),
cell: ({ row }) =>
row.original.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
),
row.original.active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />,
size: 80,
},
{
+124 -128
View File
@@ -1,71 +1,67 @@
import { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Pencil, Trash2, XCircle, CheckCircle2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { ConfirmDialog } from '@/components/confirmDialog'
import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from '@/components/viewPageComponents'
import { DataTable, type ColumnDef } from '@/components/dataTable'
import { DataTableToolbar } from '@/components/dataTableToolbar'
import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients'
import type { ClientRole, ClientBranch, ClientAuditLog } from '@/features/clients/api/clientsApi'
import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Pencil, Trash2, XCircle, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { ConfirmDialog } from "@/components/confirmDialog";
import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from "@/components/viewPageComponents";
import { DataTable, type ColumnDef } from "@/components/dataTable";
import { DataTableToolbar } from "@/components/dataTableToolbar";
import { useClient, useDeleteClient } from "@/features/clients/hooks/useClients";
import type { ClientRole, ClientBranch, ClientAuditLog } from "@/features/clients/api/clientsApi";
// ─── ActiveIndicator ──────────────────────────────────────────────────────────
function ActiveIndicator({ active }: { active: boolean }) {
return active ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
);
return active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />;
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function ClientDetailPage() {
const { id } = useParams<{ id: string }>()
const clientId = Number(id)
const { t } = useTranslation()
const navigate = useNavigate()
const deleteMutation = useDeleteClient()
const { id } = useParams<{ id: string }>();
const clientId = Number(id);
const { t } = useTranslation();
const navigate = useNavigate();
const deleteMutation = useDeleteClient();
const { data: client, isLoading } = useClient(clientId)
const { data: client, isLoading } = useClient(clientId);
const [deleteOpen, setDeleteOpen] = useState(false)
const [roleSearch, setRoleSearch] = useState('')
const [permSearch, setPermSearch] = useState('')
const [branchSearch, setBranchSearch] = useState('')
const [loanSearch, setLoanSearch] = useState('')
const [cardSearch, setCardSearch] = useState('')
const [deleteOpen, setDeleteOpen] = useState(false);
const [roleSearch, setRoleSearch] = useState("");
const [permSearch, setPermSearch] = useState("");
const [branchSearch, setBranchSearch] = useState("");
const [loanSearch, setLoanSearch] = useState("");
const [cardSearch, setCardSearch] = useState("");
// ── Role columns ──────────────────────────────────────────────────────────
const roleColumns: ColumnDef<ClientRole>[] = [
{
accessorKey: 'id',
header: t('common.id', 'ID'),
accessorKey: "id",
header: t("common.id", "ID"),
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 80,
},
{
accessorKey: 'code',
header: t('roles.fields.code', 'KOD'),
accessorKey: "code",
header: t("roles.fields.code", "KOD"),
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
},
{
accessorKey: 'name',
header: t('roles.fields.name', 'ADY'),
accessorKey: "name",
header: t("roles.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'guardName',
header: t('roles.fields.guardName', 'GUARD NAME'),
accessorKey: "guardName",
header: t("roles.fields.guardName", "GUARD NAME"),
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
cell: () => (
<div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
@@ -75,40 +71,40 @@ export default function ClientDetailPage() {
),
size: 60,
},
]
];
// ── Branch columns ────────────────────────────────────────────────────────
const branchColumns: ColumnDef<ClientBranch>[] = [
{
accessorKey: 'id',
header: t('common.id', 'ID'),
accessorKey: "id",
header: t("common.id", "ID"),
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
size: 60,
},
{
accessorKey: 'name',
header: t('branches.fields.name', 'ADY'),
accessorKey: "name",
header: t("branches.fields.name", "ADY"),
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
},
{
accessorKey: 'region',
header: t('branches.fields.region', 'WELAÝAT'),
accessorKey: "region",
header: t("branches.fields.region", "WELAÝAT"),
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
},
{
accessorKey: 'district',
header: t('branches.fields.district', 'ETRAP'),
accessorKey: "district",
header: t("branches.fields.district", "ETRAP"),
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
},
{
accessorKey: 'uniqueCode',
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'),
accessorKey: "uniqueCode",
header: t("branches.fields.uniqueCode", "UNIKAL BELGI"),
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
},
{
id: 'actions',
header: '',
id: "actions",
header: "",
cell: () => (
<div className="flex items-center gap-1 justify-end">
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
@@ -118,7 +114,7 @@ export default function ClientDetailPage() {
),
size: 60,
},
]
];
// ── Loading ───────────────────────────────────────────────────────────────
@@ -137,46 +133,44 @@ export default function ClientDetailPage() {
))}
</div>
</div>
)
);
}
if (!client) return null
if (!client) return null;
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
id: String(log.id),
id: String(log.id),
action: log.actionName,
by: log.performedBy,
by: log.performedBy,
target: log.target,
status: log.status,
date: log.createdAt,
}))
date: log.createdAt,
}));
const filteredRoles = (client.roles ?? []).filter((r) =>
r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
)
const filteredBranches = (client.branches ?? []).filter((b) =>
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
)
const filteredRoles = (client.roles ?? []).filter(
(r) => r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
);
const filteredBranches = (client.branches ?? []).filter((b) => b.name.toLowerCase().includes(branchSearch.toLowerCase()));
return (
<div className=" flex flex-col gap-6">
{/* ── Page header ──────────────────────────────────────────────────── */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-semibold text-foreground">
{t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name}
{t("clients.detailTitle", "Müşderi giňişleýin")}: {client.name}
</h1>
<div className="flex items-center gap-2">
<Button
size="icon" variant="ghost"
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => setDeleteOpen(true)}
>
<Trash2 size={15} />
</Button>
<Button
size="icon" variant="ghost"
size="icon"
variant="ghost"
className="h-8 w-8 text-muted-foreground hover:text-foreground"
onClick={() => navigate(`/clients/${clientId}/edit`)}
>
@@ -187,114 +181,117 @@ export default function ClientDetailPage() {
{/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
<BentoGrid cols={2}>
<BentoCard title={t('clients.sections.basic', 'Esasy maglumatlar')}>
<InfoRow label={t('common.id', 'ID')} value={client.id} />
<InfoRow
label={t('clients.fields.username', 'Ulanyjy ady')}
value={client.username}
/>
<InfoRow
label={t('clients.fields.name', 'Ady')}
value={client.name}
/>
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
<ActiveIndicator active={client.isActive} />
<BentoCard title={t("clients.sections.basic", "Esasy maglumatlar")}>
<InfoRow label={t("common.id", "ID")} value={client.id} />
<InfoRow label={t("clients.fields.username", "Ulanyjy ady")} value={client.username} />
<InfoRow label={t("clients.fields.name", "Ady")} value={client.name} />
<InfoRow label={t("clients.fields.isActive", "Işjeň")}>
<ActiveIndicator active={client.active} />
</InfoRow>
</BentoCard>
<BentoCard title={t('clients.sections.contact', 'Kontakt')}>
<InfoRow
label={t('clients.fields.phone', 'Telefon')}
value={client.phone ?? '—'}
/>
<InfoRow
label={t('clients.fields.email', 'E-poçta')}
value={client.email ?? '—'}
/>
<BentoCard title={t("clients.sections.contact", "Kontakt")}>
<InfoRow label={t("clients.fields.phone", "Telefon")} value={client.phone ?? "—"} />
<InfoRow label={t("clients.fields.email", "E-poçta")} value={client.email ?? "—"} />
</BentoCard>
</BentoGrid>
{/* ── Rollar ───────────────────────────────────────────────────────── */}
<CollapsibleSection title={t('clients.sections.roles', 'Rollar')}>
<CollapsibleSection title={t("clients.sections.roles", "Rollar")}>
<DataTableToolbar
searchValue={roleSearch}
onSearchChange={setRoleSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}}
actionLabel={t('clients.addRole', 'Rol birikdiriň')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("clients.addRole", "Rol birikdiriň")}
onAction={() => {}}
/>
{filteredRoles.length > 0 ? (
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
) : (
<EmptyState label={t('clients.noRoles', 'Berlen kriterýalara Rol gabat gelmedi.')} />
<EmptyState label={t("clients.noRoles", "Berlen kriterýalara Rol gabat gelmedi.")} />
)}
</CollapsibleSection>
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
<CollapsibleSection title={t('clients.sections.permissions', 'Rugsatlar')}>
<CollapsibleSection title={t("clients.sections.permissions", "Rugsatlar")}>
<DataTableToolbar
searchValue={permSearch}
onSearchChange={setPermSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}}
actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("clients.addPermission", "Rugsat birikdiriň")}
onAction={() => {}}
/>
{(client.permissions ?? []).length === 0 && (
<EmptyState label={t('clients.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} />
<EmptyState label={t("clients.noPermissions", "Berlen kriterýalara Rugsat gabat gelmedi.")} />
)}
</CollapsibleSection>
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
<CollapsibleSection title={t('clients.sections.branches', 'Şahamçalar')}>
<CollapsibleSection title={t("clients.sections.branches", "Şahamçalar")}>
<DataTableToolbar
searchValue={branchSearch}
onSearchChange={setBranchSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}}
actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("clients.addBranch", "Şahamça birikdiriň")}
onAction={() => {}}
/>
{filteredBranches.length > 0 ? (
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
) : (
<EmptyState label={t('clients.noBranches', 'Berlen kriterýalara Şahamça gabat gelmedi.')} />
<EmptyState label={t("clients.noBranches", "Berlen kriterýalara Şahamça gabat gelmedi.")} />
)}
</CollapsibleSection>
{/* ── Karz sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection title={t('clients.sections.loanOrders', 'Karz sargyt')}>
<CollapsibleSection title={t("clients.sections.loanOrders", "Karz sargyt")}>
<DataTableToolbar
searchValue={loanSearch}
onSearchChange={setLoanSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}}
actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("clients.addLoanOrder", "Karz sargyt dörediň")}
onAction={() => {}}
/>
{(client.loanOrders ?? []).length === 0 && (
<EmptyState label={t('clients.noLoanOrders', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} />
<EmptyState label={t("clients.noLoanOrders", "Berlen kriterýalara Karz sargyt gabat gelmedi.")} />
)}
</CollapsibleSection>
{/* ── Kart sargyt ──────────────────────────────────────────────────── */}
<CollapsibleSection title={t('clients.sections.cardOrders', 'Kart sargyt')}>
<CollapsibleSection title={t("clients.sections.cardOrders", "Kart sargyt")}>
<DataTableToolbar
searchValue={cardSearch}
onSearchChange={setCardSearch}
searchPlaceholder={t('common.search', 'Gözlemek')}
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
columnOrder={[]} onColumnOrderChange={() => {}}
actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')}
searchPlaceholder={t("common.search", "Gözlemek")}
columns={[]}
columnVisibility={{}}
onColumnVisibilityChange={() => {}}
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("clients.addCardOrder", "Kart sargyt dörediň")}
onAction={() => {}}
/>
{(client.cardOrders ?? []).length === 0 && (
<EmptyState label={t('clients.noCardOrders', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} />
<EmptyState label={t("clients.noCardOrders", "Berlen kriterýalara Kart sargyt gabat gelmedi.")} />
)}
</CollapsibleSection>
@@ -304,13 +301,12 @@ export default function ClientDetailPage() {
<ConfirmDialog
open={deleteOpen}
onOpenChange={setDeleteOpen}
title={t('clients.deleteTitle', 'Müşderini pozmak')}
description={t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi?', { name: client.name })}
confirmLabel={t('common.delete', 'Poz')}
onConfirm={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}
title={t("clients.deleteTitle", "Müşderini pozmak")}
description={t("clients.deleteConfirm", "{{name}} müşderisini pozmak isleýärsiňizmi?", { name: client.name })}
confirmLabel={t("common.delete", "Poz")}
onConfirm={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate("/clients") })}
isLoading={deleteMutation.isPending}
/>
</div>
)
}
);
}
+6 -10
View File
@@ -32,14 +32,14 @@ export default function OperatorsPage() {
// ── Query ────────────────────────────────────────────────────────────────────
const { data, isLoading } = useOperators({
page,
perPage,
limit: perPage,
search: search || undefined,
isActive: isActiveFilter || undefined,
});
const operators = data?.data ?? [];
const totalPages = data?.meta.totalPages ?? 1;
const totalCount = data?.meta.totalCount ?? 0;
const operators = data?.users ?? [];
const totalCount = data?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(totalCount / perPage));
// ── Columns ──────────────────────────────────────────────────────────────────
const columns: ColumnDef<Operator>[] = [
@@ -77,14 +77,10 @@ export default function OperatorsPage() {
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
},
{
accessorKey: "isActive",
accessorKey: "active",
header: t("operators.fields.isActive", "IŞJEŇ"),
cell: ({ row }) =>
row.original.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
),
row.original.active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />,
size: 80,
},
{
+2 -4
View File
@@ -236,7 +236,7 @@ export default function OperatorDetailPage() {
<InfoRow label={t("operators.fields.username", "Ulanyjy ady")} value={operator.username} />
<InfoRow label={t("operators.fields.name", "Ady")} value={operator.name} />
<InfoRow label={t("operators.fields.isActive", "Işjeň")}>
<ActiveIndicator active={operator.isActive} />
<ActiveIndicator active={operator.active} />
</InfoRow>
</BentoCard>
@@ -258,9 +258,7 @@ export default function OperatorDetailPage() {
columnOrder={[]}
onColumnOrderChange={() => {}}
actionLabel={t("operators.addRole", "Rol birikdiriň")}
onAction={() => {
/* modal aç ya da navigate */
}}
onAction={() => {}}
/>
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
</CollapsibleSection>