started connect with api
This commit is contained in:
4
.env
4
.env
@@ -1,2 +1,4 @@
|
||||
VITE_API_BASE_URL=https://test.webulgam.com/online-backend/api/admin
|
||||
VITE_API_URL=/api
|
||||
VITE_ENABLE_MOCKS=true
|
||||
VITE_ENABLE_MOCKS=false
|
||||
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -15,6 +15,7 @@ dist-ssr
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
!.env.example
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
|
||||
4
env.example
Normal file
4
env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
VITE_API_BASE_URL=https://test.webulgam.com/online-backend/api/admin
|
||||
VITE_API_URL=/api
|
||||
VITE_ENABLE_MOCKS=false
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import axios from "axios";
|
||||
import type { ApiSuccessResponse } from "@/lib/api/client";
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
id?: string | number;
|
||||
name: string;
|
||||
email: string;
|
||||
role: "admin" | "manager" | "viewer";
|
||||
email?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
refreshTokenValue: string | null;
|
||||
user: AuthUser | null;
|
||||
isAuthenticated: boolean;
|
||||
setAuth: (token: string, user: AuthUser) => void;
|
||||
setAuth: (token: string, refreshTokenValue: string | null, user: AuthUser | null) => void;
|
||||
setUser: (user: AuthUser) => void;
|
||||
clearAuth: () => void;
|
||||
logout: () => void;
|
||||
refreshToken: () => Promise<string>;
|
||||
@@ -24,32 +30,51 @@ export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: null,
|
||||
refreshTokenValue: null,
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
|
||||
setAuth: (token, user) => set({ token, user, isAuthenticated: true }),
|
||||
setAuth: (token, refreshTokenValue, user) =>
|
||||
set({
|
||||
token,
|
||||
refreshTokenValue: refreshTokenValue || get().refreshTokenValue,
|
||||
user,
|
||||
isAuthenticated: true,
|
||||
}),
|
||||
|
||||
clearAuth: () => set({ token: null, user: null, isAuthenticated: false }),
|
||||
setUser: (user) => set({ user }),
|
||||
|
||||
clearAuth: () => set({ token: null, refreshTokenValue: null, user: null, isAuthenticated: false }),
|
||||
|
||||
logout: () => {
|
||||
get().clearAuth();
|
||||
},
|
||||
|
||||
refreshToken: async () => {
|
||||
try {
|
||||
const response = await axios.post<{ token: string }>(
|
||||
`${import.meta.env.VITE_API_BASE_URL}/auth/refresh`,
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${get().token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const currentRefreshToken = get().refreshTokenValue;
|
||||
if (!currentRefreshToken) {
|
||||
get().clearAuth();
|
||||
throw new Error("No refresh token available");
|
||||
}
|
||||
|
||||
const newToken = response.data.token;
|
||||
set((state) => ({ ...state, token: newToken }));
|
||||
return newToken;
|
||||
try {
|
||||
const baseURL = import.meta.env.VITE_API_BASE_URL || "/api/admin";
|
||||
const response = await axios.post<
|
||||
ApiSuccessResponse<{
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}>
|
||||
>(`${baseURL}/token`, { refreshToken: currentRefreshToken });
|
||||
|
||||
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new Error("Token refresh response missing accessToken");
|
||||
}
|
||||
|
||||
set({ token: accessToken, refreshTokenValue: newRefreshToken });
|
||||
|
||||
return accessToken;
|
||||
} catch (error) {
|
||||
get().clearAuth();
|
||||
throw error;
|
||||
|
||||
@@ -19,7 +19,8 @@ export interface ColumnMeta {
|
||||
export interface FilterField {
|
||||
id: string;
|
||||
label: string;
|
||||
options: { value: string; label: string }[];
|
||||
type?: "select" | "text";
|
||||
options?: { value: string; label: string }[];
|
||||
}
|
||||
|
||||
export interface ActiveFilter {
|
||||
@@ -246,37 +247,65 @@ function FilterDropdown({
|
||||
<label className="block text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{field.label}</label>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Select value={current || "__all__"} onValueChange={(val) => onFilterChange(field.id, val === "__all__" ? "" : val)}>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
"h-8 flex-1 text-sm gap-1.5 transition-colors",
|
||||
isFieldActive ? "border-primary text-primary [&>svg:last-child]:text-primary" : "text-muted-foreground",
|
||||
{field.type === "text" ? (
|
||||
<>
|
||||
<input
|
||||
type="text"
|
||||
value={current}
|
||||
onChange={(e) => onFilterChange(field.id, e.target.value)}
|
||||
placeholder="—"
|
||||
className={cn(
|
||||
"h-8 flex-1 rounded-md border border-input bg-background px-2.5 text-sm text-foreground",
|
||||
"placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-ring",
|
||||
"transition-colors",
|
||||
isFieldActive && "border-primary",
|
||||
)}
|
||||
/>
|
||||
{isFieldActive && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onFilterChange(field.id, "")}
|
||||
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
||||
>
|
||||
<X size={11} />
|
||||
</button>
|
||||
)}
|
||||
>
|
||||
<span className="flex-1 text-left truncate">
|
||||
{isFieldActive ? field.options.find((o) => o.value === current)?.label : "—"}
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" sideOffset={4} className="p-1">
|
||||
<SelectItem value="__all__">
|
||||
<span className="text-muted-foreground">— Ählisi</span>
|
||||
</SelectItem>
|
||||
{field.options.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Select value={current || "__all__"} onValueChange={(val) => onFilterChange(field.id, val === "__all__" ? "" : val)}>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
"h-8 flex-1 text-sm gap-1.5 transition-colors",
|
||||
isFieldActive ? "border-primary text-primary [&>svg:last-child]:text-primary" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<span className="flex-1 text-left truncate">
|
||||
{isFieldActive ? (field.options ?? []).find((o) => o.value === current)?.label : "—"}
|
||||
</span>
|
||||
</SelectTrigger>
|
||||
<SelectContent position="popper" sideOffset={4} className="p-1">
|
||||
<SelectItem value="__all__">
|
||||
<span className="text-muted-foreground">— Ählisi</span>
|
||||
</SelectItem>
|
||||
{(field.options ?? []).map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{isFieldActive && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onFilterChange(field.id, "")}
|
||||
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
||||
>
|
||||
<X size={11} />
|
||||
</button>
|
||||
{isFieldActive && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onFilterChange(field.id, "")}
|
||||
className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors shrink-0"
|
||||
>
|
||||
<X size={11} />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from "react";
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
|
||||
import { Check, ChevronsUpDown, Search, X, Eye, EyeOff, Upload, Hash } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn, cleanPhoneNumber, formatFromApiDate } from "@/lib/utils";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -175,6 +175,9 @@ function PhoneInput({
|
||||
className,
|
||||
phonePrefix = "+993",
|
||||
}: FormInputProps) {
|
||||
// Gelen veride ülke kodu (+993) veya boşluklar olsa bile temiz 8 haneyi elde et
|
||||
const cleanedDigits = cleanPhoneNumber(value);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const digits = e.target.value.replace(/\D/g, "").slice(0, 8);
|
||||
|
||||
@@ -185,6 +188,8 @@ function PhoneInput({
|
||||
}
|
||||
};
|
||||
|
||||
const formattedDisplayValue = cleanedDigits.length <= 2 ? cleanedDigits : `${cleanedDigits.slice(0, 2)} ${cleanedDigits.slice(2)}`;
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<FieldLabel label={label} required={required} />
|
||||
@@ -203,7 +208,7 @@ function PhoneInput({
|
||||
</div>
|
||||
<input
|
||||
type="tel"
|
||||
value={value}
|
||||
value={formattedDisplayValue}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
@@ -221,8 +226,9 @@ function PhoneInput({
|
||||
function DateInput({ value = "", onChange, error, disabled, required, label, className, placeholder = "Sene saýlaň" }: FormInputProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// value is stored as 'yyyy-MM-dd' string
|
||||
const parsed = value ? parse(value, "yyyy-MM-dd", new Date()) : undefined;
|
||||
// value backend'den 'yyyy-MM-dd' veya 'yyyy-MM-ddTHH:mm:ssZ' gelebilir
|
||||
const dateStr = formatFromApiDate(value);
|
||||
const parsed = dateStr ? parse(dateStr, "yyyy-MM-dd", new Date()) : undefined;
|
||||
const selected = parsed && isValid(parsed) ? parsed : undefined;
|
||||
|
||||
const handleSelect = (day: Date | undefined) => {
|
||||
|
||||
225
src/components/infiniteSelect.tsx
Normal file
225
src/components/infiniteSelect.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
|
||||
import { Check, ChevronsUpDown, Search, X, Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface InfiniteSelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface InfiniteSelectProps {
|
||||
value?: string;
|
||||
onChange?: (value: string) => void;
|
||||
options?: InfiniteSelectOption[];
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
label?: string;
|
||||
required?: boolean;
|
||||
error?: string;
|
||||
disabled?: boolean;
|
||||
/** True while the first page is being fetched. */
|
||||
loading?: boolean;
|
||||
/** True while the next page is being fetched. */
|
||||
isLoadingMore?: boolean;
|
||||
/** Whether more pages are available to load. */
|
||||
hasNextPage?: boolean;
|
||||
/** Called when the user scrolls to the bottom of the list. */
|
||||
onLoadMore?: () => void;
|
||||
/** Controlled search text; drives server-side search + page reset. */
|
||||
searchValue?: string;
|
||||
onSearchChange?: (value: string) => void;
|
||||
}
|
||||
|
||||
// ─── Collapsible aliases ──────────────────────────────────────────────────────
|
||||
|
||||
const Collapsible = CollapsiblePrimitive.Root;
|
||||
const CollapsibleTrigger = CollapsiblePrimitive.Trigger;
|
||||
const CollapsibleContent = CollapsiblePrimitive.Content;
|
||||
|
||||
/**
|
||||
* Searchable select with infinite scroll.
|
||||
*
|
||||
* The consumer owns the data fetching (e.g. TanStack Query `useInfiniteQuery`):
|
||||
* it passes the flattened options, and `hasNextPage`/`onLoadMore` drive loading
|
||||
* additional pages when the list bottom is reached.
|
||||
*/
|
||||
export function InfiniteSelect({
|
||||
value = "",
|
||||
onChange,
|
||||
options = [],
|
||||
placeholder = "Saýlamak üçin basyň",
|
||||
searchPlaceholder = "Gözle...",
|
||||
label,
|
||||
required,
|
||||
error,
|
||||
disabled,
|
||||
loading = false,
|
||||
isLoadingMore = false,
|
||||
hasNextPage = false,
|
||||
onLoadMore,
|
||||
searchValue,
|
||||
onSearchChange,
|
||||
}: InfiniteSelectProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const sentinelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const selected = options.find((o) => o.value === value);
|
||||
|
||||
const handleSelect = (val: string) => {
|
||||
onChange?.(val);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleClear = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onChange?.("");
|
||||
};
|
||||
|
||||
// ── Infinite scroll: load more when the sentinel becomes visible ──
|
||||
useEffect(() => {
|
||||
if (!open || !sentinelRef.current || !hasNextPage || isLoadingMore) return;
|
||||
const el = sentinelRef.current;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0]?.isIntersecting && hasNextPage && !isLoadingMore) {
|
||||
onLoadMore?.();
|
||||
}
|
||||
},
|
||||
{ rootMargin: "120px" },
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [open, hasNextPage, isLoadingMore, onLoadMore]);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{label && (
|
||||
<label className="block text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-1.5 select-none">
|
||||
{label}
|
||||
{required && <span className="text-destructive ml-0.5">*</span>}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<Collapsible
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!disabled) setOpen(next);
|
||||
}}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"flex h-8 w-full items-center justify-between rounded-md border bg-background px-3 py-2",
|
||||
"text-sm ring-offset-background transition-colors duration-150",
|
||||
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0",
|
||||
"disabled:cursor-not-allowed disabled:opacity-50",
|
||||
error ? "border-destructive" : "border-input",
|
||||
open && !error && "ring-2 ring-ring ring-offset-0 border-transparent",
|
||||
)}
|
||||
>
|
||||
<span className={cn("truncate text-left", !selected && "text-muted-foreground/60")}>
|
||||
{selected ? selected.label : placeholder}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center gap-1 shrink-0 ml-2">
|
||||
{selected && !disabled && (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={-1}
|
||||
onMouseDown={handleClear}
|
||||
className="p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<X size={12} />
|
||||
</span>
|
||||
)}
|
||||
<ChevronsUpDown
|
||||
size={14}
|
||||
className={cn("text-muted-foreground transition-transform duration-200 shrink-0", open && "text-foreground")}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="mt-1 rounded-md border border-border bg-card shadow-lg overflow-hidden">
|
||||
{onSearchChange && (
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/20">
|
||||
<Search size={13} className="text-muted-foreground shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchValue ?? ""}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
placeholder={searchPlaceholder}
|
||||
className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none"
|
||||
/>
|
||||
{searchValue && (
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
onMouseDown={() => onSearchChange?.("")}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-h-60 overflow-y-auto py-1">
|
||||
{loading && options.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-muted-foreground text-center flex items-center justify-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" /> Loading...
|
||||
</p>
|
||||
) : options.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-muted-foreground text-center">Netije tapylmady</p>
|
||||
) : (
|
||||
options.map((opt) => {
|
||||
const isSelected = opt.value === value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleSelect(opt.value);
|
||||
}}
|
||||
className={cn(
|
||||
"flex items-center justify-between w-full text-left px-3 py-2 text-sm transition-colors",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
isSelected && "text-primary font-medium bg-primary/10",
|
||||
)}
|
||||
>
|
||||
<span>{opt.label}</span>
|
||||
{isSelected && <Check size={13} className="text-primary shrink-0" />}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
{hasNextPage && (
|
||||
<div ref={sentinelRef} className="px-3 py-2 text-xs text-muted-foreground text-center">
|
||||
{isLoadingMore && (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Loader2 size={12} className="animate-spin" /> Loading...
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{error && (
|
||||
<p className="mt-1.5 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -91,14 +91,14 @@ export function InfoRow({ label, value, children, isLink, href }: InfoRowProps)
|
||||
|
||||
export interface MultiLangRowProps {
|
||||
label: string;
|
||||
value?: { tk?: string; ru?: string; en?: string } | null;
|
||||
value?: { tm?: string; tk?: string; ru?: string; en?: string } | null;
|
||||
}
|
||||
|
||||
export function MultiLangRow({ label, value }: MultiLangRowProps) {
|
||||
if (!value) return <InfoRow label={label} value="—" />;
|
||||
|
||||
const langs = [
|
||||
{ code: "TK", val: value.tk },
|
||||
{ code: "TK", val: value.tm ?? value.tk },
|
||||
{ code: "RU", val: value.ru },
|
||||
{ code: "EN", val: value.en },
|
||||
];
|
||||
|
||||
@@ -1,198 +1,104 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface User {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string | null
|
||||
isActive: boolean
|
||||
phoneVerified: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
export interface SocialMedia {
|
||||
facebook: string;
|
||||
instagram: string;
|
||||
telegram: string;
|
||||
}
|
||||
|
||||
export interface UserListItem {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string | null
|
||||
isActive: boolean
|
||||
export interface User {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
avatar: string;
|
||||
socialMedia: SocialMedia;
|
||||
lightMode: number;
|
||||
role: string;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UsersListResponse {
|
||||
data: UserListItem[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
count: number;
|
||||
users: User[];
|
||||
}
|
||||
|
||||
export interface UsersListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
isActive?: string;
|
||||
}
|
||||
|
||||
export interface CreateUserPayload {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email?: string
|
||||
password: string
|
||||
phoneVerified: boolean
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
avatar: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
lightMode: number;
|
||||
name: string;
|
||||
password: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
socialMedia: SocialMedia;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserPayload {
|
||||
username?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
phoneVerified?: boolean
|
||||
isActive?: boolean
|
||||
active?: boolean;
|
||||
avatar?: string;
|
||||
email?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
lightMode?: number;
|
||||
name?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
socialMedia?: SocialMedia;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_USERS: User[] = Array.from({ length: 50 }, (_, i) => {
|
||||
const id = 5970 - i
|
||||
const names = [
|
||||
'Orazowa Nurtuwak Täşliyewna',
|
||||
'Hallyýewa Aýna Gurbanmyradowna',
|
||||
'Sopýýewa Maral Agamyradowna',
|
||||
'Babamurat Baýnazarow Şanazarowič',
|
||||
'Narmet Narmet',
|
||||
'Sheker Durdyyewa',
|
||||
'kamalowyusup',
|
||||
'Mahmudowberdimet',
|
||||
'allanazarowasayyara',
|
||||
'dadayewjepbar',
|
||||
]
|
||||
const usernames = [
|
||||
'Nurtuwak_1970', 'Ayna_1989', 'Maral_1974', 'Babamurat_0002', 'Narmet',
|
||||
'8319_ShekerDurdyyewa', 'kamalowyusup', 'Mahmudowberdimet',
|
||||
'allanazarowasayyara', 'dadayewjepbar',
|
||||
]
|
||||
const idx = i % names.length
|
||||
return {
|
||||
id,
|
||||
username: i < usernames.length ? usernames[idx] : `user_${id}`,
|
||||
name: names[idx],
|
||||
phone: `+(993)-6${Math.floor(Math.random() * 9 + 1)}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}`,
|
||||
email: i % 4 === 0 ? `user${id}@tbbank.gov.tm` : null,
|
||||
isActive: Math.random() > 0.1,
|
||||
phoneVerified: Math.random() > 0.3,
|
||||
createdAt: new Date(Date.now() - Math.random() * 1e10).toISOString(),
|
||||
updatedAt: new Date(Date.now() - Math.random() * 1e9).toISOString(),
|
||||
}
|
||||
})
|
||||
|
||||
// ─── Mock delay helper ────────────────────────────────────────────────────────
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const usersApi = {
|
||||
/**
|
||||
* GET /users
|
||||
*/
|
||||
getUsers: async (params: UsersListParams = {}): Promise<UsersListResponse> => {
|
||||
await delay()
|
||||
// Uncomment for real API:
|
||||
// const res = await apiClient.get<UsersListResponse>('/users', { params })
|
||||
// return res.data
|
||||
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = [...MOCK_USERS]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(u) =>
|
||||
u.username.toLowerCase().includes(q) ||
|
||||
u.name.toLowerCase().includes(q) ||
|
||||
u.phone.includes(q),
|
||||
)
|
||||
}
|
||||
|
||||
if (isActive !== undefined && isActive !== '') {
|
||||
const active = isActive === 'true'
|
||||
filtered = filtered.filter((u) => u.isActive === active)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage).map(({ id, username, name, phone, email, isActive }) => ({
|
||||
id, username, name, phone, email, isActive,
|
||||
}))
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
/** GET /users — backend filters by `username` */
|
||||
getUsers: async (params: UsersListParams = {}, signal?: AbortSignal): Promise<UsersListResponse> => {
|
||||
const { page, limit, search, isActive } = params;
|
||||
const { data } = await apiClient.get<UsersListResponse>("/users", {
|
||||
params: { page, limit, username: search, isActive },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* GET /users/:id
|
||||
*/
|
||||
/** GET /users/:id */
|
||||
getUserById: async (id: number): Promise<User> => {
|
||||
await delay()
|
||||
// const res = await apiClient.get<User>(`/users/${id}`)
|
||||
// return res.data
|
||||
|
||||
const user = MOCK_USERS.find((u) => u.id === id)
|
||||
if (!user) throw new Error(`User ${id} not found`)
|
||||
return user
|
||||
const { data } = await apiClient.get<User>(`/users/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* POST /users
|
||||
*/
|
||||
/** POST /users */
|
||||
createUser: async (payload: CreateUserPayload): Promise<User> => {
|
||||
await delay(800)
|
||||
// const res = await apiClient.post<User>('/users', payload)
|
||||
// return res.data
|
||||
|
||||
const newUser: User = {
|
||||
id: Math.max(...MOCK_USERS.map((u) => u.id)) + 1,
|
||||
username: payload.username,
|
||||
name: payload.name,
|
||||
phone: payload.phone,
|
||||
email: payload.email ?? null,
|
||||
isActive: payload.isActive,
|
||||
phoneVerified: payload.phoneVerified,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
MOCK_USERS.unshift(newUser)
|
||||
return newUser
|
||||
const { data } = await apiClient.post<User>("/users", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* PUT /users/:id
|
||||
*/
|
||||
/** PUT /users/:id */
|
||||
updateUser: async (id: number, payload: UpdateUserPayload): Promise<User> => {
|
||||
await delay(800)
|
||||
// const res = await apiClient.put<User>(`/users/${id}`, payload)
|
||||
// return res.data
|
||||
|
||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
||||
if (idx === -1) throw new Error(`User ${id} not found`)
|
||||
MOCK_USERS[idx] = { ...MOCK_USERS[idx], ...payload, updatedAt: new Date().toISOString() }
|
||||
return MOCK_USERS[idx]
|
||||
const { data } = await apiClient.put<User>(`/users/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* DELETE /users/:id
|
||||
*/
|
||||
/** DELETE /users/:id */
|
||||
deleteUser: async (id: number): Promise<void> => {
|
||||
await delay(600)
|
||||
// await apiClient.delete(`/users/${id}`)
|
||||
|
||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
||||
if (idx !== -1) MOCK_USERS.splice(idx, 1)
|
||||
await apiClient.delete(`/users/${id}`);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import type { User } from "../api/allUsersApi";
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/allUser.schema";
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/allUser.schema";
|
||||
import type { AllUserFormData } from "../schemas/allUser.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -50,6 +52,35 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
|
||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
|
||||
|
||||
// ── Role infinite-scroll select ──
|
||||
const [roleSearch, setRoleSearch] = useState("");
|
||||
const roleQuery = useInfiniteRoles(roleSearch);
|
||||
|
||||
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p.roles)
|
||||
.map((r) => ({ value: r.name, label: r.name }));
|
||||
|
||||
// Ensure the currently-selected role is present (edit mode), even if it
|
||||
// lives beyond the pages loaded so far.
|
||||
if (initialData) {
|
||||
const current = initialData.role;
|
||||
if (current && !opts.some((o) => o.value === current)) {
|
||||
opts.unshift({ value: current, label: current });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
options: opts,
|
||||
loading: roleQuery.isLoading,
|
||||
isLoadingMore: roleQuery.isFetchingNextPage,
|
||||
hasNextPage: !!roleQuery.hasNextPage,
|
||||
onLoadMore: () => roleQuery.fetchNextPage(),
|
||||
searchValue: roleSearch,
|
||||
onSearchChange: setRoleSearch,
|
||||
};
|
||||
}, [roleQuery, roleSearch, initialData]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -65,11 +96,18 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ""),
|
||||
firstName: initialData.firstName ?? "",
|
||||
lastName: initialData.lastName ?? "",
|
||||
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||
email: initialData.email ?? "",
|
||||
avatar: initialData.avatar ?? "",
|
||||
role: initialData.role ?? "",
|
||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||
lightMode: !!initialData.lightMode,
|
||||
password: "",
|
||||
phoneVerified: initialData.phoneVerified,
|
||||
isActive: initialData.isActive,
|
||||
active: !!initialData.active,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
@@ -99,17 +137,11 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
if (mode === "create") {
|
||||
const payload = buildPayload(data);
|
||||
await createUser.mutateAsync(payload);
|
||||
navigate("/users");
|
||||
navigate("/all-users");
|
||||
} else {
|
||||
await updateUser.mutateAsync({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
});
|
||||
navigate(`/users/${initialData!.id}`);
|
||||
const payload = buildUpdatePayload(data);
|
||||
await updateUser.mutateAsync(payload);
|
||||
navigate(`/all-users/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -145,6 +177,28 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.firstName", "Ady (at)")}
|
||||
value={form.firstName}
|
||||
onChange={(v) => setField("firstName", v)}
|
||||
placeholder={t("users.fields.firstName", "Ady (at)")}
|
||||
error={errors.firstName}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.lastName", "Familiýasy")}
|
||||
value={form.lastName}
|
||||
onChange={(v) => setField("lastName", v)}
|
||||
placeholder={t("users.fields.lastName", "Familiýasy")}
|
||||
error={errors.lastName}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
@@ -170,6 +224,29 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<InfiniteSelect
|
||||
label={t("users.fields.role", "Roly")}
|
||||
value={form.role}
|
||||
onChange={(v) => setField("role", v)}
|
||||
placeholder={t("users.fields.role", "Roly")}
|
||||
error={errors.role}
|
||||
disabled={isPending}
|
||||
required
|
||||
{...roleSelect}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.avatar", "Awatar URL")}
|
||||
value={form.avatar}
|
||||
onChange={(v) => setField("avatar", v)}
|
||||
placeholder="https://..."
|
||||
error={errors.avatar}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
{mode === "create" && (
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
@@ -187,18 +264,46 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
)}
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.phoneVerified", "Telefon tassyklanan")}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.phoneVerifiedHint", "SMS arkaly tassyklandy")}</p>
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="phoneVerified"
|
||||
checked={form.phoneVerified}
|
||||
onCheckedChange={(v) => setField("phoneVerified", !!v)}
|
||||
<div className="flex flex-col gap-3">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.facebook", "Facebook")}
|
||||
value={form.socialFacebook}
|
||||
onChange={(v) => setField("socialFacebook", v)}
|
||||
placeholder="facebook.com/..."
|
||||
error={errors.socialFacebook}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<Label htmlFor="phoneVerified" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.phoneVerified ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.instagram", "Instagram")}
|
||||
value={form.socialInstagram}
|
||||
onChange={(v) => setField("socialInstagram", v)}
|
||||
placeholder="instagram.com/..."
|
||||
error={errors.socialInstagram}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.telegram", "Telegram")}
|
||||
value={form.socialTelegram}
|
||||
onChange={(v) => setField("socialTelegram", v)}
|
||||
placeholder="t.me/..."
|
||||
error={errors.socialTelegram}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox id="lightMode" checked={form.lightMode} onCheckedChange={(v) => setField("lightMode", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="lightMode" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.lightMode ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
</Label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
@@ -208,9 +313,9 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(v) => setField("isActive", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.isActive ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
</Label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
usersApi,
|
||||
type CreateUserPayload,
|
||||
type UpdateUserPayload,
|
||||
type UsersListParams,
|
||||
} from '../api/allUsersApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { usersApi, type CreateUserPayload, type UpdateUserPayload, type UsersListParams } from "../api/allUsersApi";
|
||||
|
||||
export const userKeys = {
|
||||
all: ['users'] as const,
|
||||
lists: () => [...userKeys.all, 'list'] as const,
|
||||
all: ["users"] as const,
|
||||
lists: () => [...userKeys.all, "list"] as const,
|
||||
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
|
||||
details: () => [...userKeys.all, 'detail'] as const,
|
||||
details: () => [...userKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...userKeys.details(), id] as const,
|
||||
}
|
||||
};
|
||||
|
||||
export function useUsers(params: UsersListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: UsersListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: userKeys.list(params),
|
||||
queryFn: () => usersApi.getUsers(params),
|
||||
queryKey: userKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => usersApi.getUsers(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUser(id: number) {
|
||||
@@ -29,45 +28,45 @@ export function useUser(id: number) {
|
||||
queryKey: userKeys.detail(id),
|
||||
queryFn: () => usersApi.getUserById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateUser() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateUserPayload) => usersApi.createUser(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
toast.success(t('users.toast.createSuccess', 'Ulanyjy üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
toast.success(t("users.toast.createSuccess", "Ulanyjy üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUser(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateUserPayload) => usersApi.updateUser(id, payload),
|
||||
onSuccess: (updatedUser) => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
queryClient.setQueryData(userKeys.detail(id), updatedUser)
|
||||
toast.success(t('users.toast.updateSuccess', 'Ulanyjy üstünlikli täzelendi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
queryClient.setQueryData(userKeys.detail(id), updatedUser);
|
||||
toast.success(t("users.toast.updateSuccess", "Ulanyjy üstünlikli täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUser() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => usersApi.deleteUser(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
toast.success(t('users.toast.deleteSuccess', 'Ulanyjy üstünlikli öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
toast.success(t("users.toast.deleteSuccess", "Ulanyjy üstünlikli öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { z } from "zod";
|
||||
import type { CreateUserPayload } from "../api/allUsersApi";
|
||||
import type { CreateUserPayload, UpdateUserPayload } from "../api/allUsersApi";
|
||||
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
const urlSchema = (t: (key: string, fallback?: string) => string) =>
|
||||
z
|
||||
.string()
|
||||
.refine((v) => !v || /^(https?:\/\/|www\.|[\w.-]+\.[a-z]{2,})/i.test(v), t("validation.invalidUrl", "validation.invalidUrl"))
|
||||
.default("");
|
||||
|
||||
export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t("validation.required", "validation.required")).min(3, t("validation.minLength", "validation.minLength")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
firstName: z.string().default(""),
|
||||
lastName: z.string().default(""),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, t("validation.required", "validation.required"))
|
||||
@@ -29,9 +37,14 @@ export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fall
|
||||
.string()
|
||||
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
||||
.default(""),
|
||||
avatar: urlSchema(t),
|
||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||
socialFacebook: urlSchema(t),
|
||||
socialInstagram: urlSchema(t),
|
||||
socialTelegram: urlSchema(t),
|
||||
lightMode: z.boolean(),
|
||||
password: z.string(),
|
||||
phoneVerified: z.boolean(),
|
||||
isActive: z.boolean(),
|
||||
active: z.boolean(),
|
||||
});
|
||||
|
||||
return mode === "create"
|
||||
@@ -49,21 +62,57 @@ export type AllUserFormData = z.infer<ReturnType<typeof allUserFormSchema>>;
|
||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||
username: "",
|
||||
name: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
avatar: "",
|
||||
role: "",
|
||||
socialFacebook: "",
|
||||
socialInstagram: "",
|
||||
socialTelegram: "",
|
||||
lightMode: false,
|
||||
password: "",
|
||||
phoneVerified: false,
|
||||
isActive: true,
|
||||
active: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
firstName: data.firstName.trim(),
|
||||
lastName: data.lastName.trim(),
|
||||
phone: data.phone.replace(/\s+/g, ""),
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
telegram: data.socialTelegram.trim(),
|
||||
},
|
||||
lightMode: data.lightMode ? 1 : 0,
|
||||
password: data.password,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildUpdatePayload(data: AllUserFormData): UpdateUserPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
firstName: data.firstName.trim(),
|
||||
lastName: data.lastName.trim(),
|
||||
phone: data.phone.replace(/\s+/g, ""),
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
telegram: data.socialTelegram.trim(),
|
||||
},
|
||||
lightMode: data.lightMode ? 1 : 0,
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,63 +1,45 @@
|
||||
import type { AuthUser } from '@/app/store/authStore'
|
||||
import apiClient from "@/lib/api/client";
|
||||
import type { AuthUser } from "@/app/store/authStore";
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string
|
||||
password: string
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string
|
||||
user: AuthUser
|
||||
export interface LoginData {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
user?: AuthUser;
|
||||
}
|
||||
|
||||
// Mock credentials
|
||||
const MOCK_USERS: Array<{ email: string; password: string; user: AuthUser; token: string }> = [
|
||||
{
|
||||
email: 'jelaletdin',
|
||||
password: '123',
|
||||
token: 'mock-jwt-token-admin-xyz123',
|
||||
user: {
|
||||
id: '1',
|
||||
name: 'Admin User',
|
||||
email: 'admin@tbbank.tm',
|
||||
role: 'admin',
|
||||
},
|
||||
},
|
||||
{
|
||||
email: 'manager@tbbank.tm',
|
||||
password: 'Manager123!',
|
||||
token: 'mock-jwt-token-manager-abc456',
|
||||
user: {
|
||||
id: '2',
|
||||
name: 'Branch Manager',
|
||||
email: 'manager@tbbank.tm',
|
||||
role: 'manager',
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
function delay(ms: number) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
export interface UpdateProfileRequest {
|
||||
name: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
phone?: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export async function loginApi(credentials: LoginRequest): Promise<LoginResponse> {
|
||||
// Simulate network latency
|
||||
await delay(900)
|
||||
export async function loginApi(credentials: LoginRequest): Promise<LoginData> {
|
||||
const response = await apiClient.post<LoginData>("/login", credentials);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
const match = MOCK_USERS.find(
|
||||
(u) => u.email === credentials.email && u.password === credentials.password,
|
||||
)
|
||||
export async function refreshTokenApi(refreshToken: string): Promise<{ accessToken: string; refreshToken: string }> {
|
||||
const response = await apiClient.post<{ accessToken: string; refreshToken: string }>("/token", { refreshToken });
|
||||
return response.data;
|
||||
}
|
||||
|
||||
if (!match) {
|
||||
throw new Error('INVALID_CREDENTIALS')
|
||||
}
|
||||
export async function getProfileApi(): Promise<AuthUser> {
|
||||
const response = await apiClient.get<AuthUser>("/profile");
|
||||
return response.data;
|
||||
}
|
||||
|
||||
return {
|
||||
token: match.token,
|
||||
user: match.user,
|
||||
}
|
||||
export async function updateProfileApi(data: UpdateProfileRequest): Promise<AuthUser> {
|
||||
const response = await apiClient.put<AuthUser>("/profile", data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function logoutApi(): Promise<void> {
|
||||
await delay(300)
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@@ -1,30 +1,62 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'sonner'
|
||||
import i18next from 'i18next'
|
||||
import { useAuthStore } from '@/app/store/authStore'
|
||||
import { loginApi, type LoginRequest } from '../api/authApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
import { loginApi, getProfileApi, updateProfileApi, type LoginRequest, type UpdateProfileRequest } from "../api/authApi";
|
||||
|
||||
export function useLogin() {
|
||||
const navigate = useNavigate()
|
||||
const setAuth = useAuthStore((s) => s.setAuth)
|
||||
const navigate = useNavigate();
|
||||
const setAuth = useAuthStore((s) => s.setAuth);
|
||||
const setUser = useAuthStore((s) => s.setUser);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (credentials: LoginRequest) => loginApi(credentials),
|
||||
onSuccess: ({ token, user }) => {
|
||||
setAuth(token, user)
|
||||
toast.success(i18next.t('Success login', 'Login successful'))
|
||||
navigate('/dashboard', { replace: true })
|
||||
onSuccess: async (data) => {
|
||||
setAuth(data.accessToken, data.refreshToken, data.user ?? null);
|
||||
|
||||
if (!data.user) {
|
||||
const profile = await getProfileApi();
|
||||
setUser(profile);
|
||||
}
|
||||
|
||||
navigate("/dashboard", { replace: true });
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useProfile() {
|
||||
const setUser = useAuthStore((s) => s.setUser);
|
||||
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["auth", "profile"],
|
||||
queryFn: async () => {
|
||||
const profile = await getProfileApi();
|
||||
setUser(profile);
|
||||
return profile;
|
||||
},
|
||||
enabled: isAuthenticated,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateProfile() {
|
||||
const queryClient = useQueryClient();
|
||||
const setUser = useAuthStore((s) => s.setUser);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: UpdateProfileRequest) => updateProfileApi(data),
|
||||
onSuccess: (updatedProfile) => {
|
||||
setUser(updatedProfile);
|
||||
queryClient.setQueryData(["auth", "profile"], updatedProfile);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useLogout() {
|
||||
const clearAuth = useAuthStore((s) => s.clearAuth)
|
||||
const navigate = useNavigate()
|
||||
const clearAuth = useAuthStore((s) => s.clearAuth);
|
||||
const navigate = useNavigate();
|
||||
|
||||
return () => {
|
||||
clearAuth()
|
||||
navigate('/login', { replace: true })
|
||||
}
|
||||
clearAuth();
|
||||
navigate("/login", { replace: true });
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,172 +1,135 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||
|
||||
export interface LocalizedText {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
// ─── Province (for the provinceId select) ─────────────────────────────────────
|
||||
|
||||
export interface Province {
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
region: LocalizedText;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
// ─── Branch ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Branch {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
code: string
|
||||
districtId: number
|
||||
districtName: Record<'tk' | 'ru' | 'en', string>
|
||||
address: Record<'tk' | 'ru' | 'en', string>
|
||||
phone: string
|
||||
email: string
|
||||
workingHours: string
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
id: number;
|
||||
uniqueCode: string;
|
||||
name: LocalizedText;
|
||||
address: LocalizedText;
|
||||
region: string;
|
||||
provinceId: number;
|
||||
provinceName: LocalizedText;
|
||||
phoneNumbers: string;
|
||||
billingUsername: string;
|
||||
billingPassword: string;
|
||||
billingSberUsername: string;
|
||||
billingSberPassword: string;
|
||||
billingVisaMasterUsername: string;
|
||||
billingVisaMasterPassword: string;
|
||||
billingSwiftUsername: string;
|
||||
billingSwiftPassword: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface BranchListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
provinceId?: string;
|
||||
provinceName?: string;
|
||||
uniqueCode?: string;
|
||||
}
|
||||
|
||||
export interface BranchListResponse {
|
||||
data: Branch[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
count: number;
|
||||
branches: Branch[];
|
||||
}
|
||||
|
||||
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CreateBranchPayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
code: string
|
||||
districtId: number
|
||||
address: Record<'tk' | 'ru' | 'en', string>
|
||||
phone: string
|
||||
email: string
|
||||
workingHours: string
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
address: LocalizedText;
|
||||
billingPassword: string;
|
||||
billingSberPassword: string;
|
||||
billingSberUsername: string;
|
||||
billingSwiftPassword: string;
|
||||
billingSwiftUsername: string;
|
||||
billingUsername: string;
|
||||
billingVisaMasterPassword: string;
|
||||
billingVisaMasterUsername: string;
|
||||
name: LocalizedText;
|
||||
phoneNumbers: string;
|
||||
provinceId: number;
|
||||
region: string;
|
||||
uniqueCode: string;
|
||||
}
|
||||
|
||||
export interface UpdateBranchPayload extends CreateBranchPayload {
|
||||
id: number
|
||||
id: number;
|
||||
}
|
||||
|
||||
const DISTRICTS = [
|
||||
{ id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' } },
|
||||
{ id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' } },
|
||||
{ id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' } },
|
||||
{ id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' } },
|
||||
{ id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' } },
|
||||
{ id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' } },
|
||||
{ id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' } },
|
||||
]
|
||||
// ─── Branch CRUD ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function getDistrictOptions() {
|
||||
return DISTRICTS
|
||||
}
|
||||
|
||||
function findDistrict(id: number) {
|
||||
return DISTRICTS.find((d) => d.id === id) ?? DISTRICTS[0]
|
||||
}
|
||||
|
||||
const MOCK_BRANCHES: Branch[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: { tk: 'Merkezi şahamça', ru: 'Главное отделение', en: 'Main branch' },
|
||||
code: 'BR-001',
|
||||
districtId: 1,
|
||||
districtName: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' },
|
||||
address: { tk: 'Bitarap Türkmenistan şaýoly, 100', ru: 'Проспект Битарap Туркменистан, 100', en: 'Bitarap Turkmenistan avenue, 100' },
|
||||
phone: '+993 12 45-67-89',
|
||||
email: 'main@tbbank.gov.tm',
|
||||
workingHours: '09:00 - 18:00',
|
||||
description: null,
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: { tk: 'Mary şahamçasy', ru: 'Марыйское отделение', en: 'Mary branch' },
|
||||
code: 'BR-002',
|
||||
districtId: 5,
|
||||
districtName: { tk: 'Mary', ru: 'Мары', en: 'Mary' },
|
||||
address: { tk: 'Gurbansoltan eje köçesi, 25', ru: 'Улица Гурбансолтан эдже, 25', en: 'Gurbansoltan eje street, 25' },
|
||||
phone: '+993 55 12-34-56',
|
||||
email: 'mary@tbbank.gov.tm',
|
||||
workingHours: '09:00 - 17:00',
|
||||
description: null,
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: { tk: 'Daşoguz şahamçasy', ru: 'Дашогузское отделение', en: 'Dashoguz branch' },
|
||||
code: 'BR-003',
|
||||
districtId: 4,
|
||||
districtName: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' },
|
||||
address: { tk: 'Garaşsyzlyk köçesi, 10', ru: 'Улица Гарашсызлык, 10', en: 'Garashsyzlyk street, 10' },
|
||||
phone: '+993 32 98-76-54',
|
||||
email: 'dashoguz@tbbank.gov.tm',
|
||||
workingHours: '08:30 - 17:30',
|
||||
description: 'Şenbe güni 09:00 - 13:00',
|
||||
isActive: false,
|
||||
},
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_BRANCHES]
|
||||
let nextId = 4
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
export async function fetchBranches(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
districtId?: string
|
||||
}): Promise<BranchListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive, districtId } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
) ||
|
||||
item.code.toLowerCase().includes(search.toLowerCase())
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
const matchDistrict =
|
||||
!districtId || String(item.districtId) === districtId
|
||||
return matchSearch && matchActive && matchDistrict
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
export async function fetchBranches(params: BranchListParams = {}, signal?: AbortSignal): Promise<BranchListResponse> {
|
||||
const { page, limit, search, provinceId, provinceName, uniqueCode } = params;
|
||||
const { data } = await apiClient.get<BranchListResponse>("/branches", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
branch_name: search || undefined,
|
||||
province_id: provinceId || undefined,
|
||||
province_name: provinceName || undefined,
|
||||
unique_code: uniqueCode || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchBranchById(id: number): Promise<Branch> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
const { data } = await apiClient.get<Branch>(`/branches/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createBranch(payload: CreateBranchPayload): Promise<Branch> {
|
||||
await delay(400)
|
||||
const district = findDistrict(payload.districtId)
|
||||
const newItem: Branch = {
|
||||
id: nextId++,
|
||||
...payload,
|
||||
districtName: district.name,
|
||||
}
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
const { data } = await apiClient.post<Branch>("/branches", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateBranch(payload: UpdateBranchPayload): Promise<Branch> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const district = findDistrict(payload.districtId)
|
||||
const updated = { ...mockStore[idx], ...payload, districtName: district.name }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
const { id, ...rest } = payload;
|
||||
const { data } = await apiClient.put<Branch>(`/branches/${id}`, rest);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteBranch(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
await apiClient.delete(`/branches/${id}`);
|
||||
}
|
||||
|
||||
// ─── Province options (for the provinceId select) ─────────────────────────────
|
||||
|
||||
export interface ProvinceListResponse {
|
||||
count: number;
|
||||
provinces: Province[];
|
||||
}
|
||||
|
||||
export async function fetchProvinces(
|
||||
params: { page?: number; limit?: number; search?: string } = {},
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProvinceListResponse> {
|
||||
const { page, limit, search } = params;
|
||||
const { data } = await apiClient.get<ProvinceListResponse>("/provinces", {
|
||||
params: { page, limit, name: search || undefined },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,368 +1,466 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { Building2, MapPin, Clock } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
||||
import type { Branch } from '@/features/branches/api/branchesApi'
|
||||
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
||||
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
||||
import { useState, useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { Building2, MapPin, CreditCard } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { useCreateBranch, useUpdateBranch, useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
||||
import type { Branch } from "@/features/branches/api/branchesApi";
|
||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/branches/schemas/branch.schema";
|
||||
import type { BranchFormData } from "@/features/branches/schemas/branch.schema";
|
||||
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof BranchFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof BranchFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
shortLabel: string
|
||||
icon: LucideIcon
|
||||
subtitle: string
|
||||
validate: (form: BranchFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
shortLabel: string;
|
||||
icon: LucideIcon;
|
||||
subtitle: string;
|
||||
validate: (form: BranchFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'basic',
|
||||
titleKey: 'branches.steps.basic',
|
||||
titleFallback: 'Esasy maglumatlar',
|
||||
shortLabel: 'Esasy',
|
||||
id: "basic",
|
||||
titleKey: "branches.steps.basic",
|
||||
titleFallback: "Esasy maglumatlar",
|
||||
shortLabel: "Esasy",
|
||||
icon: Building2,
|
||||
subtitle: 'Ady, kody, etrapy',
|
||||
subtitle: "Ady, unikal belgisi, welayaty",
|
||||
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'address',
|
||||
titleKey: 'branches.steps.address',
|
||||
titleFallback: 'Salgy we habarlaşmak',
|
||||
shortLabel: 'Salgy',
|
||||
id: "address",
|
||||
titleKey: "branches.steps.address",
|
||||
titleFallback: "Salgy we habarlaşmak",
|
||||
shortLabel: "Salgy",
|
||||
icon: MapPin,
|
||||
subtitle: 'Salgy, telefon, e-poçta',
|
||||
subtitle: "Salgy, telefonlar",
|
||||
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'hours',
|
||||
titleKey: 'branches.steps.hours',
|
||||
titleFallback: 'Iş wagty',
|
||||
shortLabel: 'Wagt',
|
||||
icon: Clock,
|
||||
subtitle: 'Iş wagty we bellikler',
|
||||
id: "billing",
|
||||
titleKey: "branches.steps.billing",
|
||||
titleFallback: "Billing maglumatlary",
|
||||
shortLabel: "Billing",
|
||||
icon: CreditCard,
|
||||
subtitle: "Ulanyjy ady we parollar",
|
||||
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
||||
0: ['nameTk', 'nameRu', 'nameEn', 'code', 'districtId', 'isActive'],
|
||||
1: ['addressTk', 'addressRu', 'addressEn', 'phone', 'email'],
|
||||
2: ['workingHours', 'description'],
|
||||
}
|
||||
0: ["nameTk", "nameRu", "nameEn", "uniqueCode", "provinceId", "region", "isActive"],
|
||||
1: ["addressTk", "addressRu", "addressEn", "phoneNumbers"],
|
||||
2: [
|
||||
"billingUsername",
|
||||
"billingPassword",
|
||||
"billingSberUsername",
|
||||
"billingSberPassword",
|
||||
"billingVisaMasterUsername",
|
||||
"billingVisaMasterPassword",
|
||||
"billingSwiftUsername",
|
||||
"billingSwiftPassword",
|
||||
],
|
||||
};
|
||||
|
||||
interface StepContentProps {
|
||||
form: BranchFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
lang: 'tk' | 'ru' | 'en'
|
||||
form: BranchFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
lang: "tm" | "ru" | "en";
|
||||
provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
|
||||
}
|
||||
|
||||
function StepBasic({ form, errors, set, t, lang }: StepContentProps) {
|
||||
function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set('nameTk', v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set('nameRu', v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set('nameEn', v), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<MultiLangInput fields={nameFields} placeholder={t('branches.fields.name', 'Şahamçanyň ady')} />
|
||||
<MultiLangInput fields={nameFields} placeholder={t("branches.fields.name", "Şahamçanyň ady")} />
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('branches.fields.code', 'Kod')}
|
||||
label={t("branches.fields.uniqueCode", "Unikal belgisi")}
|
||||
required
|
||||
value={form.code}
|
||||
onChange={(v) => set('code', v)}
|
||||
placeholder="BR-XXX"
|
||||
error={errors.code}
|
||||
value={form.uniqueCode}
|
||||
onChange={(v) => set("uniqueCode", v)}
|
||||
placeholder="ORG-XXX-XXXX"
|
||||
error={errors.uniqueCode}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.region", "Welaýat")}
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder="Aşgabat şäheri"
|
||||
error={errors.region}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('branches.fields.district', 'Etrap')}
|
||||
<InfiniteSelect
|
||||
label={t("branches.fields.district", "Etrap")}
|
||||
required
|
||||
value={form.districtId}
|
||||
onChange={(v) => set('districtId', v)}
|
||||
options={getDistrictOptions().map((d) => ({ value: String(d.id), label: d.name[lang] }))}
|
||||
placeholder={t('branches.fields.district', 'Etrap saýlaň')}
|
||||
error={errors.districtId}
|
||||
placeholder={t("branches.fields.district", "Etrap saýlaň")}
|
||||
{...provinceSelect}
|
||||
error={provinceSelect.error ?? errors.provinceId}
|
||||
value={form.provinceId}
|
||||
onChange={(v) => set("provinceId", v)}
|
||||
/>
|
||||
<div className="flex items-end pb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="isActive"
|
||||
checked={form.isActive}
|
||||
onCheckedChange={(checked) => set('isActive', !!checked)}
|
||||
/>
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
||||
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
|
||||
{t('branches.fields.isActive', 'Işjeň')}
|
||||
{t("branches.fields.isActive", "Işjeň")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepAddress({ form, errors, set, t }: StepContentProps) {
|
||||
const addressFields = {
|
||||
tk: { value: form.addressTk, onChange: (v: string) => set('addressTk', v), error: errors.addressTk },
|
||||
ru: { value: form.addressRu, onChange: (v: string) => set('addressRu', v), error: errors.addressRu },
|
||||
en: { value: form.addressEn, onChange: (v: string) => set('addressEn', v), error: errors.addressEn },
|
||||
}
|
||||
tk: { value: form.addressTk, onChange: (v: string) => set("addressTk", v), error: errors.addressTk },
|
||||
ru: { value: form.addressRu, onChange: (v: string) => set("addressRu", v), error: errors.addressRu },
|
||||
en: { value: form.addressEn, onChange: (v: string) => set("addressEn", v), error: errors.addressEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<MultiLangInput fields={addressFields} placeholder={t('branches.fields.address', 'Salgy')} />
|
||||
<MultiLangInput fields={addressFields} placeholder={t("branches.fields.address", "Salgy")} />
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t('branches.fields.phone', 'Telefon')}
|
||||
type="text"
|
||||
label={t("branches.fields.phoneNumbers", "Telefonlar")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set('phone', v)}
|
||||
placeholder="12 45-67-89"
|
||||
error={errors.phone}
|
||||
/>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t('branches.fields.email', 'E-poçta')}
|
||||
required
|
||||
value={form.email}
|
||||
onChange={(v) => set('email', v)}
|
||||
placeholder="email@tbbank.gov.tm"
|
||||
error={errors.email}
|
||||
value={form.phoneNumbers}
|
||||
onChange={(v) => set("phoneNumbers", v)}
|
||||
placeholder="+99312998877, +99365123456"
|
||||
error={errors.phoneNumbers}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepHours({ form, errors, set, t }: StepContentProps) {
|
||||
function StepBilling({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('branches.fields.workingHours', 'Iş wagty')}
|
||||
label={t("branches.fields.billingIbr", "Billing ulanyjy ady")}
|
||||
required
|
||||
value={form.workingHours}
|
||||
onChange={(v) => set('workingHours', v)}
|
||||
placeholder="09:00 - 18:00"
|
||||
error={errors.workingHours}
|
||||
value={form.billingUsername}
|
||||
onChange={(v) => set("billingUsername", v)}
|
||||
placeholder="billing_user"
|
||||
error={errors.billingUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingPassword", "Billing paroly")}
|
||||
required
|
||||
value={form.billingPassword}
|
||||
onChange={(v) => set("billingPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingSber", "Billing ulanyjy ady (SBER)")}
|
||||
required
|
||||
value={form.billingSberUsername}
|
||||
onChange={(v) => set("billingSberUsername", v)}
|
||||
placeholder="sber_merchant"
|
||||
error={errors.billingSberUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingSberPassword", "Parol (SBER)")}
|
||||
required
|
||||
value={form.billingSberPassword}
|
||||
onChange={(v) => set("billingSberPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingSberPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingVisa", "Billing ulanyjy ady (VISA)")}
|
||||
required
|
||||
value={form.billingVisaMasterUsername}
|
||||
onChange={(v) => set("billingVisaMasterUsername", v)}
|
||||
placeholder="visamaster_merchant"
|
||||
error={errors.billingVisaMasterUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingVisaPassword", "Parol (VISA)")}
|
||||
required
|
||||
value={form.billingVisaMasterPassword}
|
||||
onChange={(v) => set("billingVisaMasterPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingVisaMasterPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingSwift", "Billing ulanyjy ady (SWIFT)")}
|
||||
required
|
||||
value={form.billingSwiftUsername}
|
||||
onChange={(v) => set("billingSwiftUsername", v)}
|
||||
placeholder="SWIFT_TM_BANK"
|
||||
error={errors.billingSwiftUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingSwiftPassword", "Parol (SWIFT)")}
|
||||
required
|
||||
value={form.billingSwiftPassword}
|
||||
onChange={(v) => set("billingSwiftPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingSwiftPassword}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t('branches.fields.description', 'Bellikler')}
|
||||
value={form.description}
|
||||
onChange={(v) => set('description', v)}
|
||||
placeholder="Goşmaça maglumatlar..."
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export interface BranchFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: Branch
|
||||
mode: "create" | "edit";
|
||||
initialData?: Branch;
|
||||
}
|
||||
|
||||
function mapInitial(data: Branch): Partial<BranchFormData> {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameTk: data.name.tm,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
code: data.code,
|
||||
districtId: String(data.districtId),
|
||||
addressTk: data.address.tk,
|
||||
uniqueCode: data.uniqueCode,
|
||||
provinceId: String(data.provinceId),
|
||||
region: data.region,
|
||||
addressTk: data.address.tm,
|
||||
addressRu: data.address.ru,
|
||||
addressEn: data.address.en,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
phoneNumbers: data.phoneNumbers,
|
||||
billingUsername: data.billingUsername,
|
||||
billingPassword: data.billingPassword,
|
||||
billingSberUsername: data.billingSberUsername,
|
||||
billingSberPassword: data.billingSberPassword,
|
||||
billingVisaMasterUsername: data.billingVisaMasterUsername,
|
||||
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||
billingSwiftUsername: data.billingSwiftUsername,
|
||||
billingSwiftPassword: data.billingSwiftPassword,
|
||||
isActive: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en'
|
||||
const navigate = useNavigate()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateBranch()
|
||||
const updateMutation = useUpdateBranch()
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const createMutation = useCreateBranch();
|
||||
const updateMutation = useUpdateBranch();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language])
|
||||
const [provinceSearch, setProvinceSearch] = useState("");
|
||||
const provinceQuery = useInfiniteProvinces(provinceSearch);
|
||||
|
||||
const provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p.provinces)
|
||||
.map((p) => ({ value: String(p.id), label: p.name[lang] }));
|
||||
|
||||
// Ensure the currently-selected province is present (edit mode), even if it
|
||||
// lives beyond the pages loaded so far.
|
||||
if (initialData) {
|
||||
const current = String(initialData.provinceId);
|
||||
if (!opts.some((o) => o.value === current)) {
|
||||
opts.unshift({ value: current, label: initialData.provinceName?.[lang] ?? current });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
options: opts,
|
||||
loading: provinceQuery.isLoading,
|
||||
isLoadingMore: provinceQuery.isFetchingNextPage,
|
||||
hasNextPage: !!provinceQuery.hasNextPage,
|
||||
onLoadMore: () => provinceQuery.fetchNextPage(),
|
||||
searchValue: provinceSearch,
|
||||
onSearchChange: setProvinceSearch,
|
||||
};
|
||||
}, [provinceQuery, provinceSearch, lang, initialData]);
|
||||
|
||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<BranchFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
const [isValidated, setIsValidated] = useState(false)
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [isValidated, setIsValidated] = useState(false);
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited, t])
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, t]);
|
||||
|
||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, lang }), [form, errors, set, t, lang])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, lang, provinceSelect }), [form, errors, set, t, lang, provinceSelect]);
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (!isValidated) return
|
||||
if (!isValidated) return;
|
||||
|
||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || [])
|
||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || []);
|
||||
if (visitedFields.length > 0) {
|
||||
trigger(visitedFields)
|
||||
trigger(visitedFields);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language, isValidated])
|
||||
}, [i18n.language, isValidated]);
|
||||
|
||||
const handleNext = async () => {
|
||||
setIsValidated(true)
|
||||
markVisited(currentStep)
|
||||
setIsValidated(true);
|
||||
markVisited(currentStep);
|
||||
|
||||
const fields = STEP_FIELDS[currentStep] || []
|
||||
const isValid = await trigger(fields)
|
||||
const fields = STEP_FIELDS[currentStep] || [];
|
||||
const isValid = await trigger(fields);
|
||||
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const doSubmit = async () => {
|
||||
setIsValidated(true)
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
setIsValidated(true);
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const isValid = await trigger()
|
||||
const isValid = await trigger();
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||
setCurrentStep(i); break
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate("/settings/location/branches") });
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(
|
||||
{ id: initialData.id, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/location/branches') },
|
||||
)
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/location/branches") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: s.subtitle,
|
||||
icon: s.icon,
|
||||
status: isActive ? 'active'
|
||||
: hasErrors ? 'error'
|
||||
: isDone ? 'done'
|
||||
: 'idle',
|
||||
}
|
||||
})
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create' ? t('branches.createTitle', 'Şahamça döretmek') : t('branches.editTitle', 'Şahamçany üýtgetmek')}
|
||||
{mode === "create" ? t("branches.createTitle", "Şahamça döretmek") : t("branches.editTitle", "Şahamçany üýtgetmek")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('branches.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{t("branches.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||
</div>
|
||||
|
||||
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
|
||||
@@ -372,15 +470,13 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
|
||||
{currentStep + 1} / {STEPS.length}
|
||||
</span>
|
||||
<h2 className="text-sm font-semibold text-foreground">
|
||||
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
|
||||
</h2>
|
||||
<h2 className="text-sm font-semibold text-foreground">{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}</h2>
|
||||
</div>
|
||||
|
||||
<div className="p-5">
|
||||
{currentStep === 0 && <StepBasic {...stepProps} />}
|
||||
{currentStep === 1 && <StepAddress {...stepProps} />}
|
||||
{currentStep === 2 && <StepHours {...stepProps} />}
|
||||
{currentStep === 2 && <StepBilling {...stepProps} />}
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
@@ -390,12 +486,10 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={mode === 'create'
|
||||
? t('branches.actions.create', 'Şahamça döret')
|
||||
: t('branches.actions.update', 'Täzelemek')}
|
||||
submitLabel={mode === "create" ? t("branches.actions.create", "Şahamça döret") : t("branches.actions.update", "Täzelemek")}
|
||||
className="px-5 py-3.5 border-t border-border bg-muted/30"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,35 +1,79 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchBranches,
|
||||
fetchBranchById,
|
||||
fetchProvinces,
|
||||
createBranch,
|
||||
updateBranch,
|
||||
deleteBranch,
|
||||
type BranchListParams,
|
||||
type CreateBranchPayload,
|
||||
type UpdateBranchPayload,
|
||||
} from '../api/branchesApi'
|
||||
type Province,
|
||||
} from "../api/branchesApi";
|
||||
|
||||
export const branchKeys = {
|
||||
all: ['branches'] as const,
|
||||
lists: () => [...branchKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...branchKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...branchKeys.all, 'detail', id] as const,
|
||||
all: ["branches"] as const,
|
||||
lists: () => [...branchKeys.all, "list"] as const,
|
||||
list: (params: BranchListParams) => [...branchKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...branchKeys.all, "detail", id] as const,
|
||||
provinces: ["provinces"] as const,
|
||||
};
|
||||
|
||||
export function useBranches(params: BranchListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: BranchListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: branchKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchBranches(queryParams, signal),
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranches(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
districtId?: string
|
||||
}) {
|
||||
const PROVINCE_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Paginated provinces for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteProvinces(search = "") {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: [...branchKeys.provinces, "infinite", effectiveSearch],
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) => fetchProvinces({ page: pageParam, limit: PROVINCE_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + p.provinces.length, 0);
|
||||
return loaded < lastPage.count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads every province page and flattens them.
|
||||
* Intended for static option lists (e.g. table filter dropdowns) where the
|
||||
* dataset is small and an infinite-scroll select is overkill.
|
||||
*/
|
||||
export function useProvinceOptions() {
|
||||
return useQuery({
|
||||
queryKey: branchKeys.list(params),
|
||||
queryFn: () => fetchBranches(params),
|
||||
})
|
||||
queryKey: [...branchKeys.provinces, "all"] as const,
|
||||
queryFn: async (): Promise<Province[]> => {
|
||||
const all: Province[] = [];
|
||||
let page = 1;
|
||||
for (;;) {
|
||||
const res = await fetchProvinces({ page, limit: PROVINCE_PAGE_SIZE });
|
||||
all.push(...res.provinces);
|
||||
if (all.length >= res.count || res.provinces.length === 0) break;
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranchById(id: number) {
|
||||
@@ -37,45 +81,45 @@ export function useBranchById(id: number) {
|
||||
queryKey: branchKeys.detail(id),
|
||||
queryFn: () => fetchBranchById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateBranchPayload) => createBranch(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
||||
toast.success(t('branches.toast.createSuccess', 'Şahamça döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
toast.success(t("branches.toast.createSuccess", "Şahamça döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateBranchPayload) => updateBranch(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) })
|
||||
toast.success(t('branches.toast.updateSuccess', 'Şahamça täzelendi'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) });
|
||||
toast.success(t("branches.toast.updateSuccess", "Şahamça täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteBranch(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() })
|
||||
toast.success(t('branches.toast.deleteSuccess', 'Şahamça öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
toast.success(t("branches.toast.deleteSuccess", "Şahamça öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,39 +1,26 @@
|
||||
import { z } from "zod";
|
||||
import type { CreateBranchPayload } from "@/features/branches/api/branchesApi";
|
||||
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
districtId: z.string().min(1, t("validation.required", "validation.required")),
|
||||
uniqueCode: z.string().min(1, t("validation.required", "validation.required")),
|
||||
provinceId: z.string().min(1, t("validation.required", "validation.required")),
|
||||
region: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, t("validation.required", "validation.required"))
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: t("validation.invalidPhone", "validation.invalidPhone") },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
const prefix = digits.slice(0, 2);
|
||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
||||
},
|
||||
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
||||
),
|
||||
email: z.string().min(1, t("validation.required", "validation.required")),
|
||||
workingHours: z.string().min(1, t("validation.required", "validation.required")),
|
||||
description: z.string().optional(),
|
||||
phoneNumbers: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSberUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSberPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingVisaMasterUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingVisaMasterPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSwiftUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSwiftPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
isActive: z.boolean(),
|
||||
});
|
||||
}
|
||||
@@ -45,9 +32,18 @@ type StepSchemas = Record<number, z.ZodType<Partial<BranchFormData>>>;
|
||||
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
||||
const schema = createBranchFormSchema(t);
|
||||
return {
|
||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
||||
2: schema.pick({ workingHours: true }),
|
||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, uniqueCode: true, provinceId: true, region: true }),
|
||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phoneNumbers: true }),
|
||||
2: schema.pick({
|
||||
billingUsername: true,
|
||||
billingPassword: true,
|
||||
billingSberUsername: true,
|
||||
billingSberPassword: true,
|
||||
billingVisaMasterUsername: true,
|
||||
billingVisaMasterPassword: true,
|
||||
billingSwiftUsername: true,
|
||||
billingSwiftPassword: true,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -75,28 +71,40 @@ export const DEFAULT_FORM_VALUES: BranchFormData = {
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
code: "",
|
||||
districtId: "",
|
||||
uniqueCode: "",
|
||||
provinceId: "",
|
||||
region: "",
|
||||
addressTk: "",
|
||||
addressRu: "",
|
||||
addressEn: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
workingHours: "",
|
||||
description: "",
|
||||
phoneNumbers: "",
|
||||
billingUsername: "",
|
||||
billingPassword: "",
|
||||
billingSberUsername: "",
|
||||
billingSberPassword: "",
|
||||
billingVisaMasterUsername: "",
|
||||
billingVisaMasterPassword: "",
|
||||
billingSwiftUsername: "",
|
||||
billingSwiftPassword: "",
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: BranchFormData): CreateBranchPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
code: data.code,
|
||||
districtId: Number(data.districtId),
|
||||
address: { tk: data.addressTk, ru: data.addressRu, en: data.addressEn },
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: (data.description ?? "").trim() || null,
|
||||
isActive: data.isActive,
|
||||
name: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
uniqueCode: data.uniqueCode.trim(),
|
||||
provinceId: Number(data.provinceId),
|
||||
region: data.region.trim(),
|
||||
address: { tm: data.addressTk.trim(), ru: data.addressRu.trim(), en: data.addressEn.trim() },
|
||||
phoneNumbers: data.phoneNumbers.trim(),
|
||||
billingUsername: data.billingUsername.trim(),
|
||||
billingPassword: data.billingPassword,
|
||||
billingSberUsername: data.billingSberUsername.trim(),
|
||||
billingSberPassword: data.billingSberPassword,
|
||||
billingVisaMasterUsername: data.billingVisaMasterUsername.trim(),
|
||||
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||
billingSwiftUsername: data.billingSwiftUsername.trim(),
|
||||
billingSwiftPassword: data.billingSwiftPassword,
|
||||
active: data.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,187 +1,191 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { type CardBalance } from '@/features/cardBalance/api/cardBalanceApi'
|
||||
import { useCreateCardBalance, useUpdateCardBalance } from '@/features/cardBalance/hooks/useCardBalance'
|
||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '@/features/cardBalance/schemas/cardBalance.schema'
|
||||
import type { CardBalanceFormData } from '@/features/cardBalance/schemas/cardBalance.schema'
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { type CardBalance } from "@/features/cardBalance/api/cardBalanceApi";
|
||||
import { useCreateCardBalance, useUpdateCardBalance } from "@/features/cardBalance/hooks/useCardBalance";
|
||||
import { cardBalanceFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
import type { CardBalanceFormData } from "@/features/cardBalance/schemas/cardBalance.schema";
|
||||
|
||||
interface CardBalanceFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardBalance
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardBalance;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardBalanceFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardBalanceFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardBalanceFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I-MR', label: 'I-MR' },
|
||||
{ value: 'II-MR', label: 'II-MR' },
|
||||
{ value: 'I-LB', label: 'I-LB' },
|
||||
{ value: 'II-LB', label: 'II-LB' },
|
||||
{ value: 'III-LB', label: 'III-LB' },
|
||||
{ value: 'I-BN', label: 'I-BN' },
|
||||
{ value: 'II-BN', label: 'II-BN' },
|
||||
{ value: 'I-AH', label: 'I-AH' },
|
||||
{ value: 'I-AS', label: 'I-AS' },
|
||||
{ value: 'I-DZ', label: 'I-DZ' },
|
||||
{ value: 'II-DZ', label: 'II-DZ' },
|
||||
{ value: 'A', label: 'A' },
|
||||
{ value: 'B', label: 'B' },
|
||||
]
|
||||
{ value: "I-MR", label: "I-MR" },
|
||||
{ value: "II-MR", label: "II-MR" },
|
||||
{ value: "I-LB", label: "I-LB" },
|
||||
{ value: "II-LB", label: "II-LB" },
|
||||
{ value: "III-LB", label: "III-LB" },
|
||||
{ value: "I-BN", label: "I-BN" },
|
||||
{ value: "II-BN", label: "II-BN" },
|
||||
{ value: "I-AH", label: "I-AH" },
|
||||
{ value: "I-AS", label: "I-AS" },
|
||||
{ value: "I-DZ", label: "I-DZ" },
|
||||
{ value: "II-DZ", label: "II-DZ" },
|
||||
{ value: "A", label: "A" },
|
||||
{ value: "B", label: "B" },
|
||||
];
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, '0')
|
||||
return { value: val, label: val }
|
||||
})
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
});
|
||||
|
||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
const year = String(new Date().getFullYear() + i)
|
||||
return { value: year, label: year }
|
||||
})
|
||||
const year = String(new Date().getFullYear() + i);
|
||||
return { value: year, label: year };
|
||||
});
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
|
||||
export function CardBalanceForm({ mode, initialData }: CardBalanceFormProps) {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardBalance()
|
||||
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0)
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const createMutation = useCreateCardBalance();
|
||||
const updateMutation = useUpdateCardBalance(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardBalanceFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const setField = useCallback((field: keyof CardBalanceFormData) => (value: string) => {
|
||||
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value)
|
||||
clearErrors(field)
|
||||
}, [setValue, clearErrors])
|
||||
const setField = useCallback(
|
||||
(field: keyof CardBalanceFormData) => (value: string) => {
|
||||
(setValue as (name: keyof CardBalanceFormData, val: string) => void)(field, value);
|
||||
clearErrors(field);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const errMsg = (msg: string | undefined) =>
|
||||
!msg ? undefined : msg.startsWith('validation.') ? t(msg, msg) : msg
|
||||
const errMsg = (msg: string | undefined) => (!msg ? undefined : msg.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const result = cardBalanceFormSchema.safeParse(getValues())
|
||||
const result = cardBalanceFormSchema.safeParse(getValues());
|
||||
if (!result.success) {
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardBalanceFormData
|
||||
setError(key, { message: issue.message })
|
||||
const key = issue.path[0] as keyof CardBalanceFormData;
|
||||
setError(key, { message: issue.message });
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
const payload = buildPayload(result.data)
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/card-balances')
|
||||
const payload = buildPayload(result.data);
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/card-balances");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/card-balances/${initialData!.id}`)
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/card-balances/${initialData!.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === 'create') navigate('/card-balances')
|
||||
else navigate(`/card-balances/${initialData!.id}`)
|
||||
}
|
||||
if (mode === "create") navigate("/card-balances");
|
||||
else navigate(`/card-balances/${initialData!.id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardBalance.createTitle', 'Kart galyndysy dörediň')
|
||||
: t('cardBalance.editTitle', 'Kart galyndysy üýtgetmek')}
|
||||
{mode === "create"
|
||||
? t("cardBalance.createTitle", "Kart galyndysy dörediň")
|
||||
: t("cardBalance.editTitle", "Kart galyndysy üýtgetmek")}
|
||||
</h1>
|
||||
<div className="rounded-lg border border-border bg-card p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Row 1 */}
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport series', 'Pasport seriýasy')}
|
||||
value={form.passport_series}
|
||||
onChange={setField('passport_series')}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('Select to choose', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.passport_series)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport number', 'Pasport belgisi')}
|
||||
value={form.passport_number}
|
||||
onChange={setField('passport_number')}
|
||||
placeholder={t('Passport number', 'Pasport belgisi')}
|
||||
error={errMsg(errors.passport_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Row 2 — card number full width + 2 selects */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number', 'Kart belgisi')}
|
||||
value={form.card_number}
|
||||
onChange={setField('card_number')}
|
||||
placeholder={t('Card number', 'Kart belgisi')}
|
||||
error={errMsg(errors.card_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Row 1 */}
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Card expiry month', 'Kart Möhleti (aý)')}
|
||||
value={form.card_expiry_month}
|
||||
onChange={setField('card_expiry_month')}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t('Select', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
type="searchable-select"
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={form.passport_series}
|
||||
onChange={setField("passport_series")}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.passport_series)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Card expiry year', 'Kart Möhleti (ýyl)')}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField('card_expiry_year')}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t('Select', 'Saýlamak üçin basyň')}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
type="text"
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={form.passport_number}
|
||||
onChange={setField("passport_number")}
|
||||
placeholder={t("Passport number", "Pasport belgisi")}
|
||||
error={errMsg(errors.passport_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Row 2 — card number full width + 2 selects */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={form.card_number}
|
||||
onChange={setField("card_number")}
|
||||
placeholder={t("Card number", "Kart belgisi")}
|
||||
error={errMsg(errors.card_number)}
|
||||
required
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||
value={form.card_expiry_month}
|
||||
onChange={setField("card_expiry_month")}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField("card_expiry_year")}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("Select", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
cancelLabel={t('Cancel', 'Ýatyr')}
|
||||
loadingLabel={t('Saving...', 'Saklanýar...')}
|
||||
submitLabel={mode === 'create'
|
||||
? t('Create card balance', 'Kart galyndysy dörediň')
|
||||
: t('Save changes', 'Üýtgetmeleri sakla')}
|
||||
className="mt-6"
|
||||
/>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelLabel={t("Cancel", "Ýatyr")}
|
||||
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||
submitLabel={mode === "create" ? t("Create card balance", "Kart galyndysy dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
||||
className="mt-6"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,213 +2,114 @@ import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type CardPinStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface CardPinItem {
|
||||
id: string;
|
||||
card_type: string;
|
||||
card_type_label: string;
|
||||
card_number: string;
|
||||
created_at: string;
|
||||
province: string;
|
||||
province_label: string;
|
||||
branch: string;
|
||||
branch_label: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
export interface CardPinOrder {
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
cardTypeId: number;
|
||||
cardNumber: string;
|
||||
region: string;
|
||||
branchId: number;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string | null;
|
||||
bornAt: string | null;
|
||||
phone: string;
|
||||
status: CardPinStatus;
|
||||
note: string | null;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: string | null;
|
||||
passport_file_2: string | null;
|
||||
passport_file_3: string | null;
|
||||
passport_file_4: string | null;
|
||||
created_by: string;
|
||||
created_by_label: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
passportOne: string | null;
|
||||
passportTwo: string | null;
|
||||
passportThree: string | null;
|
||||
passportFour: string | null;
|
||||
status: string;
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CardPinListResponse {
|
||||
count: number;
|
||||
cardPinOrders: CardPinOrder[];
|
||||
}
|
||||
|
||||
export interface CardPinListParams {
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
status?: CardPinStatus | "";
|
||||
province?: string;
|
||||
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||
status?: string;
|
||||
branch_id?: string;
|
||||
user_id?: string;
|
||||
card_type_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export interface CardPinListResponse {
|
||||
data: CardPinItem[];
|
||||
meta: {
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CardPinCreatePayload {
|
||||
status: CardPinStatus;
|
||||
note: string;
|
||||
card_type: string;
|
||||
card_number: string;
|
||||
province: string;
|
||||
branch: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
father_name: string;
|
||||
birth_date: string;
|
||||
export interface CreateCardPinPayload {
|
||||
bornAt: string;
|
||||
branchId: number;
|
||||
cardNumber: string;
|
||||
cardTypeId: number;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
notes: string;
|
||||
passportFour: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportSerie: string;
|
||||
passportThree: string;
|
||||
passportTwo: string;
|
||||
phone: string;
|
||||
passport_series: string;
|
||||
passport_number: string;
|
||||
passport_file_1: File | null;
|
||||
passport_file_2: File | null;
|
||||
passport_file_3: File | null;
|
||||
passport_file_4: File | null;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export type CardPinUpdatePayload = CardPinCreatePayload;
|
||||
export type UpdateCardPinPayload = CreateCardPinPayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_PINS: CardPinItem[] = [
|
||||
{
|
||||
id: "1",
|
||||
card_type: "altyn_asyr",
|
||||
card_type_label: "Altyn Asyr",
|
||||
card_number: "8600123456789012",
|
||||
created_at: "2024-05-07 10:00",
|
||||
province: "ashgabat",
|
||||
province_label: "Aşgabat",
|
||||
branch: "1",
|
||||
branch_label: "Merkezi şahamça",
|
||||
first_name: "Aman",
|
||||
last_name: "Amanow",
|
||||
father_name: "Amanowiç",
|
||||
birth_date: "1990-01-01",
|
||||
phone: "99365123456",
|
||||
status: "pending",
|
||||
note: "Test bellik",
|
||||
passport_series: "I-MR",
|
||||
passport_number: "123456",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
card_type: "visa",
|
||||
card_type_label: "Visa",
|
||||
card_number: "4400123456789012",
|
||||
created_at: "2024-05-07 11:30",
|
||||
province: "mary",
|
||||
province_label: "Mary",
|
||||
branch: "2",
|
||||
branch_label: "Mary şahamçasy",
|
||||
first_name: "Berdi",
|
||||
last_name: "Berdiyew",
|
||||
father_name: "Berdiyewiç",
|
||||
birth_date: "1995-05-05",
|
||||
phone: "99361112233",
|
||||
status: "approved",
|
||||
note: null,
|
||||
passport_series: "I-LB",
|
||||
passport_number: "654321",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
created_by: "1",
|
||||
created_by_label: "Admin",
|
||||
},
|
||||
];
|
||||
|
||||
export const cardPinApi = {
|
||||
list: async (params: CardPinListParams): Promise<CardPinListResponse> => {
|
||||
// Mock data return
|
||||
return {
|
||||
data: MOCK_CARD_PINS,
|
||||
meta: {
|
||||
current_page: params.page || 1,
|
||||
last_page: 1,
|
||||
per_page: params.per_page || 25,
|
||||
total: MOCK_CARD_PINS.length,
|
||||
/** GET /card-pin-orders */
|
||||
list: async (params: CardPinListParams = {}, signal?: AbortSignal): Promise<CardPinListResponse> => {
|
||||
const { page, limit, search, status, branch_id, user_id, card_type_id, region } = params;
|
||||
const { data } = await apiClient.get<CardPinListResponse>("/card-pin-orders", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
user_id: user_id || undefined,
|
||||
card_type_id: card_type_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
};
|
||||
|
||||
const { data } = await apiClient.get("/card-pins", { params });
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: string): Promise<CardPinItem> => {
|
||||
const mock = MOCK_CARD_PINS.find((p) => p.id === id);
|
||||
if (mock) return mock;
|
||||
|
||||
const { data } = await apiClient.get(`/card-pins/${id}`);
|
||||
/** GET /card-pin-orders/:id */
|
||||
getById: async (id: number): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.get<CardPinOrder>(`/card-pin-orders/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: (payload: CardPinCreatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload);
|
||||
return apiClient
|
||||
.post("/card-pins", form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
/** POST /card-pin-orders */
|
||||
create: async (payload: CreateCardPinPayload): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.post<CardPinOrder>("/card-pin-orders", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: (id: string, payload: CardPinUpdatePayload): Promise<CardPinItem> => {
|
||||
const form = buildFormData(payload);
|
||||
form.append("_method", "PUT");
|
||||
return apiClient
|
||||
.post(`/card-pins/${id}`, form, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
.then((r) => r.data);
|
||||
/** PUT /card-pin-orders/:id */
|
||||
update: async (id: number, payload: UpdateCardPinPayload): Promise<CardPinOrder> => {
|
||||
const { data } = await apiClient.put<CardPinOrder>(`/card-pin-orders/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
delete: (id: string): Promise<void> => apiClient.delete(`/card-pins/${id}`).then((r) => r.data),
|
||||
/** DELETE /card-pin-orders/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/card-pin-orders/${id}`);
|
||||
},
|
||||
};
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildFormData(payload: CardPinCreatePayload): FormData {
|
||||
const form = new FormData();
|
||||
|
||||
const textFields: (keyof CardPinCreatePayload)[] = [
|
||||
"status",
|
||||
"note",
|
||||
"card_type",
|
||||
"card_number",
|
||||
"province",
|
||||
"branch",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"father_name",
|
||||
"birth_date",
|
||||
"phone",
|
||||
"passport_series",
|
||||
"passport_number",
|
||||
];
|
||||
|
||||
for (const key of textFields) {
|
||||
const val = payload[key];
|
||||
if (val !== null && val !== undefined) {
|
||||
form.append(key, String(val));
|
||||
}
|
||||
}
|
||||
|
||||
const fileFields: (keyof CardPinCreatePayload)[] = ["passport_file_1", "passport_file_2", "passport_file_3", "passport_file_4"];
|
||||
|
||||
for (const key of fileFields) {
|
||||
const file = payload[key];
|
||||
if (file instanceof File) form.append(key, file);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
@@ -1,124 +1,103 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { TFunction } from 'i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
||||
import type { CardPinItem, CardPinCreatePayload } from '@/features/cardPins/api/cardPinApi'
|
||||
import { useCreateCardPin, useUpdateCardPin } from '@/features/cardPins/hooks/useCardPins'
|
||||
import { validateStep, DEFAULT_FORM_VALUES } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
import type { CardPinFormData } from '@/features/cardPins/schemas/cardPin.schema'
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardPinOrder, CreateCardPinPayload } from "@/features/cardPins/api/cardPinApi";
|
||||
import { useCreateCardPin, useUpdateCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
import type { CardPinFormData } from "@/features/cardPins/schemas/cardPin.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardPinFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardPinOrder;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const CARD_TYPE_OPTIONS = [
|
||||
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
|
||||
{ value: 'visa', label: 'Visa' },
|
||||
{ value: 'mastercard', label: 'MasterCard' },
|
||||
]
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I', label: 'I' },
|
||||
{ value: 'II', label: 'II' },
|
||||
{ value: 'I-MR', label: 'I-MR' },
|
||||
{ value: 'II-MR', label: 'II-MR' },
|
||||
]
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: 'ashgabat', label: 'Aşgabat' },
|
||||
{ value: 'mary', label: 'Mary' },
|
||||
{ value: 'dasoguz', label: 'Daşoguz' },
|
||||
{ value: 'lebap', label: 'Lebap' },
|
||||
{ value: 'balkan', label: 'Balkan' },
|
||||
{ value: 'ahal', label: 'Ahal' },
|
||||
]
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardPinFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardPinFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardPinFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: CardPinFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: CardPinFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'card',
|
||||
titleKey: 'cardPin.step.card',
|
||||
titleFallback: 'Kart',
|
||||
subtitleKey: 'cardPinForm.steps.card.subtitle',
|
||||
subtitleFallback: 'Görnüş & lokasiýa',
|
||||
id: "card",
|
||||
titleKey: "cardPin.step.card",
|
||||
titleFallback: "Kart",
|
||||
subtitleKey: "cardPinForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
titleKey: 'cardPin.step.personal',
|
||||
titleFallback: 'Şahsy',
|
||||
subtitleKey: 'cardPinForm.steps.personal.subtitle',
|
||||
subtitleFallback: 'Maglumatlar',
|
||||
id: "personal",
|
||||
titleKey: "cardPin.step.personal",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "cardPinForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Maglumatlar",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
titleKey: 'cardPin.step.passport',
|
||||
titleFallback: 'Pasport',
|
||||
subtitleKey: 'cardPinForm.steps.passport.subtitle',
|
||||
subtitleFallback: 'Resminamalar',
|
||||
id: "passport",
|
||||
titleKey: "cardPin.step.passport",
|
||||
titleFallback: "Pasport",
|
||||
subtitleKey: "cardPinForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resminamalar",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: CardPinFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void
|
||||
t: TFunction
|
||||
form: CardPinFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof CardPinFormData>(k: K, v: CardPinFormData[K]) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const STATUS_OPTIONS = useMemo(() => [
|
||||
{ value: 'pending', label: t('cardPin.status.pending', 'Garaşylýar') },
|
||||
{ value: 'approved', label: t('cardPin.status.approved', 'Tassyklandy') },
|
||||
{ value: 'rejected', label: t('cardPin.status.rejected', 'Ret edildi') },
|
||||
], [t])
|
||||
const STATUS_OPTIONS = useMemo(
|
||||
() => [
|
||||
{ value: "pending", label: t("cardPin.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardPin.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("cardPin.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -126,75 +105,86 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
||||
label={t("cardPin.field.status", "Statusy")}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v)}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
placeholder={t('loanOrderForm.placeholders.select') || 'Saýlaň'}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Note') || 'Bellik'}
|
||||
value={form.note}
|
||||
onChange={(v) => set('note', v)}
|
||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
||||
label={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
required
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardPin.field.uniqueId", "Sargyt belgisi")}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('loanOrderForm.titles.cardInfo') || 'Kart maglumatlary'}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Loan type') || 'Kart görnüşi'}
|
||||
required
|
||||
value={form.card_type}
|
||||
onChange={(v) => set('card_type', v)}
|
||||
options={CARD_TYPE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.card_type}
|
||||
/>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number') || 'Kart belgisi'}
|
||||
label={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
required
|
||||
value={form.card_number}
|
||||
onChange={(v) => set('card_number', v)}
|
||||
placeholder={t('Card number') || 'Kart belgisi'}
|
||||
error={errors.card_number}
|
||||
value={form.cardNumber}
|
||||
onChange={(v) => set("cardNumber", v)}
|
||||
placeholder={t("cardPin.field.cardNumber", "Kart belgisi")}
|
||||
error={errors.cardNumber}
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
required
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
placeholder={t("cardPin.field.cardTypeId", "Kart görnüşi ID")}
|
||||
error={errors.cardTypeId}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('cardPinForm.titles.location') || 'Lokasiýa'}>
|
||||
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Region') || 'Welaýat'}
|
||||
type="text"
|
||||
label={t("cardPin.field.region", "Sebit")}
|
||||
required
|
||||
value={form.province}
|
||||
onChange={(v) => { set('province', v); set('branch', '') }}
|
||||
options={PROVINCE_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.province}
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder={t("cardPin.field.region", "Sebit")}
|
||||
error={errors.region}
|
||||
/>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Branch') || 'Şahamça'}
|
||||
type="number"
|
||||
label={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
required
|
||||
value={form.branch}
|
||||
onChange={(v) => set('branch', v)}
|
||||
options={[]}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
disabled={!form.province}
|
||||
error={errors.branch}
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
placeholder={t("cardPin.field.branchId", "Şahamça ID")}
|
||||
error={errors.branchId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("cardPin.field.notes", "Bellikler")}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("cardPin.field.notes", "Bellikler")}
|
||||
error={errors.notes}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
@@ -203,313 +193,285 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Name') || 'Ady'} required
|
||||
value={form.first_name} onChange={(v) => set('first_name', v)}
|
||||
placeholder={t('Name') || 'Ady'} error={errors.first_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Surname') || 'Familiýasy'} required
|
||||
value={form.last_name} onChange={(v) => set('last_name', v)}
|
||||
placeholder={t('Surname') || 'Familiýasy'} error={errors.last_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Patronic name') || 'Atasynyň ady'}
|
||||
value={form.father_name} onChange={(v) => set('father_name', v)}
|
||||
placeholder={t('Patronic name') || 'Atasynyň ady'}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date" label={t('Date of birth') || 'Doglan güni'} required
|
||||
value={form.birth_date} onChange={(v) => set('birth_date', v)}
|
||||
error={errors.birth_date}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone" label={t('Phone') || 'Telefon'} required
|
||||
value={form.phone} onChange={(v) => set('phone', v)}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t, mode, initialData }: StepContentProps & {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardPinItem
|
||||
}) {
|
||||
const existingFiles =
|
||||
mode === 'edit' && initialData
|
||||
? [
|
||||
{ url: initialData.passport_file_1, label: t('Passport (page 1)') || 'Pasport (sahypa 1)' },
|
||||
{ url: initialData.passport_file_2, label: t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)' },
|
||||
{ url: initialData.passport_file_3, label: t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)' },
|
||||
{ url: initialData.passport_file_4, label: t('Passport (page 32)') || 'Pasport (32-nji sahypa)' },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: []
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
||||
type="text"
|
||||
label={t("cardPin.field.customerName", "Ady")}
|
||||
required
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set('passport_series', v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
error={errors.passport_series}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("cardPin.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport id') || 'Pasport belgisi'}
|
||||
label={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
required
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set('passport_number', v)}
|
||||
placeholder={t('Passport id') || 'Pasport belgisi'}
|
||||
error={errors.passport_number}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("cardPin.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardPin.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{existingFiles.length > 0 && (
|
||||
<BentoGrid cols={4}>
|
||||
{existingFiles.map(({ url, label }) => (
|
||||
<BentoCard key={label} title={label}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary underline truncate block"
|
||||
>
|
||||
{t('loanOrderForm.fileLabels.viewFile') || 'Faýly gör'}
|
||||
</a>
|
||||
</BentoCard>
|
||||
))}
|
||||
</BentoGrid>
|
||||
)}
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage1') || 'Pasport (sahypa 1) (çalyşmak)') : (t('Passport (page 1)') || 'Pasport (sahypa 1)')}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_1}
|
||||
onFileChange={(f) => set('passport_file_1', f)}
|
||||
error={errors.passport_file_1}
|
||||
type="date"
|
||||
label={t("cardPin.field.bornAt", "Doglan güni")}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage23') || 'Pasport (2-3-nji sahypa) (çalyşmak)') : (t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)')}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_2}
|
||||
onFileChange={(f) => set('passport_file_2', f)}
|
||||
error={errors.passport_file_2}
|
||||
type="text"
|
||||
label={t("cardPin.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardPin.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_3}
|
||||
onFileChange={(f) => set('passport_file_3', f)}
|
||||
error={errors.passport_file_3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 32)') || 'Pasport (32-nji sahypa)'}
|
||||
required={mode === 'create'}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_file_4}
|
||||
onFileChange={(f) => set('passport_file_4', f)}
|
||||
error={errors.passport_file_4}
|
||||
type="number"
|
||||
label={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardPin.field.userId", "Ulanyjy ID")}
|
||||
error={errors.userId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
placeholder={t("cardPin.field.passportSerie", "Pasport seriýasy")}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardPin.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardPin.field.passportOne", "Pasport 1")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardPin.field.passportTwo", "Pasport 2")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardPin.field.passportThree", "Pasport 3")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardPin.field.passportFour", "Pasport 4")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const createMutation = useCreateCardPin()
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const createMutation = useCreateCardPin();
|
||||
const updateMutation = useUpdateCardPin(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardPinFormData>({
|
||||
defaultValues: initialData
|
||||
? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) }
|
||||
: DEFAULT_FORM_VALUES,
|
||||
})
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set())
|
||||
const form = watch();
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited, i18n.language])
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof CardPinFormData>(key: K, value: CardPinFormData[K]) => {
|
||||
(setValue as (name: K, val: CardPinFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode))
|
||||
Object.assign(result, STEPS[stepIdx].validate(form));
|
||||
}
|
||||
return result
|
||||
}, [form, mode, submittedSteps, i18n.language])
|
||||
return result;
|
||||
}, [form, mode, submittedSteps, i18n.language]);
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>)
|
||||
return { ...fromRHF, ...allSubmittedErrors }
|
||||
}, [rhfErrors, allSubmittedErrors])
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) =>
|
||||
setSubmittedSteps((prev) => new Set([...prev, i]))
|
||||
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep)
|
||||
markSubmitted(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)))
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const values = getValues()
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values, mode))
|
||||
const values = getValues();
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(values));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardPinFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof CardPinFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(values, mode)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
if (Object.keys(STEPS[i].validate(values)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: CardPinCreatePayload = {
|
||||
status: values.status as CardPinCreatePayload['status'],
|
||||
note: values.note ?? '',
|
||||
card_type: values.card_type,
|
||||
card_number: values.card_number,
|
||||
province: values.province,
|
||||
branch: values.branch,
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
father_name: values.father_name ?? '',
|
||||
birth_date: values.birth_date,
|
||||
phone: values.phone,
|
||||
passport_series: values.passport_series,
|
||||
passport_number: values.passport_number,
|
||||
passport_file_1: values.passport_file_1,
|
||||
passport_file_2: values.passport_file_2,
|
||||
passport_file_3: values.passport_file_3,
|
||||
passport_file_4: values.passport_file_4,
|
||||
}
|
||||
const payload: CreateCardPinPayload = buildPayload(values);
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: (data) => navigate(`/card-pins/${data.id}`) });
|
||||
} else {
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate('/card-pins') })
|
||||
updateMutation.mutate(payload, { onSuccess: () => navigate("/card-pins") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── StepBar items ──────────────────────────────────────────────────────────
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
||||
icon: s.icon,
|
||||
status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle',
|
||||
}
|
||||
})
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -518,13 +480,9 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
{/* Page header */}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('cardPin.createTitle', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editTitle', 'Kart pin bukja redaktirläň')}
|
||||
{mode === "create" ? t("cardPin.createTitle", "Kart pin bukja dörediň") : t("cardPin.editTitle", "Kart pin bukja redaktirläň")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('common.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{t("common.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||
</div>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -533,46 +491,48 @@ export function CardPinForm({ mode, initialData }: CardPinFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && (
|
||||
<StepPassport {...stepProps} mode={mode} initialData={initialData} />
|
||||
)}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={currentStep === 0 ? () => navigate('/card-pins') : undefined}
|
||||
onCancel={currentStep === 0 ? () => navigate("/card-pins") : undefined}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
prevLabel={t('common.prev', 'Yza')}
|
||||
prevLabel={t("common.prev", "Yza")}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
nextLabel={t('common.next', 'Indiki')}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('cardPin.createBtn', 'Kart pin bukja dörediň')
|
||||
: t('cardPin.editBtn', 'Kart pin bukja redaktirläň')
|
||||
mode === "create" ? t("cardPin.createBtn", "Kart pin bukja dörediň") : t("cardPin.editBtn", "Kart pin bukja redaktirläň")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function mapInitial(data: CardPinItem): Partial<CardPinFormData> {
|
||||
function mapInitial(data: CardPinOrder): Partial<CardPinFormData> {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
province: data.province ?? '',
|
||||
branch: data.branch ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
father_name: data.father_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
}
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
status: data.status ?? "",
|
||||
cardNumber: data.cardNumber ?? "",
|
||||
cardTypeId: String(data.cardTypeId ?? ""),
|
||||
region: data.region ?? "",
|
||||
branchId: String(data.branchId ?? ""),
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
phone: data.phone ?? "",
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
userId: String(data.userId ?? ""),
|
||||
notes: data.notes ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,77 +1,81 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cardPinApi, type CardPinListParams, type CardPinCreatePayload, type CardPinUpdatePayload } from '../api/cardPinApi'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { cardPinApi, type CardPinListParams, type CreateCardPinPayload, type UpdateCardPinPayload } from "../api/cardPinApi";
|
||||
|
||||
export const CARD_PIN_KEYS = {
|
||||
all: ['card-pins'] as const,
|
||||
lists: () => [...CARD_PIN_KEYS.all, 'list'] as const,
|
||||
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
||||
detail: (id: string) => [...CARD_PIN_KEYS.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["card-pin-orders"] as const,
|
||||
lists: () => [...CARD_PIN_KEYS.all, "list"] as const,
|
||||
list: (p: CardPinListParams) => [...CARD_PIN_KEYS.lists(), p] as const,
|
||||
detail: (id: number) => [...CARD_PIN_KEYS.all, "detail", id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardPins(params: CardPinListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: CardPinListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: CARD_PIN_KEYS.list(params),
|
||||
queryFn: () => cardPinApi.list(params),
|
||||
queryKey: CARD_PIN_KEYS.list(queryParams),
|
||||
queryFn: ({ signal }) => cardPinApi.list(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Detail ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardPin(id: string) {
|
||||
export function useCardPin(id: number) {
|
||||
return useQuery({
|
||||
queryKey: CARD_PIN_KEYS.detail(id),
|
||||
queryFn: () => cardPinApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => cardPinApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardPin() {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CardPinCreatePayload) => cardPinApi.create(payload),
|
||||
mutationFn: (payload: CreateCardPinPayload) => cardPinApi.create(payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
toast.success(t('cardPin.createSuccess', 'Kart pin bukja döredildi'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
toast.success(t("cardPin.createSuccess", "Kart pin bukja döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardPin(id: string) {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateCardPin(id: number) {
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CardPinUpdatePayload) => cardPinApi.update(id, payload),
|
||||
mutationFn: (payload: UpdateCardPinPayload) => cardPinApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) })
|
||||
toast.success(t('cardPin.updateSuccess', 'Kart pin bukja üýtgedildi'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.detail(id) });
|
||||
toast.success(t("cardPin.updateSuccess", "Kart pin bukja üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardPin() {
|
||||
const qc = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => cardPinApi.delete(id),
|
||||
mutationFn: (id: number) => cardPinApi.delete(id),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() })
|
||||
toast.success(t('cardPin.deleteSuccess', 'Kart pin bukja pozuldy'))
|
||||
qc.invalidateQueries({ queryKey: CARD_PIN_KEYS.lists() });
|
||||
toast.success(t("cardPin.deleteSuccess", "Kart pin bukja pozuldy"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,89 +1,74 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CreateCardPinPayload } from "../api/cardPinApi";
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
const optional = () => z.string().default("");
|
||||
|
||||
export const cardPinFormSchema = z.object({
|
||||
uniqueId: z.string().min(1, "validation.required"),
|
||||
status: z.string().min(1, "validation.required"),
|
||||
note: z.string().optional(),
|
||||
card_type: z.string().min(1, "validation.required"),
|
||||
card_number: z.string().min(1, "validation.required"),
|
||||
province: z.string().min(1, "validation.required"),
|
||||
branch: z.string().min(1, "validation.required"),
|
||||
first_name: z.string().min(1, "validation.required"),
|
||||
last_name: z.string().min(1, "validation.required"),
|
||||
father_name: z.string().optional(),
|
||||
birth_date: z.string().min(1, "validation.required"),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, "validation.required")
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
const prefix = digits.slice(0, 2);
|
||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
),
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_file_1: z.custom<File | null>().nullable(),
|
||||
passport_file_2: z.custom<File | null>().nullable(),
|
||||
passport_file_3: z.custom<File | null>().nullable(),
|
||||
passport_file_4: z.custom<File | null>().nullable(),
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: optional(),
|
||||
bornAt: optional(),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().min(1, "validation.required"),
|
||||
cardTypeId: z.string().min(1, "validation.required"),
|
||||
cardNumber: z.string().min(1, "validation.required"),
|
||||
phone: z.string().min(1, "validation.required"),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
passportOne: optional(),
|
||||
passportTwo: optional(),
|
||||
passportThree: optional(),
|
||||
passportFour: optional(),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
notes: optional(),
|
||||
});
|
||||
|
||||
export type CardPinFormData = z.infer<typeof cardPinFormSchema>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardPinFormData = {
|
||||
status: "pending",
|
||||
note: "",
|
||||
card_type: "",
|
||||
card_number: "",
|
||||
province: "",
|
||||
branch: "",
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
father_name: "",
|
||||
birth_date: "",
|
||||
uniqueId: "",
|
||||
status: "",
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
bornAt: "",
|
||||
region: "",
|
||||
branchId: "",
|
||||
cardTypeId: "",
|
||||
cardNumber: "",
|
||||
phone: "",
|
||||
passport_series: "",
|
||||
passport_number: "",
|
||||
passport_file_1: null,
|
||||
passport_file_2: null,
|
||||
passport_file_3: null,
|
||||
passport_file_4: null,
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
passportOne: "",
|
||||
passportTwo: "",
|
||||
passportThree: "",
|
||||
passportFour: "",
|
||||
userId: "",
|
||||
notes: "",
|
||||
};
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<CardPinFormData>>> = {
|
||||
0: cardPinFormSchema.pick({
|
||||
uniqueId: true,
|
||||
status: true,
|
||||
card_type: true,
|
||||
card_number: true,
|
||||
province: true,
|
||||
branch: true,
|
||||
cardNumber: true,
|
||||
cardTypeId: true,
|
||||
region: true,
|
||||
branchId: true,
|
||||
}),
|
||||
1: cardPinFormSchema.pick({
|
||||
first_name: true,
|
||||
last_name: true,
|
||||
birth_date: true,
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
bornAt: true,
|
||||
phone: true,
|
||||
userId: true,
|
||||
}),
|
||||
2: z.object({
|
||||
passport_series: z.string().min(1, "validation.required"),
|
||||
passport_number: z.string().min(1, "validation.required"),
|
||||
passport_file_1: fileRequired,
|
||||
passport_file_2: fileRequired,
|
||||
passport_file_3: fileRequired,
|
||||
passport_file_4: fileRequired,
|
||||
2: cardPinFormSchema.pick({
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -91,23 +76,7 @@ function translateMsg(msg: string): string {
|
||||
return msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||
}
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: CardPinFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof CardPinFormData, string>> {
|
||||
if (stepIndex === 2 && mode === "edit") {
|
||||
const schema = cardPinFormSchema.pick({ passport_series: true, passport_number: true });
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
const errors: Partial<Record<keyof CardPinFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof CardPinFormData;
|
||||
if (!errors[key]) errors[key] = translateMsg(issue.message);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function validateStep(stepIndex: number, form: CardPinFormData): Partial<Record<keyof CardPinFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex];
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
@@ -119,3 +88,27 @@ export function validateStep(
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function buildPayload(data: CardPinFormData): CreateCardPinPayload {
|
||||
return {
|
||||
uniqueId: data.uniqueId.trim(),
|
||||
status: data.status.trim(),
|
||||
customerName: data.customerName.trim(),
|
||||
customerSurname: data.customerSurname.trim(),
|
||||
customerPatronicName: data.customerPatronicName.trim(),
|
||||
bornAt: data.bornAt.trim(),
|
||||
region: data.region.trim(),
|
||||
branchId: Number(data.branchId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
cardNumber: data.cardNumber.trim(),
|
||||
phone: data.phone.trim(),
|
||||
passportSerie: data.passportSerie.trim(),
|
||||
passportId: data.passportId.trim(),
|
||||
passportOne: data.passportOne.trim(),
|
||||
passportTwo: data.passportTwo.trim(),
|
||||
passportThree: data.passportThree.trim(),
|
||||
passportFour: data.passportFour.trim(),
|
||||
userId: Number(data.userId),
|
||||
notes: data.notes.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,108 +1,68 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LocalizedTitle {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
export interface CardReason {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
id: number;
|
||||
title: LocalizedTitle;
|
||||
price: string;
|
||||
notes: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface CardReasonListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
isActive?: string;
|
||||
}
|
||||
|
||||
export interface CardReasonListResponse {
|
||||
data: CardReason[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
count: number;
|
||||
reasonCards: CardReason[];
|
||||
}
|
||||
|
||||
export interface CreateCardReasonPayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
notes: string;
|
||||
price: string;
|
||||
title: LocalizedTitle;
|
||||
}
|
||||
|
||||
export interface UpdateCardReasonPayload extends CreateCardReasonPayload {
|
||||
id: number
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_STATES: CardReason[] = [
|
||||
{ id: 1, name: { tk: 'Täze', ru: 'Новый', en: 'New' }, value: 32, description: null, isActive: true },
|
||||
{ id: 2, name: { tk: 'Döwülen/Zaýalanan', ru: 'Сломанный/Поврежденный', en: 'Broken/Damaged' }, value: 32, description: null, isActive: true },
|
||||
{ id: 3, name: { tk: 'Ulanylyş möhleti geçen', ru: 'Срок истёк', en: 'Expired' }, value: 32, description: null, isActive: true },
|
||||
{ id: 4, name: { tk: 'Maşgalasy üýtgeýär', ru: 'Смена фамилии', en: 'Name change' }, value: 32, description: null, isActive: true },
|
||||
{ id: 5, name: { tk: 'Ýiten', ru: 'Потерян', en: 'Lost' }, value: 37.75, description: null, isActive: true },
|
||||
{ id: 6, name: { tk: 'Pin bukja (bloklanan)', ru: 'Пин конверт (заблокирован)', en: 'Pin envelope (blocked)' }, value: 3.02, description: null, isActive: false },
|
||||
{ id: 7, name: { tk: 'Rekwizit', ru: 'Реквизит', en: 'Requisite' }, value: 2.30, description: null, isActive: false },
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_CARD_STATES]
|
||||
let nextId = 8
|
||||
|
||||
// Simulated async delay
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
export type UpdateCardReasonPayload = CreateCardReasonPayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardReasons(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}): Promise<CardReasonListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
return matchSearch && matchActive
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
export async function fetchCardReasons(params: CardReasonListParams = {}, signal?: AbortSignal): Promise<CardReasonListResponse> {
|
||||
const { page, limit, search, isActive } = params;
|
||||
const { data } = await apiClient.get<CardReasonListResponse>("/reasons-cards", {
|
||||
params: { page, limit, reason_name: search, is_active: isActive },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchCardReasonById(id: number): Promise<CardReason> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
const { data } = await apiClient.get<CardReason>(`/reasons-cards/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createCardReason(payload: CreateCardReasonPayload): Promise<CardReason> {
|
||||
await delay(400)
|
||||
const newItem: CardReason = { id: nextId++, ...payload }
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
const { data } = await apiClient.post<CardReason>("/reasons-cards", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateCardReason(payload: UpdateCardReasonPayload): Promise<CardReason> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
export async function updateCardReason(id: number, payload: UpdateCardReasonPayload): Promise<CardReason> {
|
||||
const { data } = await apiClient.put<CardReason>(`/reasons-cards/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteCardReason(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
}
|
||||
await apiClient.delete(`/reasons-cards/${id}`);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,15 @@ import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardReason } from "../api/cardReasonsApi";
|
||||
import { useCreateCardReason, useUpdateCardReason } from "../hooks/useCardReasons";
|
||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardReason.schema";
|
||||
import { createCardReasonFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/cardReason.schema";
|
||||
import type { CardReasonFormData } from "../schemas/cardReason.schema";
|
||||
|
||||
// ─── Form errors helper ──────────────────────────────────────────────────────
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardReasonFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardReason;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardReasonFormData, string>>;
|
||||
|
||||
@@ -28,22 +33,6 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
|
||||
// ─── CardReasonForm ─────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardReasonFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardReason;
|
||||
}
|
||||
|
||||
function mapInitial(data: CardReason): CardReasonFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
@@ -53,7 +42,7 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardReason();
|
||||
const updateMutation = useUpdateCardReason();
|
||||
const updateMutation = useUpdateCardReason(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
@@ -62,10 +51,10 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<CardReasonFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
@@ -74,46 +63,47 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const set = useCallback(
|
||||
<K extends keyof CardReasonFormData>(key: K, value: CardReasonFormData[K]) => {
|
||||
(setValue as (name: K, val: CardReasonFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof CardReasonFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof CardReasonFormData, v: string | boolean) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const values = getValues();
|
||||
const payload = buildPayload(values);
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate("/resources/card-states"),
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/resources/card-states") });
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/settings/card/card-reasons/${result.id}`);
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/settings/card/card-reasons/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu")(v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn")(v), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäp üýtgetmek")}
|
||||
{mode === "create" ? t("cardReasons.createTitle", "Sebäp dörediň") : t("cardReasons.editTitle", "Sebäbi üýtgetmek")}
|
||||
</h1>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
@@ -126,40 +116,35 @@ export function CardReasonForm({ mode, initialData }: CardReasonFormProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardReasons.fields.value", "Baha")}
|
||||
value={form.value}
|
||||
onChange={(v) => set("value", v)}
|
||||
placeholder={t("cardReasons.fields.value", "Baha")}
|
||||
error={errors.value}
|
||||
label={t("cardReasons.fields.price", "Baha")}
|
||||
value={form.price}
|
||||
onChange={set("price")}
|
||||
placeholder={t("cardReasons.fields.price", "Baha")}
|
||||
error={errors.price}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardReasons.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={(v) => set("description", v)}
|
||||
placeholder={t("cardReasons.fields.description", "Bellikler")}
|
||||
label={t("cardReasons.fields.notes", "Bellikler")}
|
||||
value={form.notes}
|
||||
onChange={set("notes")}
|
||||
placeholder={t("cardReasons.fields.notes", "Bellikler")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardReasons.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
||||
<Checkbox checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/resources/card-states")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("cardReasons.actions.create", "Kartyň çykarylmagynyň sebäbini döretdiň")
|
||||
: t("cardReasons.actions.update", "Täzelemek")
|
||||
}
|
||||
onCancel={() => navigate("/settings/card/card-reasons")}
|
||||
submitLabel={mode === "create" ? t("cardReasons.actions.create", "Sebäbi döretmek") : t("cardReasons.actions.update", "Täzelemek")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,92 +1,93 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchCardReasons,
|
||||
fetchCardReasonById,
|
||||
createCardReason,
|
||||
updateCardReason,
|
||||
deleteCardReason,
|
||||
type CardReasonListParams,
|
||||
type CreateCardReasonPayload,
|
||||
type UpdateCardReasonPayload,
|
||||
} from '../api/cardReasonsApi'
|
||||
} from "../api/cardReasonsApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardReasonKeys = {
|
||||
all: ['cardReasons'] as const,
|
||||
lists: () => [...cardReasonKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...cardReasonKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...cardReasonKeys.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["cardReasons"] as const,
|
||||
lists: () => [...cardReasonKeys.all, "list"] as const,
|
||||
list: (params: CardReasonListParams) => [...cardReasonKeys.lists(), params] as const,
|
||||
details: () => [...cardReasonKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardReasonKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── useCardReasons ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardReasons(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}) {
|
||||
export function useCardReasons(params: CardReasonListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: CardReasonListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: cardReasonKeys.list(params),
|
||||
queryFn: () => fetchCardReasons(params),
|
||||
})
|
||||
queryKey: cardReasonKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchCardReasons(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCardReasonById ─────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardReasonById(id: number) {
|
||||
export function useCardReasonById(id: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: cardReasonKeys.detail(id),
|
||||
queryFn: () => fetchCardReasonById(id),
|
||||
queryKey: cardReasonKeys.detail(id!),
|
||||
queryFn: () => fetchCardReasonById(id!),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardReasonPayload) => createCardReason(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
toast.success(t('CardReasons.toast.createSuccess', 'Kart ýagdaýy döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||
toast.success(t("cardReasons.toast.createSuccess", "Sebäp döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateCardReason(id: number) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(data.id) })
|
||||
toast.success(t('CardReasons.toast.updateSuccess', 'Kart ýagdaýy täzelendi'))
|
||||
mutationFn: (payload: UpdateCardReasonPayload) => updateCardReason(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.detail(id) });
|
||||
toast.success(t("cardReasons.toast.updateSuccess", "Sebäp täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteCardReason ───────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardReason() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCardReason(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() })
|
||||
toast.success(t('CardReasons.toast.deleteSuccess', 'Kart ýagdaýy öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardReasonKeys.lists() });
|
||||
toast.success(t("cardReasons.toast.deleteSuccess", "Sebäp öçürildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,36 +1,46 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardReasonPayload } from '../api/cardReasonsApi'
|
||||
import { z } from "zod";
|
||||
import type { CardReason, CreateCardReasonPayload } from "../api/cardReasonsApi";
|
||||
|
||||
export function createCardReasonFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
value: z.string().min(1, t('validation.invalidNumber', 'validation.invalidNumber')).refine(
|
||||
(v) => !isNaN(Number(v)) && Number(v) >= 0,
|
||||
{ message: t('validation.invalidNumber', 'Dogry san giriziň') },
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
price: z
|
||||
.string()
|
||||
.refine((v) => v.trim() !== "" && !isNaN(Number(v)) && Number(v) >= 0, t("validation.invalidNumber", "Dogry san giriziň")),
|
||||
notes: z.string().optional(),
|
||||
active: z.boolean(),
|
||||
});
|
||||
}
|
||||
|
||||
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>
|
||||
export type CardReasonFormData = z.infer<ReturnType<typeof createCardReasonFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardReasonFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
value: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
price: "",
|
||||
notes: "",
|
||||
active: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: CardReasonFormData): CreateCardReasonPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
value: Number(data.value),
|
||||
description: data.description?.trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
title: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
price: data.price.trim(),
|
||||
notes: (data.notes ?? "").trim(),
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapInitial(data: CardReason): CardReasonFormData {
|
||||
return {
|
||||
nameTk: data.title.tm,
|
||||
nameRu: data.title.ru,
|
||||
nameEn: data.title.en,
|
||||
price: data.price,
|
||||
notes: data.notes ?? "",
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,168 +1,190 @@
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { TFunction } from 'i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { CreditCard, User, FileText } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { BentoGrid, BentoCard } from '@/components/bento'
|
||||
import type { CardRequisite } from '../api/cardRequisitesApi'
|
||||
import { useCreateCardRequisite, useUpdateCardRequisite } from '../hooks/useCardRequisites'
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/cardRequisite.schema'
|
||||
import type { CardRequisiteFormData } from '../schemas/cardRequisite.schema'
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardRequisite } from "../api/cardRequisitesApi";
|
||||
import { useCreateCardRequisite, useUpdateCardRequisite } from "../hooks/useCardRequisites";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardRequisite.schema";
|
||||
import type { CardRequisiteFormData } from "../schemas/cardRequisite.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface CardRequisiteFormProps {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardRequisite
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardRequisite;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardRequisiteFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof CardRequisiteFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof CardRequisiteFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof CardRequisiteFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'pending', label: 'Garaşylýar' },
|
||||
{ value: 'approved', label: 'Tassyklanan' },
|
||||
{ value: 'rejected', label: 'Ret edilen' },
|
||||
]
|
||||
{ value: "pending", label: "Garaşylýar" },
|
||||
{ value: "approved", label: "Tassyklanan" },
|
||||
{ value: "rejected", label: "Ret edilen" },
|
||||
];
|
||||
|
||||
const CARD_TYPE_OPTIONS = [
|
||||
{ value: 'altyn_asyr', label: 'Altyn Asyr' },
|
||||
{ value: 'visa', label: 'Visa' },
|
||||
{ value: 'mastercard', label: 'MasterCard' },
|
||||
]
|
||||
{ value: "altyn_asyr", label: "Altyn Asyr" },
|
||||
{ value: "visa", label: "Visa" },
|
||||
{ value: "mastercard", label: "MasterCard" },
|
||||
];
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: 'I-MR', label: 'I-MR' },
|
||||
{ value: 'II-MR', label: 'II-MR' },
|
||||
{ value: 'I-LB', label: 'I-LB' },
|
||||
{ value: 'II-LB', label: 'II-LB' },
|
||||
{ value: 'III-LB', label: 'III-LB' },
|
||||
{ value: 'A', label: 'A' },
|
||||
{ value: 'B', label: 'B' },
|
||||
]
|
||||
{ value: "I-MR", label: "I-MR" },
|
||||
{ value: "II-MR", label: "II-MR" },
|
||||
{ value: "I-LB", label: "I-LB" },
|
||||
{ value: "II-LB", label: "II-LB" },
|
||||
{ value: "III-LB", label: "III-LB" },
|
||||
{ value: "A", label: "A" },
|
||||
{ value: "B", label: "B" },
|
||||
];
|
||||
|
||||
const PROVINCE_OPTIONS = [
|
||||
{ value: '1', label: 'Aşgabat' },
|
||||
{ value: '2', label: 'Ahal' },
|
||||
{ value: '3', label: 'Balkan' },
|
||||
{ value: '4', label: 'Daşoguz' },
|
||||
{ value: '5', label: 'Lebap' },
|
||||
{ value: '6', label: 'Mary' },
|
||||
]
|
||||
{ value: "1", label: "Aşgabat" },
|
||||
{ value: "2", label: "Ahal" },
|
||||
{ value: "3", label: "Balkan" },
|
||||
{ value: "4", label: "Daşoguz" },
|
||||
{ value: "5", label: "Lebap" },
|
||||
{ value: "6", label: "Mary" },
|
||||
];
|
||||
|
||||
const BRANCH_OPTIONS: Record<string, { value: string; label: string }[]> = {
|
||||
'1': [{ value: '11', label: 'Köpetdag' }, { value: '12', label: 'Çandybil' }, { value: '13', label: 'Büzmeyin' }],
|
||||
'2': [{ value: '21', label: 'Änew' }, { value: '22', label: 'Tejen' }],
|
||||
'3': [{ value: '31', label: 'Balkanabat' }, { value: '32', label: 'Türkmenbaşy' }],
|
||||
'4': [{ value: '41', label: 'Daşoguz ş.' }, { value: '42', label: 'Köneürgenç' }],
|
||||
'5': [{ value: '51', label: 'Türkmenabat' }, { value: '52', label: 'Hazar' }],
|
||||
'6': [{ value: '61', label: 'Mary ş.' }, { value: '62', label: 'Ýolöten' }, { value: '63', label: 'Şatlyk' }],
|
||||
}
|
||||
"1": [
|
||||
{ value: "11", label: "Köpetdag" },
|
||||
{ value: "12", label: "Çandybil" },
|
||||
{ value: "13", label: "Büzmeyin" },
|
||||
],
|
||||
"2": [
|
||||
{ value: "21", label: "Änew" },
|
||||
{ value: "22", label: "Tejen" },
|
||||
],
|
||||
"3": [
|
||||
{ value: "31", label: "Balkanabat" },
|
||||
{ value: "32", label: "Türkmenbaşy" },
|
||||
],
|
||||
"4": [
|
||||
{ value: "41", label: "Daşoguz ş." },
|
||||
{ value: "42", label: "Köneürgenç" },
|
||||
],
|
||||
"5": [
|
||||
{ value: "51", label: "Türkmenabat" },
|
||||
{ value: "52", label: "Hazar" },
|
||||
],
|
||||
"6": [
|
||||
{ value: "61", label: "Mary ş." },
|
||||
{ value: "62", label: "Ýolöten" },
|
||||
{ value: "63", label: "Şatlyk" },
|
||||
],
|
||||
};
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, '0')
|
||||
return { value: val, label: val }
|
||||
})
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
});
|
||||
|
||||
const YEAR_OPTIONS = Array.from({ length: 20 }, (_, i) => {
|
||||
const year = String(new Date().getFullYear() + i)
|
||||
return { value: year, label: year }
|
||||
})
|
||||
const year = String(new Date().getFullYear() + i);
|
||||
return { value: year, label: year };
|
||||
});
|
||||
|
||||
function mapInitial(data: CardRequisite): CardRequisiteFormData {
|
||||
return {
|
||||
status: data.status ?? 'pending',
|
||||
note: data.note ?? '',
|
||||
card_type: data.card_type ?? '',
|
||||
card_number: data.card_number ?? '',
|
||||
card_expiry_month: data.card_expiry_month ?? '',
|
||||
card_expiry_year: data.card_expiry_year ?? '',
|
||||
province_id: data.province_id ?? '',
|
||||
branch_id: data.branch_id ?? '',
|
||||
first_name: data.first_name ?? '',
|
||||
last_name: data.last_name ?? '',
|
||||
middle_name: data.middle_name ?? '',
|
||||
birth_date: data.birth_date ?? '',
|
||||
phone: data.phone ?? '',
|
||||
passport_series: data.passport_series ?? '',
|
||||
passport_number: data.passport_number ?? '',
|
||||
passport_page1: null, passport_page2_3: null,
|
||||
passport_page8_9: null, passport_page32: null,
|
||||
}
|
||||
status: data.status ?? "pending",
|
||||
note: data.note ?? "",
|
||||
card_type: data.card_type ?? "",
|
||||
card_number: data.card_number ?? "",
|
||||
card_expiry_month: data.card_expiry_month ?? "",
|
||||
card_expiry_year: data.card_expiry_year ?? "",
|
||||
province_id: data.province_id ?? "",
|
||||
branch_id: data.branch_id ?? "",
|
||||
first_name: data.first_name ?? "",
|
||||
last_name: data.last_name ?? "",
|
||||
middle_name: data.middle_name ?? "",
|
||||
birth_date: data.birth_date ?? "",
|
||||
phone: data.phone ?? "",
|
||||
passport_series: data.passport_series ?? "",
|
||||
passport_number: data.passport_number ?? "",
|
||||
passport_page1: null,
|
||||
passport_page2_3: null,
|
||||
passport_page8_9: null,
|
||||
passport_page32: null,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
subtitleKey: string
|
||||
subtitleFallback: string
|
||||
icon: LucideIcon
|
||||
validate: (form: CardRequisiteFormData, mode: 'create' | 'edit') => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: CardRequisiteFormData, mode: "create" | "edit") => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'card',
|
||||
titleKey: 'Card',
|
||||
titleFallback: 'Kart',
|
||||
subtitleKey: 'cardRequisiteForm.steps.card.subtitle',
|
||||
subtitleFallback: 'Görnüş & lokasiýa',
|
||||
id: "card",
|
||||
titleKey: "Card",
|
||||
titleFallback: "Kart",
|
||||
subtitleKey: "cardRequisiteForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'personal',
|
||||
titleKey: 'Personal',
|
||||
titleFallback: 'Şahsy',
|
||||
subtitleKey: 'cardRequisiteForm.steps.personal.subtitle',
|
||||
subtitleFallback: 'At & telefon',
|
||||
id: "personal",
|
||||
titleKey: "Personal",
|
||||
titleFallback: "Şahsy",
|
||||
subtitleKey: "cardRequisiteForm.steps.personal.subtitle",
|
||||
subtitleFallback: "At & telefon",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
},
|
||||
{
|
||||
id: 'passport',
|
||||
titleKey: 'Passport',
|
||||
titleFallback: 'Pasport',
|
||||
subtitleKey: 'cardRequisiteForm.steps.passport.subtitle',
|
||||
subtitleFallback: 'Resminamalar',
|
||||
id: "passport",
|
||||
titleKey: "Passport",
|
||||
titleFallback: "Pasport",
|
||||
subtitleKey: "cardRequisiteForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resminamalar",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
// ─── Shared step content props ────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: CardRequisiteFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void
|
||||
t: TFunction
|
||||
form: CardRequisiteFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof CardRequisiteFormData>(k: K, v: CardRequisiteFormData[K]) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? []
|
||||
const branchOptions = BRANCH_OPTIONS[form.province_id] ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -170,68 +192,68 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('loanOrderForm.labels.status') || 'Status'}
|
||||
label={t("loanOrderForm.labels.status") || "Status"}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set('status', v)}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
error={errors.status}
|
||||
placeholder={t('loanOrderForm.placeholders.select') || 'Saýlaň'}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Note') || 'Bellik'}
|
||||
label={t("Note") || "Bellik"}
|
||||
value={form.note}
|
||||
onChange={(v) => set('note', v)}
|
||||
placeholder={t('loanOrderForm.placeholders.note') || 'Bellik...'}
|
||||
onChange={(v) => set("note", v)}
|
||||
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t('loanOrderForm.titles.cardInfo') || 'Kart maglumatlary'}>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('cardRequisiteForm.labels.cardType') || 'Görnüşi'}
|
||||
label={t("cardRequisiteForm.labels.cardType") || "Görnüşi"}
|
||||
required
|
||||
value={form.card_type}
|
||||
onChange={(v) => set('card_type', v)}
|
||||
onChange={(v) => set("card_type", v)}
|
||||
options={CARD_TYPE_OPTIONS}
|
||||
placeholder="—"
|
||||
error={errors.card_type}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Card number') || 'Kart belgisi'}
|
||||
label={t("Card number") || "Kart belgisi"}
|
||||
required
|
||||
value={form.card_number}
|
||||
onChange={(v) => set('card_number', v)}
|
||||
placeholder={t('Card number') || 'Kart belgisi'}
|
||||
onChange={(v) => set("card_number", v)}
|
||||
placeholder={t("Card number") || "Kart belgisi"}
|
||||
error={errors.card_number}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t('loanOrderForm.titles.cardExpiry') || 'Kart möhleti'}>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardExpiry") || "Kart möhleti"}>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Expiration month') || 'Möhleti (aý)'}
|
||||
label={t("Expiration month") || "Möhleti (aý)"}
|
||||
required
|
||||
value={form.card_expiry_month}
|
||||
onChange={(v) => set('card_expiry_month', v)}
|
||||
onChange={(v) => set("card_expiry_month", v)}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.card_expiry_month}
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Expiration year') || 'Möhleti (ýyl)'}
|
||||
label={t("Expiration year") || "Möhleti (ýyl)"}
|
||||
required
|
||||
value={form.card_expiry_year}
|
||||
onChange={(v) => set('card_expiry_year', v)}
|
||||
onChange={(v) => set("card_expiry_year", v)}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.card_expiry_year}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -241,31 +263,34 @@ function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t('Region') || 'Welaýat'}
|
||||
label={t("Region") || "Welaýat"}
|
||||
required
|
||||
value={form.province_id}
|
||||
onChange={(v) => { set('province_id', v); set('branch_id', '') }}
|
||||
onChange={(v) => {
|
||||
set("province_id", v);
|
||||
set("branch_id", "");
|
||||
}}
|
||||
options={PROVINCE_OPTIONS}
|
||||
placeholder={t('Region') || 'Aşgabat'}
|
||||
placeholder={t("Region") || "Aşgabat"}
|
||||
error={errors.province_id}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Branch') || 'Şahamça'}
|
||||
label={t("Branch") || "Şahamça"}
|
||||
required
|
||||
value={form.branch_id}
|
||||
onChange={(v) => set('branch_id', v)}
|
||||
onChange={(v) => set("branch_id", v)}
|
||||
options={branchOptions}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
disabled={!form.province_id}
|
||||
error={errors.branch_id}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
@@ -274,23 +299,33 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Name') || 'Ady'} required
|
||||
value={form.first_name} onChange={(v) => set('first_name', v)}
|
||||
placeholder={t('Name') || 'Ady'} error={errors.first_name}
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
required
|
||||
value={form.first_name}
|
||||
onChange={(v) => set("first_name", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.first_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Surname') || 'Familiýasy'} required
|
||||
value={form.last_name} onChange={(v) => set('last_name', v)}
|
||||
placeholder={t('Surname') || 'Familiýasy'} error={errors.last_name}
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
required
|
||||
value={form.last_name}
|
||||
onChange={(v) => set("last_name", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.last_name}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text" label={t('Patronic name') || 'Atasynyň ady'}
|
||||
value={form.middle_name} onChange={(v) => set('middle_name', v)}
|
||||
placeholder={t('Patronic name') || 'Atasynyň ady'}
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.middle_name}
|
||||
onChange={(v) => set("middle_name", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -298,37 +333,50 @@ function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date" label={t('Date of birth') || 'Doglan güni'} required
|
||||
value={form.birth_date} onChange={(v) => set('birth_date', v)}
|
||||
type="date"
|
||||
label={t("Date of birth") || "Doglan güni"}
|
||||
required
|
||||
value={form.birth_date}
|
||||
onChange={(v) => set("birth_date", v)}
|
||||
error={errors.birth_date}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone" label={t('Phone') || 'Telefon'} required
|
||||
value={form.phone} onChange={(v) => set('phone', v)}
|
||||
type="phone"
|
||||
label={t("Phone") || "Telefon"}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder="63 21 87 04"
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t, mode, initialData }: StepContentProps & {
|
||||
mode: 'create' | 'edit'
|
||||
initialData?: CardRequisite
|
||||
function StepPassport({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
mode,
|
||||
initialData,
|
||||
}: StepContentProps & {
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardRequisite;
|
||||
}) {
|
||||
const existingFiles =
|
||||
mode === 'edit' && initialData
|
||||
mode === "edit" && initialData
|
||||
? [
|
||||
{ url: initialData.passport_page1_url, label: t('Passport (page 1)') || 'Pasport (sahypa 1)' },
|
||||
{ url: initialData.passport_page2_3_url, label: t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)' },
|
||||
{ url: initialData.passport_page8_9_url, label: t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)' },
|
||||
{ url: initialData.passport_page32_url, label: t('Passport (page 32)') || 'Pasport (32-nji sahypa)' },
|
||||
{ url: initialData.passport_page1_url, label: t("Passport (page 1)") || "Pasport (sahypa 1)" },
|
||||
{ url: initialData.passport_page2_3_url, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" },
|
||||
{ url: initialData.passport_page8_9_url, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" },
|
||||
{ url: initialData.passport_page32_url, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: []
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -336,23 +384,23 @@ function StepPassport({ form, errors, set, t, mode, initialData }: StepContentPr
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('Passport serie') || 'Pasport seriýasy'}
|
||||
label={t("Passport serie") || "Pasport seriýasy"}
|
||||
required
|
||||
value={form.passport_series}
|
||||
onChange={(v) => set('passport_series', v)}
|
||||
onChange={(v) => set("passport_series", v)}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t('loanOrderForm.placeholders.searchableSelect') || 'Saýlamak üçin basyň'}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.passport_series}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('Passport id') || 'Pasport belgisi'}
|
||||
label={t("Passport id") || "Pasport belgisi"}
|
||||
required
|
||||
value={form.passport_number}
|
||||
onChange={(v) => set('passport_number', v)}
|
||||
placeholder={t('Passport id') || 'Pasport belgisi'}
|
||||
onChange={(v) => set("passport_number", v)}
|
||||
placeholder={t("Passport id") || "Pasport belgisi"}
|
||||
error={errors.passport_number}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -362,13 +410,8 @@ function StepPassport({ form, errors, set, t, mode, initialData }: StepContentPr
|
||||
<BentoGrid cols={4}>
|
||||
{existingFiles.map(({ url, label }) => (
|
||||
<BentoCard key={label} title={label}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-primary underline truncate block"
|
||||
>
|
||||
{t('loanOrderForm.fileLabels.viewFile') || 'Faýly gör'}
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate block">
|
||||
{t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"}
|
||||
</a>
|
||||
</BentoCard>
|
||||
))}
|
||||
@@ -379,196 +422,208 @@ function StepPassport({ form, errors, set, t, mode, initialData }: StepContentPr
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage1') || 'Pasport (sahypa 1) (çalyşmak)') : (t('Passport (page 1)') || 'Pasport (sahypa 1)')}
|
||||
required={mode === 'create'}
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
|
||||
: t("Passport (page 1)") || "Pasport (sahypa 1)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page1}
|
||||
onFileChange={(f) => set('passport_page1', f)}
|
||||
onFileChange={(f) => set("passport_page1", f)}
|
||||
error={errors.passport_page1}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={mode === 'edit' ? (t('loanOrderForm.fileLabels.replacePage23') || 'Pasport (2-3-nji sahypa) (çalyşmak)') : (t('Passport (page 2-3)') || 'Pasport (2-3-nji sahypa)')}
|
||||
required={mode === 'create'}
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
|
||||
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page2_3}
|
||||
onFileChange={(f) => set('passport_page2_3', f)}
|
||||
onFileChange={(f) => set("passport_page2_3", f)}
|
||||
error={errors.passport_page2_3}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 8-9)') || 'Pasport (8-9 sahypa)'}
|
||||
required={mode === 'create'}
|
||||
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page8_9}
|
||||
onFileChange={(f) => set('passport_page8_9', f)}
|
||||
onFileChange={(f) => set("passport_page8_9", f)}
|
||||
error={errors.passport_page8_9}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t('Passport (page 32)') || 'Pasport (32-nji sahypa)'}
|
||||
required={mode === 'create'}
|
||||
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passport_page32}
|
||||
onFileChange={(f) => set('passport_page32', f)}
|
||||
onFileChange={(f) => set("passport_page32", f)}
|
||||
error={errors.passport_page32}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardRequisite()
|
||||
const updateMutation = useUpdateCardRequisite(initialData?.id ?? '')
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const createMutation = useCreateCardRequisite();
|
||||
const updateMutation = useUpdateCardRequisite(initialData?.id ?? "");
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, setError,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardRequisiteFormData>({
|
||||
defaultValues: initialData ? mapInitial(initialData) : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set())
|
||||
const form = watch();
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||
|
||||
// ── Computed step errors ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited, i18n.language])
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
const set = useCallback(<K extends keyof CardRequisiteFormData>(key: K, value: CardRequisiteFormData[K]) => {
|
||||
(setValue as (name: K, val: CardRequisiteFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof CardRequisiteFormData>(key: K, value: CardRequisiteFormData[K]) => {
|
||||
(setValue as (name: K, val: CardRequisiteFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode))
|
||||
Object.assign(result, STEPS[stepIdx].validate(form, mode));
|
||||
}
|
||||
return result
|
||||
}, [form, mode, submittedSteps, i18n.language])
|
||||
return result;
|
||||
}, [form, mode, submittedSteps, i18n.language]);
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>)
|
||||
return { ...fromRHF, ...allSubmittedErrors }
|
||||
}, [rhfErrors, allSubmittedErrors])
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
const markSubmitted = (i: number) =>
|
||||
setSubmittedSteps((prev) => new Set([...prev, i]))
|
||||
const markSubmitted = (i: number) => setSubmittedSteps((prev) => new Set([...prev, i]));
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep)
|
||||
markSubmitted(currentStep)
|
||||
const errs = STEPS[currentStep].validate(form, mode)
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardRequisiteFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('Fix errors', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
setError(key as keyof CardRequisiteFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("Fix errors", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
if (mode === 'create') navigate('/card-requisites')
|
||||
else navigate(`/card-requisites/${initialData?.id}`)
|
||||
}
|
||||
if (mode === "create") navigate("/card-requisites");
|
||||
else navigate(`/card-requisites/${initialData?.id}`);
|
||||
};
|
||||
|
||||
// ── Submit ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)))
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const allErrors: FlatErrors = {}
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode))
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof CardRequisiteFormData, { type: 'manual', message: msg })
|
||||
})
|
||||
toast.error(t('Fix errors', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
setError(key as keyof CardRequisiteFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("Fix errors", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
||||
setCurrentStep(i)
|
||||
break
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
await createMutation.mutateAsync(payload)
|
||||
navigate('/card-requisites')
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/card-requisites");
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload)
|
||||
navigate(`/card-requisites/${initialData?.id}`)
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/card-requisites/${initialData?.id}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── StepBar items ──────────────────────────────────────────────────────────
|
||||
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep
|
||||
const hasErrors = stepsWithErrors.has(i)
|
||||
const isDone = visited.has(i) && !hasErrors
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
id: s.id,
|
||||
title: t(s.titleKey) || s.titleFallback,
|
||||
subtitle: t(s.subtitleKey) || s.subtitleFallback,
|
||||
icon: s.icon,
|
||||
status: isActive ? 'active' : hasErrors ? 'error' : isDone ? 'done' : 'idle',
|
||||
}
|
||||
})
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -577,13 +632,11 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
|
||||
{/* Page header */}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === 'create'
|
||||
? t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')
|
||||
: t('Edit card requisite', 'Kart rekwizitini üýtget')}
|
||||
{mode === "create"
|
||||
? t("Create card requisite order", "Kart rekwiziti üçin sargyt dörediň")
|
||||
: t("Edit card requisite", "Kart rekwizitini üýtget")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('common.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{t("common.form.subtitle", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}</p>
|
||||
</div>
|
||||
|
||||
{/* Step bar */}
|
||||
@@ -592,31 +645,28 @@ export function CardRequisiteForm({ mode, initialData }: CardRequisiteFormProps)
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && (
|
||||
<StepPassport {...stepProps} mode={mode} initialData={initialData} />
|
||||
)}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} mode={mode} initialData={initialData} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={currentStep === 0 ? handleCancel : undefined}
|
||||
cancelVariant="ghost"
|
||||
cancelLabel={t('Cancel', 'Ýatyr')}
|
||||
loadingLabel={t('Saving...', 'Saklanýar...')}
|
||||
cancelLabel={t("Cancel", "Ýatyr")}
|
||||
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
prevLabel={t('Back', 'Yza')}
|
||||
prevLabel={t("Back", "Yza")}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
nextLabel={t('Next', 'Indiki')}
|
||||
nextLabel={t("Next", "Indiki")}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? handleSubmit : undefined}
|
||||
submitLabel={
|
||||
mode === 'create'
|
||||
? t('Create card requisite order', 'Kart rekwiziti üçin sargyt dörediň')
|
||||
: t('Save changes', 'Üýtgetmeleri sakla')
|
||||
mode === "create"
|
||||
? t("Create card requisite order", "Kart rekwiziti üçin sargyt dörediň")
|
||||
: t("Save changes", "Üýtgetmeleri sakla")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,120 +1,74 @@
|
||||
import apiClient from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardTransaction {
|
||||
id: number
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
export interface Card {
|
||||
id: number;
|
||||
userId: number;
|
||||
number: string;
|
||||
name: string;
|
||||
month: string;
|
||||
year: string;
|
||||
type: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CardTransactionListResponse {
|
||||
data: CardTransaction[]
|
||||
total: number
|
||||
page: number
|
||||
per_page: number
|
||||
export interface CardListResponse {
|
||||
count: number;
|
||||
cards: Card[];
|
||||
}
|
||||
|
||||
export interface CreateCardTransactionPayload {
|
||||
passport_series: string
|
||||
passport_number: string
|
||||
card_number: string
|
||||
card_expiry_month: string
|
||||
card_expiry_year: string
|
||||
export interface CreateCardPayload {
|
||||
month: string;
|
||||
name: string;
|
||||
number: string;
|
||||
type: string;
|
||||
userId: number;
|
||||
year: string;
|
||||
}
|
||||
|
||||
export type UpdateCardTransactionPayload = CreateCardTransactionPayload
|
||||
export type UpdateCardPayload = CreateCardPayload;
|
||||
|
||||
export interface CardTransactionListParams {
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string
|
||||
export interface CardListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_TRANSACTIONS: CardTransaction[] = [
|
||||
{
|
||||
id: 1,
|
||||
passport_series: 'AA',
|
||||
passport_number: '1234567',
|
||||
card_number: '8600123456789012',
|
||||
card_expiry_month: '12',
|
||||
card_expiry_year: '28',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
passport_series: 'AB',
|
||||
passport_number: '7654321',
|
||||
card_number: '9860123456789012',
|
||||
card_expiry_month: '05',
|
||||
card_expiry_year: '27',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
passport_series: 'AC',
|
||||
passport_number: '1122334',
|
||||
card_number: '4400123456789012',
|
||||
card_expiry_month: '08',
|
||||
card_expiry_year: '26',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
passport_series: 'KA',
|
||||
passport_number: '9988776',
|
||||
card_number: '5300123456789012',
|
||||
card_expiry_month: '01',
|
||||
card_expiry_year: '30',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
passport_series: 'KB',
|
||||
passport_number: '5566778',
|
||||
card_number: '6200123456789012',
|
||||
card_expiry_month: '03',
|
||||
card_expiry_year: '29',
|
||||
},
|
||||
]
|
||||
|
||||
export const cardTransactionsApi = {
|
||||
getAll: async (params?: CardTransactionListParams): Promise<CardTransactionListResponse> => {
|
||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
||||
return { data: MOCK_CARD_TRANSACTIONS, total: MOCK_CARD_TRANSACTIONS.length, page: params?.page || 1, per_page: params?.per_page || 10 }
|
||||
|
||||
const { data } = await apiClient.get('/card-transactions', { params })
|
||||
return data
|
||||
/** GET /cards */
|
||||
getAll: async (params: CardListParams = {}, signal?: AbortSignal): Promise<CardListResponse> => {
|
||||
const { page, limit, search } = params;
|
||||
const { data } = await apiClient.get<CardListResponse>("/cards", {
|
||||
params: { page, limit, search },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<CardTransaction> => {
|
||||
// Mock data kullanmak için aşağıdaki satırı yorumdan çıkarabilirsiniz:
|
||||
const mock = MOCK_CARD_TRANSACTIONS.find(t => t.id === id)
|
||||
if (mock) return mock
|
||||
|
||||
const { data } = await apiClient.get(`/card-transactions/${id}`)
|
||||
return data
|
||||
/** GET /cards/:id */
|
||||
getById: async (id: number): Promise<Card> => {
|
||||
const { data } = await apiClient.get<Card>(`/cards/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (payload: CreateCardTransactionPayload): Promise<CardTransaction> => {
|
||||
const { data } = await apiClient.post('/card-transactions', payload)
|
||||
return data
|
||||
/** POST /cards */
|
||||
create: async (payload: CreateCardPayload): Promise<Card> => {
|
||||
const { data } = await apiClient.post<Card>("/cards", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: number, payload: UpdateCardTransactionPayload): Promise<CardTransaction> => {
|
||||
const { data } = await apiClient.put(`/card-transactions/${id}`, payload)
|
||||
return data
|
||||
/** PUT /cards/:id */
|
||||
update: async (id: number, payload: UpdateCardPayload): Promise<Card> => {
|
||||
const { data } = await apiClient.put<Card>(`/cards/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** DELETE /cards/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await apiClient.delete(`/card-transactions/${id}`)
|
||||
await apiClient.delete(`/cards/${id}`);
|
||||
},
|
||||
|
||||
download: async (id: number): Promise<Blob> => {
|
||||
const { data } = await apiClient.get(`/card-transactions/${id}/download`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
return data
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardTransaction } from "../api/cardTransactionsApi";
|
||||
import type { Card } from "../api/cardTransactionsApi";
|
||||
import { useCreateCardTransaction, useUpdateCardTransaction } from "../hooks/useCardTransactions";
|
||||
import { cardTransactionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardTransaction.schema";
|
||||
import type { CardTransactionFormData } from "../schemas/cardTransaction.schema";
|
||||
@@ -14,19 +14,11 @@ import type { CardTransactionFormData } from "../schemas/cardTransaction.schema"
|
||||
|
||||
interface CardTransactionFormProps {
|
||||
mode: "create" | "edit";
|
||||
initialData?: CardTransaction;
|
||||
initialData?: Card;
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const PASSPORT_SERIES_OPTIONS = [
|
||||
{ value: "I-LB", label: "I-LB" },
|
||||
{ value: "II-LB", label: "II-LB" },
|
||||
{ value: "III-LB", label: "III-LB" },
|
||||
{ value: "A", label: "A" },
|
||||
{ value: "B", label: "B" },
|
||||
];
|
||||
|
||||
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => {
|
||||
const val = String(i + 1).padStart(2, "0");
|
||||
return { value: val, label: val };
|
||||
@@ -64,7 +56,17 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
clearErrors,
|
||||
setError,
|
||||
} = useForm<CardTransactionFormData>({
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...initialData } : DEFAULT_FORM_VALUES,
|
||||
defaultValues: initialData
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
number: initialData.number,
|
||||
name: initialData.name,
|
||||
type: initialData.type,
|
||||
month: initialData.month,
|
||||
year: initialData.year,
|
||||
userId: String(initialData.userId),
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
const form = watch();
|
||||
@@ -112,33 +114,30 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create"
|
||||
? t("cardTransaction.createTitle", "Kart herekedi dörediň")
|
||||
: t("cardTransaction.editTitle", "Kart herekedi üýtgetmek")}
|
||||
{mode === "create" ? t("cardTransaction.createTitle", "Kart dörediň") : t("cardTransaction.editTitle", "Karty üýtgetmek")}
|
||||
</h1>
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Passport Series */}
|
||||
{/* Name */}
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Passport series", "Pasport seriýasy")}
|
||||
value={form.passport_series}
|
||||
onChange={setField("passport_series")}
|
||||
options={PASSPORT_SERIES_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.passport_series)}
|
||||
type="text"
|
||||
label={t("Card name", "Kartyň ady")}
|
||||
value={form.name}
|
||||
onChange={setField("name")}
|
||||
placeholder={t("Card name", "Kartyň ady")}
|
||||
error={errMsg(errors.name)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Passport Number */}
|
||||
{/* Type */}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport number", "Pasport belgisi")}
|
||||
value={form.passport_number}
|
||||
onChange={setField("passport_number")}
|
||||
placeholder={t("Passport number", "Pasport belgisi")}
|
||||
error={errMsg(errors.passport_number)}
|
||||
label={t("Card type", "Kart görnüşi")}
|
||||
value={form.type}
|
||||
onChange={setField("type")}
|
||||
placeholder={t("Card type", "Kart görnüşi")}
|
||||
error={errMsg(errors.type)}
|
||||
required
|
||||
/>
|
||||
|
||||
@@ -146,10 +145,21 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Card number", "Kart belgisi")}
|
||||
value={form.card_number}
|
||||
onChange={setField("card_number")}
|
||||
value={form.number}
|
||||
onChange={setField("number")}
|
||||
placeholder={t("Card number", "Kart belgisi")}
|
||||
error={errMsg(errors.card_number)}
|
||||
error={errMsg(errors.number)}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* User ID */}
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("User ID", "Ulanyjy ID")}
|
||||
value={form.userId}
|
||||
onChange={setField("userId")}
|
||||
placeholder={t("User ID", "Ulanyjy ID")}
|
||||
error={errMsg(errors.userId)}
|
||||
required
|
||||
/>
|
||||
|
||||
@@ -157,23 +167,23 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry month", "Kart Möhleti (aý)")}
|
||||
value={form.card_expiry_month}
|
||||
onChange={setField("card_expiry_month")}
|
||||
label={t("Card expiry month", "Kart möhleti (aý)")}
|
||||
value={form.month}
|
||||
onChange={setField("month")}
|
||||
options={MONTH_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_month)}
|
||||
error={errMsg(errors.month)}
|
||||
required
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Card expiry year", "Kart Möhleti (ýyl)")}
|
||||
value={form.card_expiry_year}
|
||||
onChange={setField("card_expiry_year")}
|
||||
label={t("Card expiry year", "Kart möhleti (ýyl)")}
|
||||
value={form.year}
|
||||
onChange={setField("year")}
|
||||
options={YEAR_OPTIONS}
|
||||
placeholder={t("Select to choose", "Saýlamak üçin basyň")}
|
||||
error={errMsg(errors.card_expiry_year)}
|
||||
error={errMsg(errors.year)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
@@ -183,12 +193,9 @@ export function CardTransactionForm({ mode, initialData }: CardTransactionFormPr
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
cancelLabel={t("Cancel", "Ýatyr")}
|
||||
loadingLabel={t("Saving...", "Saklanýar...")}
|
||||
submitLabel={
|
||||
mode === "create" ? t("Create card transaction", "Kart herekedi dörediň") : t("Save changes", "Üýtgetmeleri sakla")
|
||||
}
|
||||
submitLabel={mode === "create" ? t("Create card", "Kart dörediň") : t("Save changes", "Üýtgetmeleri sakla")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
@@ -1,98 +1,75 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
cardTransactionsApi,
|
||||
type CardTransactionListParams,
|
||||
type CreateCardTransactionPayload,
|
||||
type UpdateCardTransactionPayload,
|
||||
} from '../api/cardTransactionsApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { cardTransactionsApi, type CardListParams, type CreateCardPayload, type UpdateCardPayload } from "../api/cardTransactionsApi";
|
||||
|
||||
const QUERY_KEY = 'card-transactions'
|
||||
const QUERY_KEY = "cards";
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTransactions(params?: CardTransactionListParams) {
|
||||
export function useCardTransactions(params?: CardListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params?.search ?? "");
|
||||
const queryParams: CardListParams = { ...(params ?? {}), search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, params],
|
||||
queryFn: () => cardTransactionsApi.getAll(params),
|
||||
})
|
||||
queryKey: [QUERY_KEY, "list", queryParams],
|
||||
queryFn: ({ signal }) => cardTransactionsApi.getAll(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTransaction(id: number) {
|
||||
return useQuery({
|
||||
queryKey: [QUERY_KEY, id],
|
||||
queryKey: [QUERY_KEY, "detail", id],
|
||||
queryFn: () => cardTransactionsApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardTransaction() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardTransactionPayload) =>
|
||||
cardTransactionsApi.create(payload),
|
||||
mutationFn: (payload: CreateCardPayload) => cardTransactionsApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card transaction created successfully', 'Kart herekedi üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||
toast.success(t("Card transaction created successfully", "Kart üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardTransaction(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardTransactionPayload) =>
|
||||
cardTransactionsApi.update(id, payload),
|
||||
mutationFn: (payload: UpdateCardPayload) => cardTransactionsApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card transaction updated successfully', 'Kart herekedi üstünlikli üýtgedildi'))
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||
toast.success(t("Card transaction updated successfully", "Kart üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardTransaction() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => cardTransactionsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] })
|
||||
toast.success(t('Card transaction deleted successfully', 'Kart herekedi üstünlikli öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: [QUERY_KEY] });
|
||||
toast.success(t("Card transaction deleted successfully", "Kart üstünlikli öçürildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Download ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDownloadCardTransaction() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (id: number) => {
|
||||
const blob = await cardTransactionsApi.download(id)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `card-transaction-${id}.pdf`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t('Downloaded successfully', 'Üstünlikli ýüklenildi'))
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,30 +1,33 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardTransactionPayload } from '../api/cardTransactionsApi'
|
||||
import { z } from "zod";
|
||||
import type { CreateCardPayload } from "../api/cardTransactionsApi";
|
||||
|
||||
export const cardTransactionFormSchema = z.object({
|
||||
passport_series: z.string().min(1, 'validation.required'),
|
||||
passport_number: z.string().min(1, 'validation.required'),
|
||||
card_number: z.string().min(1, 'validation.required'),
|
||||
card_expiry_month: z.string().min(1, 'validation.required'),
|
||||
card_expiry_year: z.string().min(1, 'validation.required'),
|
||||
})
|
||||
number: z.string().min(1, "validation.required"),
|
||||
name: z.string().min(1, "validation.required"),
|
||||
type: z.string().min(1, "validation.required"),
|
||||
month: z.string().min(1, "validation.required"),
|
||||
year: z.string().min(1, "validation.required"),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
});
|
||||
|
||||
export type CardTransactionFormData = z.infer<typeof cardTransactionFormSchema>
|
||||
export type CardTransactionFormData = z.infer<typeof cardTransactionFormSchema>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardTransactionFormData = {
|
||||
passport_series: '',
|
||||
passport_number: '',
|
||||
card_number: '',
|
||||
card_expiry_month: '',
|
||||
card_expiry_year: '',
|
||||
}
|
||||
number: "",
|
||||
name: "",
|
||||
type: "",
|
||||
month: "",
|
||||
year: "",
|
||||
userId: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: CardTransactionFormData): CreateCardTransactionPayload {
|
||||
export function buildPayload(data: CardTransactionFormData): CreateCardPayload {
|
||||
return {
|
||||
passport_series: data.passport_series,
|
||||
passport_number: data.passport_number,
|
||||
card_number: data.card_number,
|
||||
card_expiry_month: data.card_expiry_month,
|
||||
card_expiry_year: data.card_expiry_year,
|
||||
}
|
||||
number: data.number,
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
month: data.month,
|
||||
year: data.year,
|
||||
userId: Number(data.userId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,107 +1,78 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LocalizedTitle {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
export interface CardType {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
id: number;
|
||||
price: string;
|
||||
title: LocalizedTitle;
|
||||
notes: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface CardTypeListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
isActive?: string;
|
||||
}
|
||||
|
||||
export interface CardTypeListResponse {
|
||||
data: CardType[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
count: number;
|
||||
paymentCards: CardType[];
|
||||
}
|
||||
|
||||
export interface CreateCardTypePayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
value: number
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
notes: string;
|
||||
price: string;
|
||||
title: LocalizedTitle;
|
||||
}
|
||||
|
||||
export interface UpdateCardTypePayload extends CreateCardTypePayload {
|
||||
id: number
|
||||
}
|
||||
|
||||
// ─── Mock Store ───────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_CARD_TYPES: CardType[] = [
|
||||
{ id: 1, name: { tk: 'Altyn Asyr', ru: 'Алтын Асыр', en: 'Altyn Asyr' }, value: 32, description: null, isActive: true },
|
||||
{ id: 2, name: { tk: 'Maşgala', ru: 'Семья', en: 'Family' }, value: 32, description: null, isActive: true },
|
||||
{ id: 3, name: { tk: 'Goýum', ru: 'Депозит', en: 'Deposit' }, value: 32, description: null, isActive: true },
|
||||
{ id: 4, name: { tk: 'Pensiýa', ru: 'Пенсия', en: 'Pension' }, value: 32, description: null, isActive: true },
|
||||
{ id: 5, name: { tk: 'Telekeçi', ru: 'Предприниматель', en: 'Entrepreneur' }, value: 32, description: null, isActive: true },
|
||||
{ id: 6, name: { tk: 'Karz', ru: 'Кредит', en: 'Credit' }, value: 32, description: null, isActive: false },
|
||||
{ id: 7, name: { tk: 'Owerdraft', ru: 'Овердрафт', en: 'Overdraft' }, value: 32, description: null, isActive: true },
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_CARD_TYPES]
|
||||
let nextId = 8
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
export type UpdateCardTypePayload = CreateCardTypePayload;
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardTypes(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}): Promise<CardTypeListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
return matchSearch && matchActive
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
export async function fetchCardTypes(params: CardTypeListParams = {}, signal?: AbortSignal): Promise<CardTypeListResponse> {
|
||||
const { page, limit, search, isActive } = params;
|
||||
const { data } = await apiClient.get<CardTypeListResponse>("/payment-cards", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
card_name: search || undefined,
|
||||
active: isActive || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchCardTypeById(id: number): Promise<CardType> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
const { data } = await apiClient.get<CardType>(`/payment-cards/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createCardType(payload: CreateCardTypePayload): Promise<CardType> {
|
||||
await delay(400)
|
||||
const newItem: CardType = { id: nextId++, ...payload }
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
const { data } = await apiClient.post<CardType>("/payment-cards", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateCardType(payload: UpdateCardTypePayload): Promise<CardType> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
export async function updateCardType(id: number, payload: UpdateCardTypePayload): Promise<CardType> {
|
||||
const { data } = await apiClient.put<CardType>(`/payment-cards/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteCardType(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
}
|
||||
await apiClient.delete(`/payment-cards/${id}`);
|
||||
}
|
||||
|
||||
export async function updateCardTypeActive(id: number, active: boolean): Promise<CardType> {
|
||||
const { data } = await apiClient.put<CardType>(`/payment-cards/${id}/active`, { active });
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { CardType } from "../api/cardTypesApi";
|
||||
import { useCreateCardType, useUpdateCardType } from "../hooks/useCardTypes";
|
||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/cardType.schema";
|
||||
import { createCardTypeFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/cardType.schema";
|
||||
import type { CardTypeFormData } from "../schemas/cardType.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -20,19 +20,6 @@ export interface CardTypeFormProps {
|
||||
initialData?: CardType;
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function mapInitial(data: CardType): CardTypeFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
value: String(data.value),
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof CardTypeFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
@@ -55,7 +42,7 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardType();
|
||||
const updateMutation = useUpdateCardType();
|
||||
const updateMutation = useUpdateCardType(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
@@ -76,6 +63,12 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
const set = useCallback(
|
||||
(key: keyof CardTypeFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof CardTypeFormData, v: string | boolean) => void)(key, value);
|
||||
@@ -84,26 +77,22 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => navigate("/settings/card/card-types"),
|
||||
});
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate({ id: initialData.id, ...payload }, { onSuccess: () => navigate("/settings/card/card-types") });
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/settings/card/card-types/${result.id}`);
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/settings/card/card-types/${initialData!.id}`);
|
||||
}
|
||||
}, [mode, initialData, createMutation, updateMutation, navigate, trigger, getValues]);
|
||||
};
|
||||
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk")(v), error: errors.nameTk },
|
||||
@@ -127,26 +116,27 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardTypes.fields.value", "Baha")}
|
||||
value={form.value}
|
||||
onChange={set("value")}
|
||||
placeholder={t("cardTypes.fields.value", "Baha")}
|
||||
error={errors.value}
|
||||
label={t("cardTypes.fields.price", "Baha")}
|
||||
value={form.price}
|
||||
onChange={set("price")}
|
||||
placeholder={t("cardTypes.fields.price", "Baha")}
|
||||
error={errors.price}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardTypes.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={set("description")}
|
||||
placeholder={t("cardTypes.fields.description", "Bellikler")}
|
||||
label={t("cardTypes.fields.notes", "Bellikler")}
|
||||
value={form.notes}
|
||||
onChange={set("notes")}
|
||||
placeholder={t("cardTypes.fields.notes", "Bellikler")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("cardTypes.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox checked={form.isActive} onCheckedChange={(checked) => set("isActive")(!!checked)} />
|
||||
<Checkbox checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -154,7 +144,6 @@ export function CardTypeForm({ mode, initialData }: CardTypeFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/settings/card/card-types")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create" ? t("cardTypes.actions.create", "Kart görnüşi döretdiň") : t("cardTypes.actions.update", "Täzelemek")
|
||||
}
|
||||
|
||||
@@ -1,92 +1,109 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchCardTypes,
|
||||
fetchCardTypeById,
|
||||
createCardType,
|
||||
updateCardType,
|
||||
updateCardTypeActive,
|
||||
deleteCardType,
|
||||
type CardTypeListParams,
|
||||
type CreateCardTypePayload,
|
||||
type UpdateCardTypePayload,
|
||||
} from '../api/cardTypesApi'
|
||||
} from "../api/cardTypesApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardTypeKeys = {
|
||||
all: ['cardTypes'] as const,
|
||||
lists: () => [...cardTypeKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...cardTypeKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...cardTypeKeys.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["cardTypes"] as const,
|
||||
lists: () => [...cardTypeKeys.all, "list"] as const,
|
||||
list: (params: CardTypeListParams) => [...cardTypeKeys.lists(), params] as const,
|
||||
details: () => [...cardTypeKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardTypeKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── useCardTypes ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTypes(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}) {
|
||||
export function useCardTypes(params: CardTypeListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: CardTypeListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: cardTypeKeys.list(params),
|
||||
queryFn: () => fetchCardTypes(params),
|
||||
})
|
||||
queryKey: cardTypeKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchCardTypes(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCardTypeById ──────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardTypeById(id: number) {
|
||||
export function useCardTypeById(id: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: cardTypeKeys.detail(id),
|
||||
queryFn: () => fetchCardTypeById(id),
|
||||
queryKey: cardTypeKeys.detail(id!),
|
||||
queryFn: () => fetchCardTypeById(id!),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardTypePayload) => createCardType(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
toast.success(t('cardTypes.toast.createSuccess', 'Kart görnüşi döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||
toast.success(t("cardTypes.toast.createSuccess", "Kart görnüşi döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
export function useUpdateCardType(id: number) {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardTypePayload) => updateCardType(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(data.id) })
|
||||
toast.success(t('cardTypes.toast.updateSuccess', 'Kart görnüşi täzelendi'))
|
||||
mutationFn: (payload: UpdateCardTypePayload) => updateCardType(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.detail(id) });
|
||||
toast.success(t("cardTypes.toast.updateSuccess", "Kart görnüşi täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateCardTypeActive ──────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardTypeActive() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, active }: { id: number; active: boolean }) => updateCardTypeActive(id, active),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||
toast.success(t("cardTypes.toast.statusUpdated", "Kart görnüşi statusy täzelendi!"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteCardType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteCardType(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() })
|
||||
toast.success(t('cardTypes.toast.deleteSuccess', 'Kart görnüşi öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: cardTypeKeys.lists() });
|
||||
toast.success(t("cardTypes.toast.deleteSuccess", "Kart görnüşi öçürildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,36 +1,46 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateCardTypePayload } from '../api/cardTypesApi'
|
||||
import { z } from "zod";
|
||||
import type { CardType, CreateCardTypePayload } from "../api/cardTypesApi";
|
||||
|
||||
export function createCardTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
value: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) >= 0,
|
||||
t('validation.invalidNumber', 'Dogry san giriziň'),
|
||||
),
|
||||
description: z.string().optional(),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
price: z
|
||||
.string()
|
||||
.refine((v) => v.trim() !== "" && !isNaN(Number(v)) && Number(v) >= 0, t("validation.invalidNumber", "Dogry san giriziň")),
|
||||
notes: z.string().optional(),
|
||||
active: z.boolean(),
|
||||
});
|
||||
}
|
||||
|
||||
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>
|
||||
export type CardTypeFormData = z.infer<ReturnType<typeof createCardTypeFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: CardTypeFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
value: '',
|
||||
description: '',
|
||||
isActive: true,
|
||||
}
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
price: "",
|
||||
notes: "",
|
||||
active: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: CardTypeFormData): CreateCardTypePayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
value: Number(data.value),
|
||||
description: (data.description ?? '').trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
title: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
price: data.price.trim(),
|
||||
notes: (data.notes ?? "").trim(),
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapInitial(data: CardType): CardTypeFormData {
|
||||
return {
|
||||
nameTk: data.title.tm,
|
||||
nameRu: data.title.ru,
|
||||
nameEn: data.title.en,
|
||||
price: data.price,
|
||||
notes: data.notes ?? "",
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -205,7 +205,6 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate(-1)}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
@@ -162,7 +162,6 @@ export function CurrencyRateForm({ mode, initialData }: CurrencyRateFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("currencyRates.actions.create", "Walýuta kursy dörediň")
|
||||
|
||||
@@ -1,99 +1,79 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||
|
||||
export interface LocalizedText {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
// ─── District (Province) ──────────────────────────────────────────────────────
|
||||
|
||||
export interface District {
|
||||
id: number
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
region: LocalizedText;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DistrictListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
active?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export interface DistrictListResponse {
|
||||
data: District[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
count: number;
|
||||
provinces: District[];
|
||||
}
|
||||
|
||||
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CreateDistrictPayload {
|
||||
name: Record<'tk' | 'ru' | 'en', string>
|
||||
description: string | null
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
name: LocalizedText;
|
||||
region: LocalizedText;
|
||||
}
|
||||
|
||||
export interface UpdateDistrictPayload extends CreateDistrictPayload {
|
||||
id: number
|
||||
id: number;
|
||||
}
|
||||
|
||||
const MOCK_DISTRICTS: District[] = [
|
||||
{ id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' }, description: null, isActive: true },
|
||||
{ id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' }, description: null, isActive: true },
|
||||
{ id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' }, description: null, isActive: true },
|
||||
{ id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' }, description: null, isActive: true },
|
||||
{ id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' }, description: null, isActive: true },
|
||||
{ id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' }, description: null, isActive: false },
|
||||
{ id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' }, description: null, isActive: true },
|
||||
]
|
||||
// ─── District CRUD ────────────────────────────────────────────────────────────
|
||||
|
||||
let mockStore = [...MOCK_DISTRICTS]
|
||||
let nextId = 8
|
||||
|
||||
const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
export async function fetchDistricts(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}): Promise<DistrictListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = mockStore.filter((item) => {
|
||||
const matchSearch =
|
||||
!search ||
|
||||
Object.values(item.name).some((n) =>
|
||||
n.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
const matchActive =
|
||||
isActive === '' || isActive === undefined
|
||||
? true
|
||||
: isActive === 'true'
|
||||
? item.isActive
|
||||
: !item.isActive
|
||||
return matchSearch && matchActive
|
||||
})
|
||||
|
||||
filtered = [...filtered].sort((a, b) => b.id - a.id)
|
||||
|
||||
const total = filtered.length
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage }
|
||||
export async function fetchDistricts(params: DistrictListParams = {}): Promise<DistrictListResponse> {
|
||||
const { page, limit, search, active, region } = params;
|
||||
const { data } = await apiClient.get<DistrictListResponse>("/provinces", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
name: search || undefined,
|
||||
region: region || undefined,
|
||||
active: active || undefined,
|
||||
},
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchDistrictById(id: number): Promise<District> {
|
||||
await delay()
|
||||
const item = mockStore.find((c) => c.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { ...item }
|
||||
const { data } = await apiClient.get<District>(`/provinces/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createDistrict(payload: CreateDistrictPayload): Promise<District> {
|
||||
await delay(400)
|
||||
const newItem: District = { id: nextId++, ...payload }
|
||||
mockStore = [newItem, ...mockStore]
|
||||
return newItem
|
||||
const { data } = await apiClient.post<District>("/provinces", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateDistrict(payload: UpdateDistrictPayload): Promise<District> {
|
||||
await delay(400)
|
||||
const idx = mockStore.findIndex((c) => c.id === payload.id)
|
||||
if (idx === -1) throw new Error('Not found')
|
||||
const updated = { ...mockStore[idx], ...payload }
|
||||
mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c))
|
||||
return updated
|
||||
const { id, ...rest } = payload;
|
||||
const { data } = await apiClient.put<District>(`/provinces/${id}`, rest);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteDistrict(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
await apiClient.delete(`/provinces/${id}`);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { District } from "../api/districtsApi";
|
||||
@@ -31,11 +30,13 @@ export interface DistrictFormProps {
|
||||
|
||||
function mapInitial(data: District): DistrictFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameTk: data.name.tm,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
description: data.description ?? "",
|
||||
isActive: data.isActive,
|
||||
regionTk: data.region.tm,
|
||||
regionRu: data.region.ru,
|
||||
regionEn: data.region.en,
|
||||
isActive: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -105,6 +106,12 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
||||
en: { value: form.nameEn, onChange: set("nameEn"), error: errors.nameEn },
|
||||
};
|
||||
|
||||
const regionFields = {
|
||||
tk: { value: form.regionTk, onChange: set("regionTk"), error: errors.regionTk },
|
||||
ru: { value: form.regionRu, onChange: set("regionRu"), error: errors.regionRu },
|
||||
en: { value: form.regionEn, onChange: set("regionEn"), error: errors.regionEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
@@ -118,14 +125,12 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("districts.fields.name", "Ady")} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("districts.fields.description", "Bellikler")}
|
||||
value={form.description}
|
||||
onChange={set("description")}
|
||||
placeholder={t("districts.fields.description", "Bellikler")}
|
||||
/>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("districts.fields.region", "Region")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<MultiLangInput fields={regionFields} placeholder={t("districts.fields.region", "Region")} />
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-3 pt-1">
|
||||
@@ -138,7 +143,6 @@ export function DistrictForm({ mode, initialData }: DistrictFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/settings/location/districts")}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === "create" ? t("districts.actions.create", "Etrap döret") : t("districts.actions.update", "Täzelemek")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,34 +1,29 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
fetchDistricts,
|
||||
fetchDistrictById,
|
||||
createDistrict,
|
||||
updateDistrict,
|
||||
deleteDistrict,
|
||||
type DistrictListParams,
|
||||
type CreateDistrictPayload,
|
||||
type UpdateDistrictPayload,
|
||||
} from '../api/districtsApi'
|
||||
} from "../api/districtsApi";
|
||||
|
||||
export const districtKeys = {
|
||||
all: ['districts'] as const,
|
||||
lists: () => [...districtKeys.all, 'list'] as const,
|
||||
list: (params: Record<string, unknown>) =>
|
||||
[...districtKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...districtKeys.all, 'detail', id] as const,
|
||||
}
|
||||
all: ["districts"] as const,
|
||||
lists: () => [...districtKeys.all, "list"] as const,
|
||||
list: (params: DistrictListParams) => [...districtKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...districtKeys.all, "detail", id] as const,
|
||||
};
|
||||
|
||||
export function useDistricts(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
}) {
|
||||
export function useDistricts(params: DistrictListParams) {
|
||||
return useQuery({
|
||||
queryKey: districtKeys.list(params),
|
||||
queryFn: () => fetchDistricts(params),
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDistrictById(id: number) {
|
||||
@@ -36,45 +31,45 @@ export function useDistrictById(id: number) {
|
||||
queryKey: districtKeys.detail(id),
|
||||
queryFn: () => fetchDistrictById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateDistrict() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateDistrictPayload) => createDistrict(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
||||
toast.success(t('districts.toast.createSuccess', 'Etrap döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||
toast.success(t("districts.toast.createSuccess", "Etrap döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateDistrict() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateDistrictPayload) => updateDistrict(payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.detail(data.id) })
|
||||
toast.success(t('districts.toast.updateSuccess', 'Etrap täzelendi'))
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.detail(data.id) });
|
||||
toast.success(t("districts.toast.updateSuccess", "Etrap täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteDistrict() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteDistrict(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() })
|
||||
toast.success(t('districts.toast.deleteSuccess', 'Etrap öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: districtKeys.lists() });
|
||||
toast.success(t("districts.toast.deleteSuccess", "Etrap öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,30 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateDistrictPayload } from '../api/districtsApi'
|
||||
import { z } from "zod";
|
||||
import type { CreateDistrictPayload } from "../api/districtsApi";
|
||||
|
||||
export function createDistrictFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
description: z.string().optional(),
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
regionTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
regionRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
regionEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>
|
||||
export type DistrictFormData = z.infer<ReturnType<typeof createDistrictFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: DistrictFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
description: '',
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
regionTk: "",
|
||||
regionRu: "",
|
||||
regionEn: "",
|
||||
isActive: true,
|
||||
}
|
||||
};
|
||||
|
||||
export function buildPayload(data: DistrictFormData): CreateDistrictPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
description: data.description?.trim() || null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
name: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
region: { tm: data.regionTk.trim(), ru: data.regionRu.trim(), en: data.regionEn.trim() },
|
||||
active: data.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,109 +2,106 @@ import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type LoanPaidOffLetterStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export interface LoanPaidOffLetter {
|
||||
id: number;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
loanAccount: string;
|
||||
issuedAt: string;
|
||||
uniqueId: string;
|
||||
region: string;
|
||||
branchId: number | null;
|
||||
userId: number | null;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string;
|
||||
bornAt: string;
|
||||
phone: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
status: LoanPaidOffLetterStatus;
|
||||
notes: string;
|
||||
loanContractNumber: string;
|
||||
loanContractDate: string;
|
||||
loanAmount: string;
|
||||
loanReason: string;
|
||||
loanFile: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type LoanPaidOffLetterPayload = Omit<LoanPaidOffLetter, "id">;
|
||||
export interface LoanPaidOffLetterPayload {
|
||||
bornAt: string;
|
||||
branchId: number;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
loanAmount: string;
|
||||
loanContractDate: string;
|
||||
loanContractNumber: string;
|
||||
loanFile: string;
|
||||
loanReason: string;
|
||||
notes: string;
|
||||
passportId: string;
|
||||
passportSerie: string;
|
||||
phone: string;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface LoanPaidOffLetterListParams {
|
||||
search?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
limit?: number;
|
||||
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||
passport_id?: string;
|
||||
status?: string;
|
||||
branch_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const USE_MOCK = true;
|
||||
|
||||
const MOCK_DATA: LoanPaidOffLetter[] = [
|
||||
{ id: 1, passportSeries: "TM", passportNumber: "A123456", loanAccount: "LOAN-2024-001", issuedAt: "2025-01-10" },
|
||||
{ id: 2, passportSeries: "TM", passportNumber: "B234567", loanAccount: "LOAN-2024-002", issuedAt: "2025-01-14" },
|
||||
{ id: 3, passportSeries: "TM", passportNumber: "C345678", loanAccount: "LOAN-2024-003", issuedAt: "2025-01-17" },
|
||||
{ id: 4, passportSeries: "TM", passportNumber: "D456789", loanAccount: "LOAN-2023-115", issuedAt: "2025-01-20" },
|
||||
{ id: 5, passportSeries: "TM", passportNumber: "E567890", loanAccount: "LOAN-2023-116", issuedAt: "2025-01-23" },
|
||||
{ id: 6, passportSeries: "TM", passportNumber: "F678901", loanAccount: "LOAN-2024-044", issuedAt: "2025-01-27" },
|
||||
{ id: 7, passportSeries: "TM", passportNumber: "G789012", loanAccount: "LOAN-2024-055", issuedAt: "2025-02-01" },
|
||||
{ id: 8, passportSeries: "TM", passportNumber: "H890123", loanAccount: "LOAN-2024-066", issuedAt: "2025-02-05" },
|
||||
{ id: 9, passportSeries: "TM", passportNumber: "I901234", loanAccount: "LOAN-2024-077", issuedAt: "2025-02-09" },
|
||||
{ id: 10, passportSeries: "TM", passportNumber: "J012345", loanAccount: "LOAN-2024-088", issuedAt: "2025-02-12" },
|
||||
];
|
||||
|
||||
function applyMockFilters(params: LoanPaidOffLetterListParams): PaginatedResponse<LoanPaidOffLetter> {
|
||||
let result = [...MOCK_DATA];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter((r) => r.passportNumber.toLowerCase().includes(q) || r.loanAccount.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const total = result.length;
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
export interface LoanPaidOffLetterListResponse {
|
||||
count: number;
|
||||
loanPaidLetters: LoanPaidOffLetter[];
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanPaidOffLetters(params: LoanPaidOffLetterListParams): Promise<PaginatedResponse<LoanPaidOffLetter>> {
|
||||
if (USE_MOCK) return applyMockFilters(params);
|
||||
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanPaidOffLetter>>("/loan-paid-off-letter-orders", { params });
|
||||
export async function fetchLoanPaidOffLetters(
|
||||
params: LoanPaidOffLetterListParams = {},
|
||||
signal?: AbortSignal,
|
||||
): Promise<LoanPaidOffLetterListResponse> {
|
||||
const { page, limit, search, passport_id, status, branch_id, region } = params;
|
||||
const { data } = await apiClient.get<LoanPaidOffLetterListResponse>("/loan-paid-off-letters", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
customer_name: search || undefined,
|
||||
passport_id: passport_id || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanPaidOffLetter(id: number): Promise<void> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1);
|
||||
return;
|
||||
}
|
||||
await apiClient.delete(`/loan-paid-off-letter-orders/${id}`);
|
||||
}
|
||||
|
||||
export async function fetchLoanPaidOffLetterById(id: number): Promise<LoanPaidOffLetter> {
|
||||
if (USE_MOCK) {
|
||||
const item = MOCK_DATA.find((r) => r.id === id);
|
||||
if (!item) throw new Error("Not found");
|
||||
return item;
|
||||
}
|
||||
const { data } = await apiClient.get<LoanPaidOffLetter>(`/loan-paid-off-letter-orders/${id}`);
|
||||
const { data } = await apiClient.get<LoanPaidOffLetter>(`/loan-paid-off-letters/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createLoanPaidOffLetter(payload: LoanPaidOffLetterPayload): Promise<LoanPaidOffLetter> {
|
||||
if (USE_MOCK) {
|
||||
const newItem: LoanPaidOffLetter = {
|
||||
id: Math.max(0, ...MOCK_DATA.map((d) => d.id)) + 1,
|
||||
...payload,
|
||||
};
|
||||
MOCK_DATA.unshift(newItem);
|
||||
return newItem;
|
||||
}
|
||||
const { data } = await apiClient.post<LoanPaidOffLetter>("/loan-paid-off-letter-orders", payload);
|
||||
const { data } = await apiClient.post<LoanPaidOffLetter>("/loan-paid-off-letters", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateLoanPaidOffLetter(id: number, payload: LoanPaidOffLetterPayload): Promise<LoanPaidOffLetter> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx === -1) throw new Error("Not found");
|
||||
const updated = { ...MOCK_DATA[idx], ...payload };
|
||||
MOCK_DATA[idx] = updated;
|
||||
return updated;
|
||||
}
|
||||
const { data } = await apiClient.put<LoanPaidOffLetter>(`/loan-paid-off-letter-orders/${id}`, payload);
|
||||
const { data } = await apiClient.put<LoanPaidOffLetter>(`/loan-paid-off-letters/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanPaidOffLetter(id: number): Promise<void> {
|
||||
await apiClient.delete(`/loan-paid-off-letters/${id}`);
|
||||
}
|
||||
|
||||
@@ -1,143 +1,503 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useForm, type PathValue } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { User, FileText, Wallet, MapPin } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormInput, type SelectOption } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
|
||||
import { useCreateLoanPaidOffLetter, useUpdateLoanPaidOffLetter } from "../hooks/useLoanPaidOffLetters";
|
||||
import type { LoanPaidOffLetter } from "../api/loanPaidOffLettersApi";
|
||||
import {
|
||||
loanPaidOffLetterFormSchema,
|
||||
validateStep,
|
||||
type LoanPaidOffLetterFormData,
|
||||
DEFAULT_FORM_VALUES,
|
||||
buildPayload,
|
||||
mapInitial,
|
||||
} from "../schemas/loanPaidOffLetter.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type FormMode = "create" | "edit";
|
||||
|
||||
interface LoanPaidOffLetterFormProps {
|
||||
mode: "create" | "edit";
|
||||
mode: FormMode;
|
||||
initialData?: LoanPaidOffLetter;
|
||||
}
|
||||
|
||||
type FlatErrors = Partial<Record<keyof LoanPaidOffLetterFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof LoanPaidOffLetterFormData] = msg;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Static options ───────────────────────────────────────────────────────────
|
||||
|
||||
const REGION_CODES = ["AG", "AH", "BA", "DA", "LE", "MA"] as const;
|
||||
|
||||
// ─── Step definitions ─────────────────────────────────────────────────────────
|
||||
|
||||
interface StepDef {
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: LoanPaidOffLetterFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: "customer",
|
||||
titleKey: "loanPaidOffLetters.sections.customer",
|
||||
titleFallback: "Müşderi maglumatlary",
|
||||
subtitleKey: "loanPaidOffLetters.steps.customer.subtitle",
|
||||
subtitleFallback: "At, familiýa, senesi, telefon",
|
||||
icon: User,
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
titleKey: "loanPaidOffLetters.sections.passport",
|
||||
titleFallback: "Pasport",
|
||||
subtitleKey: "loanPaidOffLetters.steps.passport.subtitle",
|
||||
subtitleFallback: "Seriýa we belgisi",
|
||||
icon: FileText,
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: "loan",
|
||||
titleKey: "loanPaidOffLetters.sections.loan",
|
||||
titleFallback: "Karz maglumatlary",
|
||||
subtitleKey: "loanPaidOffLetters.steps.loan.subtitle",
|
||||
subtitleFallback: "Şertnama, senesi, möçberi",
|
||||
icon: Wallet,
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
{
|
||||
id: "location",
|
||||
titleKey: "loanPaidOffLetters.sections.additional",
|
||||
titleFallback: "Lokasiýa we Status",
|
||||
subtitleKey: "loanPaidOffLetters.steps.additional.subtitle",
|
||||
subtitleFallback: "Sebit, şahamça, status",
|
||||
icon: MapPin,
|
||||
validate: (form) => validateStep(3, form),
|
||||
},
|
||||
];
|
||||
|
||||
// ─── Step components ──────────────────────────────────────────────────────────
|
||||
|
||||
interface StepContentProps {
|
||||
form: LoanPaidOffLetterFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof LoanPaidOffLetterFormData>(k: K) => (v: string) => void;
|
||||
t: TFunction;
|
||||
}
|
||||
|
||||
function StepCustomer({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.customerName", "Ady")}
|
||||
value={form.customerName}
|
||||
onChange={set("customerName")}
|
||||
error={errors.customerName}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.customerSurname", "Familiýasy")}
|
||||
value={form.customerSurname}
|
||||
onChange={set("customerSurname")}
|
||||
error={errors.customerSurname}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName ?? ""}
|
||||
onChange={set("customerPatronicName")}
|
||||
/>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("loanPaidOffLetters.fields.bornAt", "Doglan senesi")}
|
||||
value={form.bornAt}
|
||||
onChange={set("bornAt")}
|
||||
error={errors.bornAt}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("loanPaidOffLetters.fields.phone", "Telefon")}
|
||||
value={form.phone}
|
||||
onChange={set("phone")}
|
||||
error={errors.phone}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.passportSerie", "Pasport seriýasy")}
|
||||
value={form.passportSerie}
|
||||
onChange={set("passportSerie")}
|
||||
placeholder="I-AG"
|
||||
error={errors.passportSerie}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.passportId", "Pasport belgisi")}
|
||||
value={form.passportId}
|
||||
onChange={set("passportId")}
|
||||
placeholder="101010"
|
||||
error={errors.passportId}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
);
|
||||
}
|
||||
|
||||
function StepLoan({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.loanContractNumber", "Karz şertnamasy belgisi")}
|
||||
value={form.loanContractNumber}
|
||||
onChange={set("loanContractNumber")}
|
||||
error={errors.loanContractNumber}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("loanPaidOffLetters.fields.loanContractDate", "Karz şertnamasy senesi")}
|
||||
value={form.loanContractDate}
|
||||
onChange={set("loanContractDate")}
|
||||
error={errors.loanContractDate}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("loanPaidOffLetters.fields.loanAmount", "Karz möçberi")}
|
||||
value={form.loanAmount}
|
||||
onChange={set("loanAmount")}
|
||||
error={errors.loanAmount}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.loanReason", "Karz sebäbi")}
|
||||
value={form.loanReason ?? ""}
|
||||
onChange={set("loanReason")}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
);
|
||||
}
|
||||
|
||||
function StepLocation({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
regionOptions,
|
||||
statusOptions,
|
||||
}: StepContentProps & { regionOptions: SelectOption[]; statusOptions: SelectOption[] }) {
|
||||
return (
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("loanPaidOffLetters.fields.region", "Sebit")}
|
||||
value={form.region}
|
||||
onChange={set("region")}
|
||||
options={regionOptions}
|
||||
error={errors.region}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("loanPaidOffLetters.fields.branchId", "Şahamça ID")}
|
||||
value={form.branchId}
|
||||
onChange={set("branchId")}
|
||||
error={errors.branchId}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("loanPaidOffLetters.fields.userId", "Ulanyjy ID")}
|
||||
value={form.userId ?? ""}
|
||||
onChange={set("userId")}
|
||||
/>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("loanPaidOffLetters.fields.status", "Status")}
|
||||
value={form.status}
|
||||
onChange={set("status")}
|
||||
options={statusOptions}
|
||||
error={errors.status}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.uniqueId", "Unikal ID")}
|
||||
value={form.uniqueId ?? ""}
|
||||
onChange={set("uniqueId")}
|
||||
placeholder="LPL-2026-0001"
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanPaidOffLetters.fields.loanFile", "Faýl")}
|
||||
value={form.loanFile ?? ""}
|
||||
onChange={set("loanFile")}
|
||||
placeholder="letter1.pdf"
|
||||
/>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("loanPaidOffLetters.fields.notes", "Bellikler")}
|
||||
value={form.notes ?? ""}
|
||||
onChange={set("notes")}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── LoanPaidOffLetterForm ────────────────────────────────────────────────────
|
||||
|
||||
export function LoanPaidOffLetterForm({ mode, initialData }: LoanPaidOffLetterFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateLoanPaidOffLetter();
|
||||
const updateMutation = useUpdateLoanPaidOffLetter(initialData?.id ?? 0);
|
||||
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>([0])));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(() => new Set());
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
reset,
|
||||
formState: { errors },
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
setError,
|
||||
getValues,
|
||||
} = useForm<LoanPaidOffLetterFormData>({
|
||||
resolver: zodResolver(loanPaidOffLetterFormSchema),
|
||||
defaultValues: DEFAULT_FORM_VALUES,
|
||||
mode: "onSubmit",
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "edit" && initialData) {
|
||||
reset({
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
issuedAt: initialData.issuedAt,
|
||||
});
|
||||
}
|
||||
}, [mode, initialData, reset]);
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const onSubmit = (data: LoanPaidOffLetterFormData) => {
|
||||
const payload = buildPayload(data);
|
||||
const set = useCallback(
|
||||
<K extends keyof LoanPaidOffLetterFormData>(key: K) =>
|
||||
(value: string) => {
|
||||
setValue(key, value as PathValue<LoanPaidOffLetterFormData, K>);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const statusOptions = useMemo<SelectOption[]>(
|
||||
() => [
|
||||
{ value: "pending", label: t("loanPaidOffLetters.status.pending", "Pending") },
|
||||
{ value: "approved", label: t("loanPaidOffLetters.status.approved", "Approved") },
|
||||
{ value: "rejected", label: t("loanPaidOffLetters.status.rejected", "Rejected") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const regionOptions = useMemo<SelectOption[]>(
|
||||
() =>
|
||||
REGION_CODES.map((code) => ({
|
||||
value: code,
|
||||
label: t(`loanPaidOffLetters.regions.${code}`, code),
|
||||
})),
|
||||
[t],
|
||||
);
|
||||
|
||||
// ── Step validation state ───────────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const set = new Set<number>();
|
||||
STEPS.forEach((step, i) => {
|
||||
if (visited.has(i) || submittedSteps.has(i)) {
|
||||
const stepErrs = step.validate(form);
|
||||
if (Object.keys(stepErrs).length > 0) set.add(i);
|
||||
}
|
||||
});
|
||||
return set;
|
||||
}, [form, visited, submittedSteps]);
|
||||
|
||||
const markVisited = (idx: number) => setVisited((prev) => new Set([...prev, idx]));
|
||||
|
||||
// ── Step Navigation ─────────────────────────────────────────────────────────
|
||||
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep);
|
||||
setSubmittedSteps((prev) => new Set([...prev, currentStep]));
|
||||
|
||||
const stepErrs = STEPS[currentStep].validate(form);
|
||||
if (Object.keys(stepErrs).length > 0) {
|
||||
Object.entries(stepErrs).forEach(([key, msg]) => {
|
||||
setError(key as keyof LoanPaidOffLetterFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const doSubmit = async () => {
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
setError(key as keyof LoanPaidOffLetterFormData, { type: "manual", message: msg });
|
||||
});
|
||||
toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň"));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t("common.success.create", "Üstünlikli döredildi"));
|
||||
navigate("/loan-paid-off-letters");
|
||||
},
|
||||
});
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/loan-paid-off-letters/${result.id}`);
|
||||
} else {
|
||||
updateMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t("common.success.save", "Üstünlikli ýatda saklandy"));
|
||||
navigate("/loan-paid-off-letters");
|
||||
},
|
||||
});
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/loan-paid-off-letters/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const errMsg = (msg: string | undefined) => (msg?.startsWith("validation.") ? t(msg, msg) : msg);
|
||||
// ── StepBar items ───────────────────────────────────────────────────────────
|
||||
|
||||
const onError = () => {
|
||||
toast.error(t("common.errors.fillRequired", "Hökman doldurylmaly öýjükleri dolduryň"));
|
||||
};
|
||||
const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
|
||||
const isActive = i === currentStep;
|
||||
const hasErrors = stepsWithErrors.has(i);
|
||||
const isDone = visited.has(i) && !hasErrors;
|
||||
return {
|
||||
id: s.id,
|
||||
title: t(s.titleKey, s.titleFallback),
|
||||
subtitle: t(s.subtitleKey, s.subtitleFallback),
|
||||
icon: s.icon,
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1;
|
||||
|
||||
const stepProps = { form, errors, set, t };
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create"
|
||||
? t("loanPaidOffLetters.createTitle", "Karzyň ýapylandygy barada güwanama almak dörediň")
|
||||
: t("loanPaidOffLetters.editTitle", "Karzyň ýapylandygy barada güwanama almak üýtgetmek")}
|
||||
</h1>
|
||||
<form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-6">
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.passportSeries", "Pasport seriýasy")}
|
||||
required
|
||||
value={watch("passportSeries")}
|
||||
onChange={(v) => setValue("passportSeries", v)}
|
||||
placeholder={t("loanPaidOffLetters.placeholders.passportSeries", "TM")}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
/>
|
||||
{/* Page Header */}
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{mode === "create"
|
||||
? t("loanPaidOffLetters.createTitle", "Karzyň ýapylandygy barada güwanama almak dörediň")
|
||||
: t("loanPaidOffLetters.editTitle", "Karzyň ýapylandygy barada güwanama almak üýtgetmek")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t("loanPaidOffLetters.stepDescription", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.passportNumber", "Pasport belgisi")}
|
||||
required
|
||||
value={watch("passportNumber")}
|
||||
onChange={(v) => setValue("passportNumber", v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
/>
|
||||
{/* Step Bar */}
|
||||
<div className="bg-card border border-border rounded-xl p-3 overflow-x-auto">
|
||||
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.loanAccount", "Karz hasaby")}
|
||||
required
|
||||
value={watch("loanAccount")}
|
||||
onChange={(v) => setValue("loanAccount", v)}
|
||||
placeholder="LOAN-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
{/* Step Panels */}
|
||||
{currentStep === 0 && <StepCustomer {...stepProps} />}
|
||||
{currentStep === 1 && <StepPassport {...stepProps} />}
|
||||
{currentStep === 2 && <StepLoan {...stepProps} />}
|
||||
{currentStep === 3 && <StepLocation {...stepProps} regionOptions={regionOptions} statusOptions={statusOptions} />}
|
||||
|
||||
<FormInput
|
||||
label={t("loanPaidOffLetters.columns.issuedAt", "Berlen wagty")}
|
||||
required
|
||||
type="date"
|
||||
value={watch("issuedAt")}
|
||||
onChange={(v) => setValue("issuedAt", v)}
|
||||
error={errMsg(errors.issuedAt?.message)}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit(onSubmit, onError)}
|
||||
onCancel={() => navigate("/loan-paid-off-letters")}
|
||||
submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")}
|
||||
/>
|
||||
</form>
|
||||
{/* Form Actions */}
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onCancel={currentStep === 0 ? () => navigate("/loan-paid-off-letters") : undefined}
|
||||
onPrev={currentStep > 0 ? handleBack : undefined}
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={mode === "create" ? t("common.create", "Döret") : t("common.save", "Ýatda sakla")}
|
||||
loadingLabel={t("common.loading", "Ýüklenilýär...")}
|
||||
cancelLabel={t("common.cancel", "Ýatyr")}
|
||||
prevLabel={t("common.back", "Yza")}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
|
||||
import {
|
||||
fetchLoanPaidOffLetters,
|
||||
@@ -10,39 +11,42 @@ import {
|
||||
updateLoanPaidOffLetter,
|
||||
type LoanPaidOffLetterListParams,
|
||||
type LoanPaidOffLetterPayload,
|
||||
} from '../api/loanPaidOffLettersApi'
|
||||
} from "../api/loanPaidOffLettersApi";
|
||||
|
||||
// ─── Query keys ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const loanPaidOffLetterKeys = {
|
||||
all: ['loanPaidOffLetters'] as const,
|
||||
lists: () => [...loanPaidOffLetterKeys.all, 'list'] as const,
|
||||
list: (params: LoanPaidOffLetterListParams) =>
|
||||
[...loanPaidOffLetterKeys.lists(), params] as const,
|
||||
details: () => [...loanPaidOffLetterKeys.all, 'detail'] as const,
|
||||
all: ["loanPaidOffLetters"] as const,
|
||||
lists: () => [...loanPaidOffLetterKeys.all, "list"] as const,
|
||||
list: (params: LoanPaidOffLetterListParams) => [...loanPaidOffLetterKeys.lists(), params] as const,
|
||||
details: () => [...loanPaidOffLetterKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...loanPaidOffLetterKeys.details(), id] as const,
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Hooks ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useLoanPaidOffLetters(params: LoanPaidOffLetterListParams) {
|
||||
export function useLoanPaidOffLetters(params: LoanPaidOffLetterListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: LoanPaidOffLetterListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: loanPaidOffLetterKeys.list(params),
|
||||
queryFn: () => fetchLoanPaidOffLetters(params),
|
||||
})
|
||||
queryKey: loanPaidOffLetterKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchLoanPaidOffLetters(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteLoanPaidOffLetter() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteLoanPaidOffLetter(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() })
|
||||
toast.success(t('loanPaidOffLetters.deleteSuccess', 'Güwanama üstünlikli pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() });
|
||||
toast.success(t("loanPaidOffLetters.deleteSuccess", "Güwanama üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useLoanPaidOffLetterById(id?: string) {
|
||||
@@ -50,32 +54,32 @@ export function useLoanPaidOffLetterById(id?: string) {
|
||||
queryKey: loanPaidOffLetterKeys.detail(Number(id)),
|
||||
queryFn: () => fetchLoanPaidOffLetterById(Number(id)),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateLoanPaidOffLetter() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanPaidOffLetterPayload) => createLoanPaidOffLetter(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() })
|
||||
toast.success(t('loanPaidOffLetters.createSuccess', 'Üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() });
|
||||
toast.success(t("loanPaidOffLetters.createSuccess", "Üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateLoanPaidOffLetter(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanPaidOffLetterPayload) => updateLoanPaidOffLetter(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.detail(id) })
|
||||
toast.success(t('loanPaidOffLetters.updateSuccess', 'Üstünlikli üýtgedildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: loanPaidOffLetterKeys.detail(id) });
|
||||
toast.success(t("loanPaidOffLetters.updateSuccess", "Üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,28 +1,162 @@
|
||||
import { z } from 'zod'
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import { formatToApiDate, formatFromApiDate, formatToApiPhone, formatFromApiPhone } from "@/lib/utils";
|
||||
import type { LoanPaidOffLetter, LoanPaidOffLetterPayload } from "../api/loanPaidOffLettersApi";
|
||||
|
||||
export const loanPaidOffLetterFormSchema = z.object({
|
||||
passportSeries: z.string().min(1, 'validation.required'),
|
||||
passportNumber: z.string().min(1, 'validation.required'),
|
||||
loanAccount: z.string().min(1, 'validation.required'),
|
||||
issuedAt: z.string().min(1, 'validation.required'),
|
||||
})
|
||||
export function createLoanPaidOffLetterFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
customerName: z.string().min(1, t("validation.required", "validation.required")),
|
||||
customerSurname: z.string().min(1, t("validation.required", "validation.required")),
|
||||
customerPatronicName: z.string().optional(),
|
||||
bornAt: z.string().min(1, t("validation.required", "validation.required")),
|
||||
phone: z.string().min(1, t("validation.required", "validation.required")),
|
||||
passportSerie: z.string().min(1, t("validation.required", "validation.required")),
|
||||
passportId: z.string().min(1, t("validation.required", "validation.required")),
|
||||
region: z.string().min(1, t("validation.required", "validation.required")),
|
||||
branchId: z.string().refine((v) => v.trim() !== "" && !isNaN(Number(v)), t("validation.required", "validation.required")),
|
||||
userId: z.string().optional(),
|
||||
status: z.string().min(1, t("validation.required", "validation.required")),
|
||||
notes: z.string().optional(),
|
||||
loanContractNumber: z.string().min(1, t("validation.required", "validation.required")),
|
||||
loanContractDate: z.string().min(1, t("validation.required", "validation.required")),
|
||||
loanAmount: z.string().min(1, t("validation.required", "validation.required")),
|
||||
loanReason: z.string().optional(),
|
||||
uniqueId: z.string().optional(),
|
||||
loanFile: z.string().optional(),
|
||||
});
|
||||
}
|
||||
|
||||
export type LoanPaidOffLetterFormData = z.infer<typeof loanPaidOffLetterFormSchema>
|
||||
export const baseLoanPaidOffLetterSchema = z.object({
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: z.string().optional(),
|
||||
bornAt: z.string().min(1, "validation.required"),
|
||||
phone: z.string().min(1, "validation.required"),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().refine((v) => v.trim() !== "" && !isNaN(Number(v)), "validation.required"),
|
||||
userId: z.string().optional(),
|
||||
status: z.string().min(1, "validation.required"),
|
||||
notes: z.string().optional(),
|
||||
loanContractNumber: z.string().min(1, "validation.required"),
|
||||
loanContractDate: z.string().min(1, "validation.required"),
|
||||
loanAmount: z.string().min(1, "validation.required"),
|
||||
loanReason: z.string().optional(),
|
||||
uniqueId: z.string().optional(),
|
||||
loanFile: z.string().optional(),
|
||||
});
|
||||
|
||||
export type LoanPaidOffLetterFormData = z.infer<typeof baseLoanPaidOffLetterSchema>;
|
||||
|
||||
const stepSchemas = {
|
||||
0: baseLoanPaidOffLetterSchema.pick({
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
customerPatronicName: true,
|
||||
bornAt: true,
|
||||
phone: true,
|
||||
}),
|
||||
1: baseLoanPaidOffLetterSchema.pick({
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
}),
|
||||
2: baseLoanPaidOffLetterSchema.pick({
|
||||
loanContractNumber: true,
|
||||
loanContractDate: true,
|
||||
loanAmount: true,
|
||||
loanReason: true,
|
||||
}),
|
||||
3: baseLoanPaidOffLetterSchema.pick({
|
||||
region: true,
|
||||
branchId: true,
|
||||
userId: true,
|
||||
status: true,
|
||||
uniqueId: true,
|
||||
loanFile: true,
|
||||
notes: true,
|
||||
}),
|
||||
};
|
||||
|
||||
export function validateStep(stepIndex: number, form: LoanPaidOffLetterFormData): Partial<Record<keyof LoanPaidOffLetterFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex as keyof typeof stepSchemas];
|
||||
if (!schema) return {};
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
const errors: Partial<Record<keyof LoanPaidOffLetterFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof LoanPaidOffLetterFormData;
|
||||
if (!errors[key]) {
|
||||
const msg = issue.message;
|
||||
errors[key] = msg.startsWith("validation.") ? i18next.t(msg, msg) : msg;
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanPaidOffLetterFormData = {
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
loanAccount: '',
|
||||
issuedAt: '',
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
bornAt: "",
|
||||
phone: "",
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
region: "",
|
||||
branchId: "",
|
||||
userId: "",
|
||||
status: "pending",
|
||||
notes: "",
|
||||
loanContractNumber: "",
|
||||
loanContractDate: "",
|
||||
loanAmount: "",
|
||||
loanReason: "",
|
||||
uniqueId: "",
|
||||
loanFile: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: LoanPaidOffLetterFormData): LoanPaidOffLetterPayload {
|
||||
return {
|
||||
bornAt: formatToApiDate(data.bornAt),
|
||||
branchId: Number(data.branchId) || 0,
|
||||
customerName: data.customerName.trim(),
|
||||
customerPatronicName: data.customerPatronicName?.trim() ?? "",
|
||||
customerSurname: data.customerSurname.trim(),
|
||||
loanAmount: data.loanAmount.trim(),
|
||||
loanContractDate: formatToApiDate(data.loanContractDate),
|
||||
loanContractNumber: data.loanContractNumber.trim(),
|
||||
loanFile: data.loanFile?.trim() ?? "",
|
||||
loanReason: data.loanReason?.trim() ?? "",
|
||||
notes: data.notes?.trim() ?? "",
|
||||
passportId: data.passportId.trim(),
|
||||
passportSerie: data.passportSerie.trim(),
|
||||
phone: formatToApiPhone(data.phone),
|
||||
region: data.region.trim(),
|
||||
status: data.status,
|
||||
uniqueId: data.uniqueId?.trim() ?? "",
|
||||
userId: Number(data.userId) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPayload(
|
||||
data: LoanPaidOffLetterFormData,
|
||||
): { passportSeries: string; passportNumber: string; loanAccount: string; issuedAt: string } {
|
||||
export function mapInitial(data: LoanPaidOffLetter): LoanPaidOffLetterFormData {
|
||||
return {
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
loanAccount: data.loanAccount,
|
||||
issuedAt: data.issuedAt,
|
||||
}
|
||||
customerName: data.customerName ?? "",
|
||||
customerSurname: data.customerSurname ?? "",
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
bornAt: formatFromApiDate(data.bornAt),
|
||||
phone: formatFromApiPhone(data.phone),
|
||||
passportSerie: data.passportSerie ?? "",
|
||||
passportId: data.passportId ?? "",
|
||||
region: data.region ?? "",
|
||||
branchId: data.branchId != null ? String(data.branchId) : "",
|
||||
userId: data.userId != null ? String(data.userId) : "",
|
||||
status: data.status ?? "pending",
|
||||
notes: data.notes ?? "",
|
||||
loanContractNumber: data.loanContractNumber ?? "",
|
||||
loanContractDate: formatFromApiDate(data.loanContractDate),
|
||||
loanAmount: data.loanAmount ?? "",
|
||||
loanReason: data.loanReason ?? "",
|
||||
uniqueId: data.uniqueId ?? "",
|
||||
loanFile: data.loanFile ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,106 +4,61 @@ import apiClient from "@/lib/api/client";
|
||||
|
||||
export interface LoanRemaining {
|
||||
id: number;
|
||||
passportSeries: string;
|
||||
passportNumber: string;
|
||||
loanAccount: string;
|
||||
userId: number;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
accountNumber: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type LoanRemainingPayload = Omit<LoanRemaining, "id">;
|
||||
export type LoanRemainingPayload = {
|
||||
accountNumber: string;
|
||||
passportId: string;
|
||||
passportSerie: string;
|
||||
userId: number;
|
||||
};
|
||||
|
||||
export interface LoanRemainingListParams {
|
||||
search?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
limit?: number;
|
||||
passport_id?: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ─── Mock Data ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const USE_MOCK = true;
|
||||
|
||||
const MOCK_DATA: LoanRemaining[] = [
|
||||
{ id: 1, passportSeries: "TM", passportNumber: "A111111", loanAccount: "NOVA-2024-001" },
|
||||
{ id: 2, passportSeries: "TM", passportNumber: "B222222", loanAccount: "NOVA-2024-002" },
|
||||
{ id: 3, passportSeries: "TM", passportNumber: "C333333", loanAccount: "NOVA-2023-078" },
|
||||
{ id: 4, passportSeries: "TM", passportNumber: "D444444", loanAccount: "NOVA-2023-079" },
|
||||
{ id: 5, passportSeries: "TM", passportNumber: "E555555", loanAccount: "NOVA-2024-033" },
|
||||
{ id: 6, passportSeries: "TM", passportNumber: "F666666", loanAccount: "NOVA-2024-034" },
|
||||
{ id: 7, passportSeries: "TM", passportNumber: "G777777", loanAccount: "NOVA-2024-051" },
|
||||
{ id: 8, passportSeries: "TM", passportNumber: "H888888", loanAccount: "NOVA-2024-052" },
|
||||
{ id: 9, passportSeries: "TM", passportNumber: "I999999", loanAccount: "NOVA-2024-063" },
|
||||
{ id: 10, passportSeries: "TM", passportNumber: "J000000", loanAccount: "NOVA-2024-064" },
|
||||
];
|
||||
|
||||
function applyMockFilters(params: LoanRemainingListParams): PaginatedResponse<LoanRemaining> {
|
||||
let result = [...MOCK_DATA];
|
||||
|
||||
if (params.search) {
|
||||
const q = params.search.toLowerCase();
|
||||
result = result.filter((r) => r.passportNumber.toLowerCase().includes(q) || r.loanAccount.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const total = result.length;
|
||||
const page = params.page ?? 1;
|
||||
const perPage = params.perPage ?? 25;
|
||||
const start = (page - 1) * perPage;
|
||||
|
||||
return { data: result.slice(start, start + perPage), total };
|
||||
export interface LoanRemainingListResponse {
|
||||
count: number;
|
||||
loans: LoanRemaining[];
|
||||
}
|
||||
|
||||
// ─── API Functions ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanRemaining(params: LoanRemainingListParams): Promise<PaginatedResponse<LoanRemaining>> {
|
||||
if (USE_MOCK) return applyMockFilters(params);
|
||||
|
||||
const { data } = await apiClient.get<PaginatedResponse<LoanRemaining>>("/nova-loan-remaining-orders", { params });
|
||||
export async function fetchLoanRemaining(params: LoanRemainingListParams = {}): Promise<LoanRemainingListResponse> {
|
||||
const { page, limit, passport_id } = params;
|
||||
const { data } = await apiClient.get<LoanRemainingListResponse>("/loans-repayment", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
passport_id: passport_id || undefined,
|
||||
},
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanRemaining(id: number): Promise<void> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx !== -1) MOCK_DATA.splice(idx, 1);
|
||||
return;
|
||||
}
|
||||
await apiClient.delete(`/nova-loan-remaining-orders/${id}`);
|
||||
}
|
||||
|
||||
export async function fetchLoanRemainingById(id: number): Promise<LoanRemaining> {
|
||||
if (USE_MOCK) {
|
||||
const item = MOCK_DATA.find((r) => r.id === id);
|
||||
if (!item) throw new Error("Not found");
|
||||
return item;
|
||||
}
|
||||
const { data } = await apiClient.get<LoanRemaining>(`/nova-loan-remaining-orders/${id}`);
|
||||
const { data } = await apiClient.get<LoanRemaining>(`/loans-repayment/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createLoanRemaining(payload: LoanRemainingPayload): Promise<LoanRemaining> {
|
||||
if (USE_MOCK) {
|
||||
const newItem: LoanRemaining = {
|
||||
id: Math.max(0, ...MOCK_DATA.map((d) => d.id)) + 1,
|
||||
...payload,
|
||||
};
|
||||
MOCK_DATA.unshift(newItem);
|
||||
return newItem;
|
||||
}
|
||||
const { data } = await apiClient.post<LoanRemaining>("/nova-loan-remaining-orders", payload);
|
||||
const { data } = await apiClient.post<LoanRemaining>("/loans-repayment", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateLoanRemaining(id: number, payload: LoanRemainingPayload): Promise<LoanRemaining> {
|
||||
if (USE_MOCK) {
|
||||
const idx = MOCK_DATA.findIndex((r) => r.id === id);
|
||||
if (idx === -1) throw new Error("Not found");
|
||||
const updated = { ...MOCK_DATA[idx], ...payload };
|
||||
MOCK_DATA[idx] = updated;
|
||||
return updated;
|
||||
}
|
||||
const { data } = await apiClient.put<LoanRemaining>(`/nova-loan-remaining-orders/${id}`, payload);
|
||||
const { data } = await apiClient.put<LoanRemaining>(`/loans-repayment/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanRemaining(id: number): Promise<void> {
|
||||
await apiClient.delete(`/loans-repayment/${id}`);
|
||||
}
|
||||
|
||||
@@ -42,9 +42,10 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
useEffect(() => {
|
||||
if (mode === "edit" && initialData) {
|
||||
reset({
|
||||
passportSeries: initialData.passportSeries,
|
||||
passportNumber: initialData.passportNumber,
|
||||
loanAccount: initialData.loanAccount,
|
||||
passportSerie: initialData.passportSerie,
|
||||
passportId: initialData.passportId,
|
||||
accountNumber: initialData.accountNumber,
|
||||
userId: String(initialData.userId),
|
||||
});
|
||||
}
|
||||
}, [mode, initialData, reset]);
|
||||
@@ -55,14 +56,12 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t("common.success.create", "Üstünlikli döredildi"));
|
||||
navigate("/loan-remaining");
|
||||
},
|
||||
});
|
||||
} else {
|
||||
updateMutation.mutate(payload, {
|
||||
onSuccess: () => {
|
||||
toast.success(t("common.success.save", "Üstünlikli ýatda saklandy"));
|
||||
navigate("/loan-remaining");
|
||||
},
|
||||
});
|
||||
@@ -87,33 +86,40 @@ export function LoanRemainingForm({ mode, initialData }: LoanRemainingFormProps)
|
||||
<BentoCard>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.passportSeries", "Pasport seriýasy")}
|
||||
label={t("loanRemaining.columns.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={watch("passportSeries")}
|
||||
onChange={(v) => setValue("passportSeries", v)}
|
||||
placeholder={t("loanRemaining.placeholders.passportSeries", "TM")}
|
||||
error={errMsg(errors.passportSeries?.message)}
|
||||
value={watch("passportSerie")}
|
||||
onChange={(v) => setValue("passportSerie", v)}
|
||||
placeholder={t("loanRemaining.placeholders.passportSerie", "TM")}
|
||||
error={errMsg(errors.passportSerie?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.passportNumber", "Pasport belgisi")}
|
||||
label={t("loanRemaining.columns.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={watch("passportNumber")}
|
||||
onChange={(v) => setValue("passportNumber", v)}
|
||||
value={watch("passportId")}
|
||||
onChange={(v) => setValue("passportId", v)}
|
||||
placeholder="A123456"
|
||||
error={errMsg(errors.passportNumber?.message)}
|
||||
error={errMsg(errors.passportId?.message)}
|
||||
/>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.loanAccount", "Karz hasaby")}
|
||||
required
|
||||
value={watch("loanAccount")}
|
||||
onChange={(v) => setValue("loanAccount", v)}
|
||||
placeholder="NOVA-..."
|
||||
error={errMsg(errors.loanAccount?.message)}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.accountNumber", "Karz hasaby")}
|
||||
required
|
||||
value={watch("accountNumber")}
|
||||
onChange={(v) => setValue("accountNumber", v)}
|
||||
placeholder="ACC-LOAN-..."
|
||||
error={errMsg(errors.accountNumber?.message)}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label={t("loanRemaining.columns.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={watch("userId")}
|
||||
onChange={(v) => setValue("userId", v)}
|
||||
placeholder="2"
|
||||
error={errMsg(errors.userId?.message)}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
|
||||
import {
|
||||
fetchLoanRemaining,
|
||||
@@ -10,38 +11,44 @@ import {
|
||||
updateLoanRemaining,
|
||||
type LoanRemainingListParams,
|
||||
type LoanRemainingPayload,
|
||||
} from '../api/loanRemainingApi'
|
||||
} from "../api/loanRemainingApi";
|
||||
|
||||
// ─── Query keys ────────────────────────────────────────────────────────────────
|
||||
|
||||
export const loanRemainingKeys = {
|
||||
all: ['loanRemaining'] as const,
|
||||
lists: () => [...loanRemainingKeys.all, 'list'] as const,
|
||||
all: ["loanRemaining"] as const,
|
||||
lists: () => [...loanRemainingKeys.all, "list"] as const,
|
||||
list: (params: LoanRemainingListParams) => [...loanRemainingKeys.lists(), params] as const,
|
||||
details: () => [...loanRemainingKeys.all, 'detail'] as const,
|
||||
details: () => [...loanRemainingKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...loanRemainingKeys.details(), id] as const,
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Hooks ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useLoanRemaining(params: LoanRemainingListParams) {
|
||||
const debouncedPassport = useDebouncedValue(params.passport_id ?? "");
|
||||
const queryParams: LoanRemainingListParams = {
|
||||
...params,
|
||||
passport_id: normalizeSearch(debouncedPassport),
|
||||
};
|
||||
|
||||
return useQuery({
|
||||
queryKey: loanRemainingKeys.list(params),
|
||||
queryFn: () => fetchLoanRemaining(params),
|
||||
})
|
||||
queryKey: loanRemainingKeys.list(queryParams),
|
||||
queryFn: () => fetchLoanRemaining(queryParams),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteLoanRemaining() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteLoanRemaining(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() })
|
||||
toast.success(t('loanRemaining.deleteSuccess', 'Ýazgy üstünlikli pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() });
|
||||
toast.success(t("loanRemaining.deleteSuccess", "Ýazgy üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useLoanRemainingById(id?: string) {
|
||||
@@ -49,32 +56,32 @@ export function useLoanRemainingById(id?: string) {
|
||||
queryKey: loanRemainingKeys.detail(Number(id)),
|
||||
queryFn: () => fetchLoanRemainingById(Number(id)),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateLoanRemaining() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanRemainingPayload) => createLoanRemaining(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() })
|
||||
toast.success(t('loanRemaining.createSuccess', 'Üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() });
|
||||
toast.success(t("loanRemaining.createSuccess", "Üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateLoanRemaining(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanRemainingPayload) => updateLoanRemaining(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.detail(id) })
|
||||
toast.success(t('loanRemaining.updateSuccess', 'Üstünlikli üýtgedildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: loanRemainingKeys.detail(id) });
|
||||
toast.success(t("loanRemaining.updateSuccess", "Üstünlikli üýtgedildi"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
import { z } from 'zod'
|
||||
import { z } from "zod";
|
||||
|
||||
export const loanRemainingFormSchema = z.object({
|
||||
passportSeries: z.string().min(1, 'validation.required'),
|
||||
passportNumber: z.string().min(1, 'validation.required'),
|
||||
loanAccount: z.string().min(1, 'validation.required'),
|
||||
})
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
accountNumber: z.string().min(1, "validation.required"),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
});
|
||||
|
||||
export type LoanRemainingFormData = z.infer<typeof loanRemainingFormSchema>
|
||||
export type LoanRemainingFormData = z.infer<typeof loanRemainingFormSchema>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanRemainingFormData = {
|
||||
passportSeries: '',
|
||||
passportNumber: '',
|
||||
loanAccount: '',
|
||||
}
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
accountNumber: "",
|
||||
userId: "",
|
||||
};
|
||||
|
||||
export function buildPayload(
|
||||
data: LoanRemainingFormData,
|
||||
): { passportSeries: string; passportNumber: string; loanAccount: string } {
|
||||
export function buildPayload(data: LoanRemainingFormData): {
|
||||
accountNumber: string;
|
||||
passportId: string;
|
||||
passportSerie: string;
|
||||
userId: number;
|
||||
} {
|
||||
return {
|
||||
passportSeries: data.passportSeries,
|
||||
passportNumber: data.passportNumber,
|
||||
loanAccount: data.loanAccount,
|
||||
}
|
||||
passportSerie: data.passportSerie,
|
||||
passportId: data.passportId,
|
||||
accountNumber: data.accountNumber,
|
||||
userId: Number(data.userId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,169 +1,75 @@
|
||||
// features/loanTypes/api/loanTypesApi.ts
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
export interface LoanTypeTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||
|
||||
export interface LocalizedText {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
// ─── Loan Type ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LoanType {
|
||||
id: number
|
||||
name: LoanTypeTranslation
|
||||
tax: number
|
||||
loanTerm: number
|
||||
notes: LoanTypeTranslation | null
|
||||
isActive: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
id: number;
|
||||
title: LocalizedText;
|
||||
tax: number;
|
||||
loanTerm: string;
|
||||
content: LocalizedText;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface LoanTypeListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export interface LoanTypeListResponse {
|
||||
data: LoanType[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
count: number;
|
||||
loanTypes: LoanType[];
|
||||
}
|
||||
|
||||
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CreateLoanTypePayload {
|
||||
name: LoanTypeTranslation
|
||||
tax: number
|
||||
loanTerm: number
|
||||
notes: LoanTypeTranslation | null
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
content: LocalizedText;
|
||||
loanTerm: string;
|
||||
tax: number;
|
||||
title: LocalizedText;
|
||||
}
|
||||
|
||||
export type UpdateLoanTypePayload = CreateLoanTypePayload
|
||||
export type UpdateLoanTypePayload = CreateLoanTypePayload;
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
// ─── Loan Type CRUD ───────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_LOAN_TYPES: LoanType[] = [
|
||||
{
|
||||
id: 5,
|
||||
name: { tk: 'Talyp karzy', ru: 'Студенческий кредит', en: 'Student Loan' },
|
||||
tax: 1,
|
||||
loanTerm: 30,
|
||||
notes: { tk: 'Bellik', ru: 'Примечание', en: 'Note' },
|
||||
isActive: true,
|
||||
createdAt: '2026-01-10T08:00:00Z',
|
||||
updatedAt: '2026-03-15T10:30:00Z',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: {
|
||||
tk: 'Üpjünçiligine girew emlägi bolan sarp ediş karzy',
|
||||
ru: 'Потребительский кредит под залог имущества',
|
||||
en: 'Consumer Loan Secured by Property',
|
||||
},
|
||||
tax: 1,
|
||||
loanTerm: 30,
|
||||
notes: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-08T09:00:00Z',
|
||||
updatedAt: '2026-02-20T11:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: { tk: 'Kiçi göwrümli karzlar', ru: 'Микрокредиты', en: 'Micro Loans' },
|
||||
tax: 1,
|
||||
loanTerm: 30,
|
||||
notes: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-05T07:00:00Z',
|
||||
updatedAt: '2026-01-05T07:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: {
|
||||
tk: 'Üpjünçiligine zamunlyk bolan sarp ediş karzy',
|
||||
ru: 'Потребительский кредит под поручительство',
|
||||
en: 'Consumer Loan with Guarantor',
|
||||
},
|
||||
tax: 1,
|
||||
loanTerm: 30,
|
||||
notes: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-03T06:00:00Z',
|
||||
updatedAt: '2026-01-03T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
name: { tk: 'Ýaş çatynjalara', ru: 'Молодожёнам', en: 'Newlyweds Loan' },
|
||||
tax: 1,
|
||||
loanTerm: 30,
|
||||
notes: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
let _mockStore: LoanType[] = [...MOCK_LOAN_TYPES]
|
||||
let _nextId = 6
|
||||
|
||||
const delay = (ms = 400) => new Promise<void>((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanTypes(params: LoanTypeListParams = {}): Promise<LoanTypeListResponse> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 25, search = '' } = params
|
||||
|
||||
const filtered = search.trim()
|
||||
? _mockStore.filter((lt) =>
|
||||
lt.name.tk.toLowerCase().includes(search.toLowerCase()) ||
|
||||
lt.name.ru.toLowerCase().includes(search.toLowerCase()) ||
|
||||
lt.name.en.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
: _mockStore
|
||||
|
||||
const sorted = [...filtered].sort((a, b) => b.id - a.id)
|
||||
const start = (page - 1) * perPage
|
||||
const data = sorted.slice(start, start + perPage)
|
||||
|
||||
return {
|
||||
data,
|
||||
total: filtered.length,
|
||||
page,
|
||||
perPage,
|
||||
totalPages: Math.max(1, Math.ceil(filtered.length / perPage)),
|
||||
}
|
||||
export async function fetchLoanTypes(params: LoanTypeListParams = {}, signal?: AbortSignal): Promise<LoanTypeListResponse> {
|
||||
const { page, limit, search } = params;
|
||||
const { data } = await apiClient.get<LoanTypeListResponse>("/loan-types", {
|
||||
params: { page, limit, loan_type_name: search },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchLoanTypeById(id: number): Promise<LoanType> {
|
||||
await delay()
|
||||
const found = _mockStore.find((lt) => lt.id === id)
|
||||
if (!found) throw new Error(`LoanType with id=${id} not found`)
|
||||
return { ...found }
|
||||
const { data } = await apiClient.get<LoanType>(`/loan-types/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createLoanType(payload: CreateLoanTypePayload): Promise<LoanType> {
|
||||
await delay()
|
||||
const newItem: LoanType = {
|
||||
id: _nextId++,
|
||||
...payload,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
_mockStore = [newItem, ..._mockStore]
|
||||
return { ...newItem }
|
||||
const { data } = await apiClient.post<LoanType>("/loan-types", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateLoanType(id: number, payload: UpdateLoanTypePayload): Promise<LoanType> {
|
||||
await delay()
|
||||
const idx = _mockStore.findIndex((lt) => lt.id === id)
|
||||
if (idx === -1) throw new Error(`LoanType with id=${id} not found`)
|
||||
_mockStore[idx] = { ..._mockStore[idx], ...payload, updatedAt: new Date().toISOString() }
|
||||
return { ..._mockStore[idx] }
|
||||
const { data } = await apiClient.put<LoanType>(`/loan-types/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanType(id: number): Promise<void> {
|
||||
await delay()
|
||||
_mockStore = _mockStore.filter((lt) => lt.id !== id)
|
||||
}
|
||||
await apiClient.delete(`/loan-types/${id}`);
|
||||
}
|
||||
|
||||
@@ -36,15 +36,15 @@ function flattenErrors(errors: Record<string, { message?: string } | undefined>)
|
||||
|
||||
function mapInitial(data: LoanType): LoanTypeFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
notesTk: data.notes?.tk ?? "",
|
||||
notesRu: data.notes?.ru ?? "",
|
||||
notesEn: data.notes?.en ?? "",
|
||||
nameTk: data.title.tm,
|
||||
nameRu: data.title.ru,
|
||||
nameEn: data.title.en,
|
||||
notesTk: data.content.tm ?? "",
|
||||
notesRu: data.content.ru ?? "",
|
||||
notesEn: data.content.en ?? "",
|
||||
tax: String(data.tax),
|
||||
loanTerm: String(data.loanTerm),
|
||||
isActive: data.isActive,
|
||||
loanTerm: data.loanTerm,
|
||||
isActive: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -103,14 +103,14 @@ export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) {
|
||||
|
||||
if (mode === "create") {
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/resources/loan-types/${result.id}`);
|
||||
navigate(`/settings/loan/loan-types/${result.id}`);
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate(`/resources/loan-types/${initialData!.id}`);
|
||||
navigate(`/settings/loan/loan-types/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => navigate("/resources/loan-types");
|
||||
const handleCancel = () => navigate("/settings/loan/loan-types");
|
||||
|
||||
// ── Name fields per lang ───────────────────────────────────────────────────
|
||||
const nameFields = {
|
||||
@@ -153,11 +153,11 @@ export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) {
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="number"
|
||||
type="text"
|
||||
label={t("loanTypes.fields.loanTerm", "Karz möhleti")}
|
||||
value={form.loanTerm}
|
||||
onChange={set("loanTerm")}
|
||||
placeholder={t("loanTypes.fields.loanTerm", "Karz möhleti")}
|
||||
placeholder={t("loanTypes.placeholders.loanTerm", "12, 24, 36")}
|
||||
error={errors.loanTerm}
|
||||
required
|
||||
/>
|
||||
@@ -180,7 +180,6 @@ export function LoanTypeForm({ mode, initialData }: LoanTypeFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === "create" ? t("loanTypes.actions.create", "Karz görnüşi dörediň") : t("loanTypes.actions.save", "Ýatda sakla")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// features/loanTypes/hooks/useLoanTypes.ts
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchLoanTypes,
|
||||
fetchLoanTypeById,
|
||||
@@ -12,24 +13,27 @@ import {
|
||||
type LoanTypeListParams,
|
||||
type CreateLoanTypePayload,
|
||||
type UpdateLoanTypePayload,
|
||||
} from '../api/loanTypesApi'
|
||||
} from "../api/loanTypesApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const loanTypeKeys = {
|
||||
all: () => ['loanTypes'] as const,
|
||||
list: (params: LoanTypeListParams) => ['loanTypes', 'list', params] as const,
|
||||
detail: (id: number) => ['loanTypes', 'detail', id] as const,
|
||||
}
|
||||
all: () => ["loanTypes"] as const,
|
||||
list: (params: LoanTypeListParams) => ["loanTypes", "list", params] as const,
|
||||
detail: (id: number) => ["loanTypes", "detail", id] as const,
|
||||
};
|
||||
|
||||
// ─── useGetLoanTypes ──────────────────────────────────────────────────────────
|
||||
|
||||
export function useGetLoanTypes(params: LoanTypeListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: LoanTypeListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: loanTypeKeys.list(params),
|
||||
queryFn: () => fetchLoanTypes(params),
|
||||
queryKey: loanTypeKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchLoanTypes(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useGetLoanTypeById ───────────────────────────────────────────────────────
|
||||
@@ -37,52 +41,52 @@ export function useGetLoanTypes(params: LoanTypeListParams = {}) {
|
||||
export function useGetLoanTypeById(id: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: loanTypeKeys.detail(id!),
|
||||
queryFn: () => fetchLoanTypeById(id!),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => fetchLoanTypeById(id!),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateLoanType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateLoanType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateLoanTypePayload) => createLoanType(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
|
||||
toast.success(t('loanTypes.toast.created', 'Karz görnüşi üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() });
|
||||
toast.success(t("loanTypes.toast.created", "Karz görnüşi üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateLoanType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateLoanType(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateLoanTypePayload) => updateLoanType(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
|
||||
toast.success(t('loanTypes.toast.updated', 'Karz görnüşi üstünlikli täzelendi'))
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() });
|
||||
toast.success(t("loanTypes.toast.updated", "Karz görnüşi üstünlikli täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteLoanType ────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteLoanType() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteLoanType(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() })
|
||||
toast.success(t('loanTypes.toast.deleted', 'Karz görnüşi üstünlikli pozuldy'))
|
||||
queryClient.invalidateQueries({ queryKey: loanTypeKeys.all() });
|
||||
toast.success(t("loanTypes.toast.deleted", "Karz görnüşi üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,49 +1,46 @@
|
||||
import { z } from 'zod'
|
||||
import type { CreateLoanTypePayload } from '../api/loanTypesApi'
|
||||
import { z } from "zod";
|
||||
import type { CreateLoanTypePayload } from "../api/loanTypesApi";
|
||||
|
||||
export function createLoanTypeFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
notesTk: z.string().optional(),
|
||||
notesRu: z.string().optional(),
|
||||
notesEn: z.string().optional(),
|
||||
tax: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||
),
|
||||
loanTerm: z.string().refine(
|
||||
(v) => v.trim() !== '' && !isNaN(Number(v)) && Number(v) > 0,
|
||||
t('validation.positiveNumber', 'validation.positiveNumber'),
|
||||
),
|
||||
tax: z
|
||||
.string()
|
||||
.refine((v) => v.trim() !== "" && !isNaN(Number(v)) && Number(v) > 0, t("validation.positiveNumber", "validation.positiveNumber")),
|
||||
loanTerm: z.string().min(1, t("validation.required", "validation.required")),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export type LoanTypeFormData = z.infer<ReturnType<typeof createLoanTypeFormSchema>>
|
||||
export type LoanTypeFormData = z.infer<ReturnType<typeof createLoanTypeFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: LoanTypeFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
notesTk: '',
|
||||
notesRu: '',
|
||||
notesEn: '',
|
||||
tax: '',
|
||||
loanTerm: '',
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
notesTk: "",
|
||||
notesRu: "",
|
||||
notesEn: "",
|
||||
tax: "",
|
||||
loanTerm: "",
|
||||
isActive: true,
|
||||
}
|
||||
};
|
||||
|
||||
export function buildPayload(data: LoanTypeFormData): CreateLoanTypePayload {
|
||||
return {
|
||||
name: { tk: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
title: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
tax: Number(data.tax),
|
||||
loanTerm: Number(data.loanTerm),
|
||||
notes:
|
||||
(data.notesTk ?? '').trim() || (data.notesRu ?? '').trim() || (data.notesEn ?? '').trim()
|
||||
? { tk: (data.notesTk ?? '').trim(), ru: (data.notesRu ?? '').trim(), en: (data.notesEn ?? '').trim() }
|
||||
: null,
|
||||
isActive: data.isActive,
|
||||
}
|
||||
loanTerm: data.loanTerm.trim(),
|
||||
content: {
|
||||
tm: (data.notesTk ?? "").trim(),
|
||||
ru: (data.notesRu ?? "").trim(),
|
||||
en: (data.notesEn ?? "").trim(),
|
||||
},
|
||||
active: data.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -216,7 +216,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate(-1)}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={mode === "create" ? t("operators.createBtn", "Operator döredin") : t("operators.updateBtn", "Üýtgetmeleri sakla")}
|
||||
className="px-6 py-4 border-t border-border bg-muted/20"
|
||||
/>
|
||||
|
||||
@@ -1,425 +1,132 @@
|
||||
// ─── Enums / Unions ───────────────────────────────────────────────────────────
|
||||
|
||||
export type CardOrderStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
|
||||
export type CardOrderSortField =
|
||||
| 'id'
|
||||
| 'createdAt'
|
||||
| 'status'
|
||||
| 'welayat'
|
||||
| 'sahamca'
|
||||
|
||||
// ─── Lookup entities ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardIssuanceReason {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface CardType {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface Province {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface Branch {
|
||||
id: number
|
||||
name: string
|
||||
provinceId: number
|
||||
}
|
||||
|
||||
// ─── Passport ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PassportFiles {
|
||||
page1: string | null // URL
|
||||
page23: string | null
|
||||
page89: string | null
|
||||
page32: string | null
|
||||
}
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Card Order ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardOrder {
|
||||
id: string
|
||||
createdAt: string // ISO datetime string
|
||||
isPaid: boolean
|
||||
status: CardOrderStatus
|
||||
note: string | null
|
||||
createdBy: string // user display name
|
||||
|
||||
// Card
|
||||
issuanceReasonId: number
|
||||
issuanceReasonName: string
|
||||
cardTypeId: number
|
||||
cardTypeName: string
|
||||
|
||||
// Location
|
||||
provinceId: number
|
||||
provinceName: string
|
||||
branchId: number
|
||||
branchName: string
|
||||
|
||||
// Personal info
|
||||
firstName: string
|
||||
lastName: string
|
||||
middleName: string | null
|
||||
formerLastName: string | null
|
||||
birthDate: string // yyyy-MM-dd
|
||||
phone: string
|
||||
phoneExtra: string | null
|
||||
citizenship: string
|
||||
registeredAddress: string
|
||||
currentAddress: string
|
||||
workplace: string
|
||||
|
||||
// Passport
|
||||
passportSeriesId: number
|
||||
passportSeriesName: string
|
||||
passportNumber: string
|
||||
passportIssueDate: string // yyyy-MM-dd
|
||||
passportIssuedBy: string
|
||||
passportBirthPlace: string
|
||||
|
||||
passportFiles: PassportFiles
|
||||
id: number;
|
||||
uniqueId: string;
|
||||
cardStateId: number;
|
||||
cardTypeId: number;
|
||||
region: string;
|
||||
branchId: number;
|
||||
customerName: string;
|
||||
customerSurname: string;
|
||||
customerPatronicName: string;
|
||||
bornAt: string | null;
|
||||
oldSurname: string | null;
|
||||
citizenship: string;
|
||||
passportSerie: string;
|
||||
passportId: string;
|
||||
passportGivenAt: string | null;
|
||||
passportGivenBy: string;
|
||||
bornPlace: string;
|
||||
jobLocation: string;
|
||||
passportAddress: string;
|
||||
realAddress: string;
|
||||
phone: string;
|
||||
phoneAdditional: string;
|
||||
status: string;
|
||||
passportOne: string;
|
||||
passportTwo: string;
|
||||
passportThree: string;
|
||||
passportFour: string;
|
||||
notes: string;
|
||||
userId: number;
|
||||
paid: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ─── List item (lighter shape for table rows) ─────────────────────────────────
|
||||
|
||||
export interface CardOrderListItem {
|
||||
id: string
|
||||
createdAt: string
|
||||
issuanceReasonName: string
|
||||
cardTypeName: string
|
||||
provinceName: string
|
||||
branchName: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
status: CardOrderStatus
|
||||
export interface CardOrderListResponse {
|
||||
count: number;
|
||||
cardOrders: CardOrder[];
|
||||
}
|
||||
|
||||
// ─── Pagination ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
totalCount: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
export interface CardOrderListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
// ─── Filter params ──────────────────────────────────────────────────────────
|
||||
status?: string;
|
||||
branch_id?: string;
|
||||
user_id?: string;
|
||||
card_state_id?: string;
|
||||
card_type_id?: string;
|
||||
region?: string;
|
||||
}
|
||||
|
||||
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
export interface CardOrderFilters {
|
||||
search?: string
|
||||
status?: CardOrderStatus | ''
|
||||
provinceId?: number | ''
|
||||
branchId?: number | ''
|
||||
page?: number
|
||||
perPage?: number
|
||||
}
|
||||
|
||||
export interface CreateCardOrderPayload {
|
||||
isPaid: boolean
|
||||
status: CardOrderStatus
|
||||
note: string | null
|
||||
|
||||
issuanceReasonId: number
|
||||
cardTypeId: number
|
||||
provinceId: number
|
||||
branchId: number
|
||||
|
||||
firstName: string
|
||||
lastName: string
|
||||
middleName: string | null
|
||||
formerLastName: string | null
|
||||
birthDate: string
|
||||
phone: string
|
||||
phoneExtra: string | null
|
||||
citizenship: string
|
||||
registeredAddress: string
|
||||
currentAddress: string
|
||||
workplace: string
|
||||
|
||||
passportSeriesId: number
|
||||
passportNumber: string
|
||||
passportIssueDate: string
|
||||
passportIssuedBy: string
|
||||
passportBirthPlace: string
|
||||
|
||||
passportPage1: File
|
||||
passportPage23: File
|
||||
passportPage89: File
|
||||
passportPage32: File
|
||||
bornAt: string;
|
||||
bornPlace: string;
|
||||
branchId: number;
|
||||
cardStateId: number;
|
||||
cardTypeId: number;
|
||||
citizenship: string;
|
||||
customerName: string;
|
||||
customerPatronicName: string;
|
||||
customerSurname: string;
|
||||
jobLocation: string;
|
||||
notes: string;
|
||||
oldSurname: string;
|
||||
paid: boolean;
|
||||
passportAddress: string;
|
||||
passportFour: string;
|
||||
passportGivenAt: string;
|
||||
passportGivenBy: string;
|
||||
passportId: string;
|
||||
passportOne: string;
|
||||
passportSerie: string;
|
||||
passportThree: string;
|
||||
passportTwo: string;
|
||||
phone: string;
|
||||
phoneAdditional: string;
|
||||
realAddress: string;
|
||||
region: string;
|
||||
status: string;
|
||||
uniqueId: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
export interface UpdateCardOrderPayload extends Partial<CreateCardOrderPayload> {}
|
||||
export type UpdateCardOrderPayload = CreateCardOrderPayload;
|
||||
|
||||
import apiClient from '@/lib/api/client'
|
||||
// ─── Card Order CRUD ──────────────────────────────────────────────────────────
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
const USE_MOCK = true
|
||||
|
||||
const MOCK_REASONS: CardIssuanceReason[] = [
|
||||
{ id: 1, name: 'Möhleti gutardy' },
|
||||
{ id: 2, name: 'Täze kart açmak' },
|
||||
{ id: 3, name: 'Kartyň ýitmegi' },
|
||||
{ id: 4, name: 'Adyň üýtgemegi' },
|
||||
]
|
||||
|
||||
const MOCK_TYPES: CardType[] = [
|
||||
{ id: 1, name: 'Altyn Asyr' },
|
||||
{ id: 2, name: 'Maşgala' },
|
||||
{ id: 3, name: 'Goýum' },
|
||||
{ id: 4, name: 'Milli' },
|
||||
]
|
||||
|
||||
const MOCK_PROVINCES: Province[] = [
|
||||
{ id: 1, name: 'Aşgabat ş.' },
|
||||
{ id: 2, name: 'Ahal' },
|
||||
{ id: 3, name: 'Balkan' },
|
||||
{ id: 4, name: 'Daşoguz' },
|
||||
{ id: 5, name: 'Lebap' },
|
||||
{ id: 6, name: 'Mary' },
|
||||
]
|
||||
|
||||
const MOCK_BRANCHES: Branch[] = [
|
||||
{ id: 1, name: 'Aşgabat Baş şahamça', provinceId: 1 },
|
||||
{ id: 2, name: 'Köpetdag şahamçasy', provinceId: 1 },
|
||||
{ id: 3, name: 'Abadan şahamçasy', provinceId: 2 },
|
||||
{ id: 4, name: 'Balkanabat şahamçasy', provinceId: 3 },
|
||||
{ id: 5, name: 'Mary şahamçasy', provinceId: 6 },
|
||||
]
|
||||
|
||||
const MOCK_ORDERS: CardOrder[] = [
|
||||
{
|
||||
id: 'CRD-10254',
|
||||
createdAt: '2026-05-01T10:00:00Z',
|
||||
isPaid: true,
|
||||
status: 'APPROVED',
|
||||
note: 'Hemme zat ýerinde',
|
||||
createdBy: 'Jumaýew Aman',
|
||||
issuanceReasonId: 2,
|
||||
issuanceReasonName: 'Täze kart açmak',
|
||||
cardTypeId: 1,
|
||||
cardTypeName: 'Altyn Asyr',
|
||||
provinceId: 1,
|
||||
provinceName: 'Aşgabat ş.',
|
||||
branchId: 1,
|
||||
branchName: 'Aşgabat Baş şahamça',
|
||||
firstName: 'Berdi',
|
||||
lastName: 'Myradow',
|
||||
middleName: 'Gurbanowiç',
|
||||
formerLastName: null,
|
||||
birthDate: '1995-04-12',
|
||||
phone: '+99365123456',
|
||||
phoneExtra: null,
|
||||
citizenship: 'Türkmenistan',
|
||||
registeredAddress: 'Aşgabat, Magtymguly şaýoly 12',
|
||||
currentAddress: 'Aşgabat, Magtymguly şaýoly 12',
|
||||
workplace: 'TDB, IT hünärmen',
|
||||
passportSeriesId: 1,
|
||||
passportSeriesName: 'I-AS',
|
||||
passportNumber: '123456',
|
||||
passportIssueDate: '2015-05-20',
|
||||
passportIssuedBy: 'Aşgabat ş. Polisiýa müdirligi',
|
||||
passportBirthPlace: 'Aşgabat',
|
||||
passportFiles: {
|
||||
page1: 'https://placehold.co/600x400?text=Passport+P1',
|
||||
page23: 'https://placehold.co/600x400?text=Passport+P23',
|
||||
page89: 'https://placehold.co/600x400?text=Passport+P89',
|
||||
page32: 'https://placehold.co/600x400?text=Passport+P32',
|
||||
export async function fetchCardOrders(params: CardOrderListParams = {}, signal?: AbortSignal): Promise<CardOrderListResponse> {
|
||||
const { page, limit, search, status, branch_id, user_id, card_state_id, card_type_id, region } = params;
|
||||
const { data } = await apiClient.get<CardOrderListResponse>("/card-orders", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
search: search || undefined,
|
||||
status: status || undefined,
|
||||
branch_id: branch_id || undefined,
|
||||
user_id: user_id || undefined,
|
||||
card_state_id: card_state_id || undefined,
|
||||
card_type_id: card_type_id || undefined,
|
||||
region: region || undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'CRD-10255',
|
||||
createdAt: '2026-05-02T14:30:00Z',
|
||||
isPaid: false,
|
||||
status: 'PENDING',
|
||||
note: null,
|
||||
createdBy: 'Saparow Batyr',
|
||||
issuanceReasonId: 1,
|
||||
issuanceReasonName: 'Möhleti gutardy',
|
||||
cardTypeId: 2,
|
||||
cardTypeName: 'Maşgala',
|
||||
provinceId: 6,
|
||||
provinceName: 'Mary',
|
||||
branchId: 5,
|
||||
branchName: 'Mary şahamçasy',
|
||||
firstName: 'Gyzylgül',
|
||||
lastName: 'Annageldiýewa',
|
||||
middleName: 'Begliýewna',
|
||||
formerLastName: 'Saparowa',
|
||||
birthDate: '1998-08-25',
|
||||
phone: '+99361987654',
|
||||
phoneExtra: '+99312444234',
|
||||
citizenship: 'Türkmenistan',
|
||||
registeredAddress: 'Mary ş., Gurbansoltan eje köç. 45',
|
||||
currentAddress: 'Mary ş., Gurbansoltan eje köç. 45',
|
||||
workplace: 'Mekdep müdiri',
|
||||
passportSeriesId: 2,
|
||||
passportSeriesName: 'I-MR',
|
||||
passportNumber: '654321',
|
||||
passportIssueDate: '2018-10-10',
|
||||
passportIssuedBy: 'Mary w. Polisiýa müdirligi',
|
||||
passportBirthPlace: 'Mary',
|
||||
passportFiles: {
|
||||
page1: 'https://placehold.co/600x400?text=Passport+P1',
|
||||
page23: 'https://placehold.co/600x400?text=Passport+P23',
|
||||
page89: 'https://placehold.co/600x400?text=Passport+P89',
|
||||
page32: 'https://placehold.co/600x400?text=Passport+P32',
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
// ─── Card Orders CRUD ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardOrders(
|
||||
filters: CardOrderFilters,
|
||||
): Promise<PaginatedResponse<CardOrderListItem>> {
|
||||
if (USE_MOCK) {
|
||||
await new Promise((r) => setTimeout(r, 500))
|
||||
const list: CardOrderListItem[] = MOCK_ORDERS.map((o) => ({
|
||||
id: o.id,
|
||||
createdAt: o.createdAt,
|
||||
issuanceReasonName: o.issuanceReasonName,
|
||||
cardTypeName: o.cardTypeName,
|
||||
provinceName: o.provinceName,
|
||||
branchName: o.branchName,
|
||||
firstName: o.firstName,
|
||||
lastName: o.lastName,
|
||||
status: o.status,
|
||||
}))
|
||||
return {
|
||||
data: list,
|
||||
totalCount: list.length,
|
||||
page: filters.page ?? 1,
|
||||
perPage: filters.perPage ?? 25,
|
||||
totalPages: 1,
|
||||
}
|
||||
}
|
||||
|
||||
const params = new URLSearchParams()
|
||||
|
||||
if (filters.search) params.set('search', filters.search)
|
||||
if (filters.status) params.set('status', filters.status)
|
||||
if (filters.provinceId) params.set('provinceId', String(filters.provinceId))
|
||||
if (filters.branchId) params.set('branchId', String(filters.branchId))
|
||||
|
||||
params.set('page', String(filters.page ?? 1))
|
||||
params.set('perPage', String(filters.perPage ?? 25))
|
||||
|
||||
const { data } = await apiClient.get<PaginatedResponse<CardOrderListItem>>(
|
||||
`/card-orders?${params.toString()}`,
|
||||
)
|
||||
return data
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchCardOrderById(id: string): Promise<CardOrder> {
|
||||
if (USE_MOCK) {
|
||||
await new Promise((r) => setTimeout(r, 500))
|
||||
const order = MOCK_ORDERS.find((o) => o.id === id) || MOCK_ORDERS[0]
|
||||
return { ...order, id }
|
||||
}
|
||||
const { data } = await apiClient.get<CardOrder>(`/card-orders/${id}`)
|
||||
return data
|
||||
export async function fetchCardOrderById(id: number): Promise<CardOrder> {
|
||||
const { data } = await apiClient.get<CardOrder>(`/card-orders/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createCardOrder(
|
||||
payload: CreateCardOrderPayload,
|
||||
): Promise<CardOrder> {
|
||||
if (USE_MOCK) {
|
||||
await new Promise((r) => setTimeout(r, 1000))
|
||||
return { ...MOCK_ORDERS[0], id: `CRD-${Math.floor(Math.random() * 10000)}` }
|
||||
}
|
||||
const formData = buildFormData(payload)
|
||||
const { data } = await apiClient.post<CardOrder>('/card-orders', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return data
|
||||
export async function createCardOrder(payload: CreateCardOrderPayload): Promise<CardOrder> {
|
||||
const { data } = await apiClient.post<CardOrder>("/card-orders", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateCardOrder(
|
||||
id: string,
|
||||
payload: UpdateCardOrderPayload,
|
||||
): Promise<CardOrder> {
|
||||
if (USE_MOCK) {
|
||||
await new Promise((r) => setTimeout(r, 1000))
|
||||
return { ...MOCK_ORDERS[0], id }
|
||||
}
|
||||
const formData = buildFormData(payload)
|
||||
const { data } = await apiClient.put<CardOrder>(`/card-orders/${id}`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return data
|
||||
export async function updateCardOrder(id: number, payload: UpdateCardOrderPayload): Promise<CardOrder> {
|
||||
const { data } = await apiClient.put<CardOrder>(`/card-orders/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteCardOrder(id: string): Promise<void> {
|
||||
if (USE_MOCK) {
|
||||
await new Promise((r) => setTimeout(r, 500))
|
||||
return
|
||||
}
|
||||
await apiClient.delete(`/card-orders/${id}`)
|
||||
export async function deleteCardOrder(id: number): Promise<void> {
|
||||
await apiClient.delete(`/card-orders/${id}`);
|
||||
}
|
||||
|
||||
// ─── Lookup lists ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchCardIssuanceReasons(): Promise<CardIssuanceReason[]> {
|
||||
if (USE_MOCK) return MOCK_REASONS
|
||||
const { data } = await apiClient.get<CardIssuanceReason[]>('/settings/card/reasons')
|
||||
return data
|
||||
}
|
||||
|
||||
export async function fetchCardTypes(): Promise<CardType[]> {
|
||||
if (USE_MOCK) return MOCK_TYPES
|
||||
const { data } = await apiClient.get<CardType[]>('/settings/card/types')
|
||||
return data
|
||||
}
|
||||
|
||||
export async function fetchProvinces(): Promise<Province[]> {
|
||||
if (USE_MOCK) return MOCK_PROVINCES
|
||||
const { data } = await apiClient.get<Province[]>('/settings/location/districts')
|
||||
return data
|
||||
}
|
||||
|
||||
export async function fetchBranches(provinceId?: number): Promise<Branch[]> {
|
||||
if (USE_MOCK) {
|
||||
if (!provinceId) return MOCK_BRANCHES
|
||||
return MOCK_BRANCHES.filter((b) => b.provinceId === provinceId)
|
||||
}
|
||||
const params = provinceId ? `?provinceId=${provinceId}` : ''
|
||||
const { data } = await apiClient.get<Branch[]>(`/settings/location/branches${params}`)
|
||||
return data
|
||||
}
|
||||
|
||||
// ─── Helper ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildFormData(
|
||||
payload: CreateCardOrderPayload | UpdateCardOrderPayload,
|
||||
): FormData {
|
||||
const fd = new FormData()
|
||||
|
||||
const fileKeys = new Set([
|
||||
'passportPage1',
|
||||
'passportPage23',
|
||||
'passportPage89',
|
||||
'passportPage32',
|
||||
])
|
||||
|
||||
for (const [key, value] of Object.entries(payload)) {
|
||||
if (value === undefined) continue
|
||||
|
||||
if (fileKeys.has(key) && value instanceof File) {
|
||||
fd.append(key, value)
|
||||
} else if (value === null) {
|
||||
fd.append(key, '')
|
||||
} else {
|
||||
fd.append(key, String(value))
|
||||
}
|
||||
}
|
||||
|
||||
return fd
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { toast } from "sonner";
|
||||
import { CreditCard, User, FileText, Upload } from "lucide-react";
|
||||
import { CreditCard, User, FileText, MapPin } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
@@ -11,16 +11,8 @@ import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import type { SelectOption } from "@/components/formInput";
|
||||
import type { CardOrder, CardOrderStatus, CreateCardOrderPayload } from "../api/orderNewCardApi";
|
||||
import {
|
||||
useCardIssuanceReasons,
|
||||
useCardTypes,
|
||||
useProvinces,
|
||||
useBranches,
|
||||
useCreateCardOrder,
|
||||
useUpdateCardOrder,
|
||||
} from "../hooks/useOrderNewCard";
|
||||
import type { CardOrder } from "../api/orderNewCardApi";
|
||||
import { useCreateCard, useUpdateCard } from "../hooks/useOrderNewCard";
|
||||
import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/orderNewCard.schema";
|
||||
import type { OrderNewCardFormData } from "../schemas/orderNewCard.schema";
|
||||
|
||||
@@ -53,7 +45,7 @@ interface StepDef {
|
||||
subtitleKey: string;
|
||||
subtitleFallback: string;
|
||||
icon: LucideIcon;
|
||||
validate: (form: OrderNewCardFormData, mode: "create" | "edit") => FlatErrors;
|
||||
validate: (form: OrderNewCardFormData) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
@@ -64,7 +56,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.card.subtitle",
|
||||
subtitleFallback: "Görnüş & lokasiýa",
|
||||
icon: CreditCard,
|
||||
validate: (form, mode) => validateStep(0, form, mode),
|
||||
validate: (form) => validateStep(0, form),
|
||||
},
|
||||
{
|
||||
id: "personal",
|
||||
@@ -73,7 +65,7 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.personal.subtitle",
|
||||
subtitleFallback: "Maglumatlar",
|
||||
icon: User,
|
||||
validate: (form, mode) => validateStep(1, form, mode),
|
||||
validate: (form) => validateStep(1, form),
|
||||
},
|
||||
{
|
||||
id: "passport",
|
||||
@@ -82,16 +74,16 @@ const STEPS: StepDef[] = [
|
||||
subtitleKey: "orderNewCardForm.steps.passport.subtitle",
|
||||
subtitleFallback: "Resmi maglumat",
|
||||
icon: FileText,
|
||||
validate: (form, mode) => validateStep(2, form, mode),
|
||||
validate: (form) => validateStep(2, form),
|
||||
},
|
||||
{
|
||||
id: "files",
|
||||
titleKey: "cardOrder.step.files",
|
||||
titleFallback: "Faýllar",
|
||||
subtitleKey: "orderNewCardForm.steps.files.subtitle",
|
||||
subtitleFallback: "Ýüklemek & Tassyklamak",
|
||||
icon: Upload,
|
||||
validate: (form, mode) => validateStep(3, form, mode),
|
||||
id: "contact",
|
||||
titleKey: "cardOrder.step.contact",
|
||||
titleFallback: "Kontakt",
|
||||
subtitleKey: "orderNewCardForm.steps.contact.subtitle",
|
||||
subtitleFallback: "Salgy & Bellik",
|
||||
icon: MapPin,
|
||||
validate: (form) => validateStep(3, form),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -106,119 +98,113 @@ interface StepContentProps {
|
||||
|
||||
// ─── Step panels ──────────────────────────────────────────────────────────────
|
||||
|
||||
function StepCard({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
statusOptions,
|
||||
issuanceReasonOptions,
|
||||
cardTypeOptions,
|
||||
provinceOptions,
|
||||
branchOptions,
|
||||
}: StepContentProps & {
|
||||
statusOptions: SelectOption[];
|
||||
issuanceReasonOptions: SelectOption[];
|
||||
cardTypeOptions: SelectOption[];
|
||||
provinceOptions: SelectOption[];
|
||||
branchOptions: SelectOption[];
|
||||
}) {
|
||||
function StepCard({ form, errors, set, t }: StepContentProps) {
|
||||
const STATUS_OPTIONS = useMemo(
|
||||
() => [
|
||||
{ value: "PENDING", label: t("cardOrder.status.pending", "Garaşylýar") },
|
||||
{ value: "APPROVED", label: t("cardOrder.status.approved", "Tassyklandy") },
|
||||
{ value: "REJECTED", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("loanOrderForm.labels.status") || "Status"}
|
||||
label={t("cardOrder.field.status", "Status")}
|
||||
required
|
||||
value={form.status}
|
||||
onChange={(v) => set("status", v as CardOrderStatus)}
|
||||
options={statusOptions}
|
||||
onChange={(v) => set("status", v)}
|
||||
options={STATUS_OPTIONS}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.status}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.uniqueId", "Sargyt belgisi")}
|
||||
required
|
||||
value={form.uniqueId}
|
||||
onChange={(v) => set("uniqueId", v)}
|
||||
placeholder={t("cardOrder.field.uniqueId", "Sargyt belgisi")}
|
||||
error={errors.uniqueId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="paid"
|
||||
type="checkbox"
|
||||
checked={form.paid}
|
||||
onChange={(e) => set("paid", e.target.checked)}
|
||||
className="w-4 h-4 accent-primary cursor-pointer"
|
||||
/>
|
||||
<label
|
||||
htmlFor="paid"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
|
||||
>
|
||||
{t("cardOrder.field.paid", "Tölenen")}
|
||||
</label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t("Note") || "Bellik"}
|
||||
value={form.note}
|
||||
onChange={(v) => set("note", v)}
|
||||
label={t("cardOrder.field.notes", "Bellik")}
|
||||
value={form.notes}
|
||||
onChange={(v) => set("notes", v)}
|
||||
placeholder={t("loanOrderForm.placeholders.note") || "Bellik..."}
|
||||
rows={3}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
id="isPaid"
|
||||
type="checkbox"
|
||||
checked={form.isPaid}
|
||||
onChange={(e) => set("isPaid", e.target.checked)}
|
||||
className="w-4 h-4 accent-primary cursor-pointer"
|
||||
/>
|
||||
<label
|
||||
htmlFor="isPaid"
|
||||
className="text-xs font-semibold text-muted-foreground uppercase tracking-wider cursor-pointer select-none"
|
||||
>
|
||||
{t("orderNewCardForm.isPaid") || "Tölenen"}
|
||||
</label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<BentoCard title={t("loanOrderForm.titles.cardInfo") || "Kart maglumatlary"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Reason for issuing the card") || "Kartyň çykarylmagynyň sebäbi"}
|
||||
required
|
||||
value={form.issuanceReasonId}
|
||||
onChange={(v) => set("issuanceReasonId", v)}
|
||||
options={issuanceReasonOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
error={errors.issuanceReasonId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Card type") || "Kart görnüşi"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.cardTypeId", "Kart görnüşi ID")}
|
||||
required
|
||||
value={form.cardTypeId}
|
||||
onChange={(v) => set("cardTypeId", v)}
|
||||
options={cardTypeOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
placeholder={t("cardOrder.field.cardTypeId", "Kart görnüşi ID")}
|
||||
error={errors.cardTypeId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Region") || "Welaýat"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.cardStateId", "Kart ýagdaýy ID")}
|
||||
required
|
||||
value={form.provinceId}
|
||||
onChange={(v) => {
|
||||
set("provinceId", v);
|
||||
set("branchId", "");
|
||||
}}
|
||||
options={provinceOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.provinceId}
|
||||
value={form.cardStateId}
|
||||
onChange={(v) => set("cardStateId", v)}
|
||||
placeholder={t("cardOrder.field.cardStateId", "Kart ýagdaýy ID")}
|
||||
error={errors.cardStateId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
|
||||
<BentoCard title={t("cardPinForm.titles.location") || "Lokasiýa"}>
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t("Branch") || "Şahamça"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.region", "Sebit")}
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder={t("cardOrder.field.region", "Sebit")}
|
||||
error={errors.region}
|
||||
/>
|
||||
<FormInput
|
||||
type="number"
|
||||
label={t("cardOrder.field.branchId", "Şahamça ID")}
|
||||
required
|
||||
value={form.branchId}
|
||||
onChange={(v) => set("branchId", v)}
|
||||
options={branchOptions}
|
||||
disabled={!form.provinceId}
|
||||
placeholder={t("loanOrderForm.placeholders.searchableSelect") || "Saýlamak üçin basyň"}
|
||||
placeholder={t("cardOrder.field.branchId", "Şahamça ID")}
|
||||
error={errors.branchId}
|
||||
/>
|
||||
</BentoCard>
|
||||
@@ -227,69 +213,39 @@ function StepCard({
|
||||
);
|
||||
}
|
||||
|
||||
function StepPersonal({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
citizenshipOptions,
|
||||
}: StepContentProps & {
|
||||
citizenshipOptions: SelectOption[];
|
||||
}) {
|
||||
function StepPersonal({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Name") || "Ady"}
|
||||
label={t("cardOrder.field.customerName", "Ady")}
|
||||
required
|
||||
value={form.firstName}
|
||||
onChange={(v) => set("firstName", v)}
|
||||
placeholder={t("Name") || "Ady"}
|
||||
error={errors.firstName}
|
||||
value={form.customerName}
|
||||
onChange={(v) => set("customerName", v)}
|
||||
placeholder={t("cardOrder.field.customerName", "Ady")}
|
||||
error={errors.customerName}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Surname") || "Familiýasy"}
|
||||
label={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
required
|
||||
value={form.lastName}
|
||||
onChange={(v) => set("lastName", v)}
|
||||
placeholder={t("Surname") || "Familiýasy"}
|
||||
error={errors.lastName}
|
||||
value={form.customerSurname}
|
||||
onChange={(v) => set("customerSurname", v)}
|
||||
placeholder={t("cardOrder.field.customerSurname", "Familiýasy")}
|
||||
error={errors.customerSurname}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Patronic name") || "Atasynyň ady"}
|
||||
value={form.middleName}
|
||||
onChange={(v) => set("middleName", v)}
|
||||
placeholder={t("Patronic name") || "Atasynyň ady"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Old surname (if changed)") || "Köne familiýaňyz (eger üýtgän bolsa)"}
|
||||
value={form.formerLastName}
|
||||
onChange={(v) => set("formerLastName", v)}
|
||||
placeholder={t("orderNewCardForm.placeholders.formerLastName") || "Köne familiýaňyz"}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Date of birth") || "Doglan güni"}
|
||||
required
|
||||
value={form.birthDate}
|
||||
onChange={(v) => set("birthDate", v)}
|
||||
error={errors.birthDate}
|
||||
label={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
value={form.customerPatronicName}
|
||||
onChange={(v) => set("customerPatronicName", v)}
|
||||
placeholder={t("cardOrder.field.customerPatronicName", "Atasynyň ady")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -297,32 +253,103 @@ function StepPersonal({
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("Phone") || "Telefon"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.oldSurname", "Köne familiýaňyz (eger üýtgän bolsa)")}
|
||||
value={form.oldSurname}
|
||||
onChange={(v) => set("oldSurname", v)}
|
||||
placeholder={t("cardOrder.field.oldSurname", "Köne familiýa")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.bornAt", "Doglan güni")}
|
||||
value={form.bornAt}
|
||||
onChange={(v) => set("bornAt", v)}
|
||||
error={errors.bornAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
value={form.bornPlace}
|
||||
onChange={(v) => set("bornPlace", v)}
|
||||
placeholder={t("cardOrder.field.bornPlace", "Doglan ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||
required
|
||||
value={form.citizenship}
|
||||
onChange={(v) => set("citizenship", v)}
|
||||
placeholder={t("cardOrder.field.citizenship", "Raýatlyk")}
|
||||
error={errors.citizenship}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.phone", "Telefon")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set("phone", v)}
|
||||
placeholder={t("cardOrder.field.phone", "Telefon")}
|
||||
error={errors.phone}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t("Phone Additional") || "Telefon goşmaça"}
|
||||
value={form.phoneExtra}
|
||||
onChange={(v) => set("phoneExtra", v)}
|
||||
error={errors.phoneExtra}
|
||||
type="text"
|
||||
label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
value={form.phoneAdditional}
|
||||
onChange={(v) => set("phoneAdditional", v)}
|
||||
placeholder={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
||||
required
|
||||
value={form.passportSerie}
|
||||
onChange={(v) => set("passportSerie", v)}
|
||||
placeholder={t("cardOrder.field.passportSerie", "Pasport seriýasy")}
|
||||
error={errors.passportSerie}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Citizenship") || "Raýatlyk"}
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
required
|
||||
value={form.citizenship}
|
||||
onChange={(v) => set("citizenship", v)}
|
||||
options={citizenshipOptions}
|
||||
error={errors.citizenship}
|
||||
value={form.passportId}
|
||||
onChange={(v) => set("passportId", v)}
|
||||
placeholder={t("cardOrder.field.passportId", "Pasport belgisi")}
|
||||
error={errors.passportId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("cardOrder.field.passportGivenAt", "Pasport berlen senesi")}
|
||||
value={form.passportGivenAt}
|
||||
onChange={(v) => set("passportGivenAt", v)}
|
||||
error={errors.passportGivenAt}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -331,23 +358,85 @@ function StepPersonal({
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.registeredAddress") || "Ýazgy edilen salgyňyz"}
|
||||
required
|
||||
value={form.registeredAddress}
|
||||
onChange={(v) => set("registeredAddress", v)}
|
||||
placeholder={t("orderNewCardForm.labels.registeredAddress") || "Ýazgy edilen salgyňyz"}
|
||||
error={errors.registeredAddress}
|
||||
label={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
value={form.passportGivenBy}
|
||||
onChange={(v) => set("passportGivenBy", v)}
|
||||
placeholder={t("cardOrder.field.passportGivenBy", "Kim tarapyndan berildi")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.currentAddress") || "Häzirki ýaşaýyş ýeri"}
|
||||
required
|
||||
value={form.currentAddress}
|
||||
onChange={(v) => set("currentAddress", v)}
|
||||
placeholder={t("orderNewCardForm.labels.currentAddress") || "Häzirki ýaşaýyş ýeri"}
|
||||
error={errors.currentAddress}
|
||||
label={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||
value={form.passportAddress}
|
||||
onChange={(v) => set("passportAddress", v)}
|
||||
placeholder={t("cardOrder.field.passportAddress", "Pasport salgysy")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
value={form.passportOne}
|
||||
onChange={(v) => set("passportOne", v)}
|
||||
placeholder={t("cardOrder.field.passportOne", "Pasport 1")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
value={form.passportTwo}
|
||||
onChange={(v) => set("passportTwo", v)}
|
||||
placeholder={t("cardOrder.field.passportTwo", "Pasport 2")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
value={form.passportThree}
|
||||
onChange={(v) => set("passportThree", v)}
|
||||
placeholder={t("cardOrder.field.passportThree", "Pasport 3")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
value={form.passportFour}
|
||||
onChange={(v) => set("passportFour", v)}
|
||||
placeholder={t("cardOrder.field.passportFour", "Pasport 4")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepContact({ form, errors, set, t }: StepContentProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.realAddress", "Hakyky ýaşaýyş ýeri")}
|
||||
value={form.realAddress}
|
||||
onChange={(v) => set("realAddress", v)}
|
||||
placeholder={t("cardOrder.field.realAddress", "Hakyky ýaşaýyş ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("cardOrder.field.jobLocation", "Işleýän ýeri we wezipäňiz")}
|
||||
value={form.jobLocation}
|
||||
onChange={(v) => set("jobLocation", v)}
|
||||
placeholder={t("cardOrder.field.jobLocation", "Işleýän ýeri")}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -355,13 +444,13 @@ function StepPersonal({
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("orderNewCardForm.labels.workplace") || "Işleýän ýeriňiz we wezipäňiz"}
|
||||
type="number"
|
||||
label={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
required
|
||||
value={form.workplace}
|
||||
onChange={(v) => set("workplace", v)}
|
||||
placeholder={t("orderNewCardForm.labels.workplace") || "Işleýän ýeriňiz we wezipäňiz"}
|
||||
error={errors.workplace}
|
||||
value={form.userId}
|
||||
onChange={(v) => set("userId", v)}
|
||||
placeholder={t("cardOrder.field.userId", "Ulanyjy ID")}
|
||||
error={errors.userId}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
@@ -369,198 +458,14 @@ function StepPersonal({
|
||||
);
|
||||
}
|
||||
|
||||
function StepPassport({
|
||||
form,
|
||||
errors,
|
||||
set,
|
||||
t,
|
||||
passportSeriesOptions,
|
||||
}: StepContentProps & {
|
||||
passportSeriesOptions: SelectOption[];
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
label={t("Passport serie") || "Pasport seriýasy"}
|
||||
required
|
||||
value={form.passportSeriesId}
|
||||
onChange={(v) => set("passportSeriesId", v)}
|
||||
options={passportSeriesOptions}
|
||||
placeholder={t("loanOrderForm.placeholders.select") || "Saýlaň"}
|
||||
error={errors.passportSeriesId}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport id") || "Pasport belgisi"}
|
||||
required
|
||||
value={form.passportNumber}
|
||||
onChange={(v) => set("passportNumber", v)}
|
||||
placeholder={t("Passport id") || "Pasport belgisi"}
|
||||
error={errors.passportNumber}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="date"
|
||||
label={t("Passport date of issue") || "Pasport berlen senesi"}
|
||||
required
|
||||
value={form.passportIssueDate}
|
||||
onChange={(v) => set("passportIssueDate", v)}
|
||||
error={errors.passportIssueDate}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Passport given by") || "Kim tarapyndan berildi"}
|
||||
required
|
||||
value={form.passportIssuedBy}
|
||||
onChange={(v) => set("passportIssuedBy", v)}
|
||||
placeholder={t("Passport given by") || "Kim tarapyndan berildi"}
|
||||
error={errors.passportIssuedBy}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("Born place (passport)") || "Doglan ýeri (pasport)"}
|
||||
required
|
||||
value={form.passportBirthPlace}
|
||||
onChange={(v) => set("passportBirthPlace", v)}
|
||||
placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"}
|
||||
error={errors.passportBirthPlace}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepFiles({ form, errors, set, t, mode, initialData }: StepContentProps & { mode: "create" | "edit"; initialData?: CardOrder }) {
|
||||
const existingFiles =
|
||||
mode === "edit" && initialData
|
||||
? [
|
||||
{ url: initialData.passportFiles.page1, label: t("Passport (page 1)") || "Pasport (sahypa 1)" },
|
||||
{ url: initialData.passportFiles.page23, label: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)" },
|
||||
{ url: initialData.passportFiles.page89, label: t("Passport (page 8-9)") || "Pasport (8-9 sahypa)" },
|
||||
{ url: initialData.passportFiles.page32, label: t("Passport (page 32)") || "Pasport (32-nji sahypa)" },
|
||||
].filter((f): f is { url: string; label: string } => !!f.url)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{existingFiles.length > 0 && (
|
||||
<BentoGrid cols={4}>
|
||||
{existingFiles.map(({ url, label }) => (
|
||||
<BentoCard key={label} title={label}>
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" className="text-xs text-primary underline truncate block">
|
||||
{t("loanOrderForm.fileLabels.viewFile") || "Faýly gör"}
|
||||
</a>
|
||||
</BentoCard>
|
||||
))}
|
||||
</BentoGrid>
|
||||
)}
|
||||
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage1") || "Pasport (sahypa 1) (çalyşmak)"
|
||||
: t("Passport (page 1)") || "Pasport (sahypa 1)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage1}
|
||||
onFileChange={(f) => set("passportPage1", f)}
|
||||
error={errors.passportPage1}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={
|
||||
mode === "edit"
|
||||
? t("loanOrderForm.fileLabels.replacePage23") || "Pasport (2-3-nji sahypa) (çalyşmak)"
|
||||
: t("Passport (page 2-3)") || "Pasport (2-3-nji sahypa)"
|
||||
}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage23}
|
||||
onFileChange={(f) => set("passportPage23", f)}
|
||||
error={errors.passportPage23}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t("Passport (page 8-9)") || "Pasport (8-9 sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage89}
|
||||
onFileChange={(f) => set("passportPage89", f)}
|
||||
error={errors.passportPage89}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="file"
|
||||
label={t("Passport (page 32)") || "Pasport (32-nji sahypa)"}
|
||||
required={mode === "create"}
|
||||
accept="image/*,.pdf"
|
||||
fileValue={form.passportPage32}
|
||||
onFileChange={(f) => set("passportPage32", f)}
|
||||
error={errors.passportPage32}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{mode === "create" && (
|
||||
<BentoGrid cols={1}>
|
||||
<BentoCard>
|
||||
<div
|
||||
className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors
|
||||
${errors.termsAccepted ? "bg-destructive/10 border border-destructive/30" : "bg-primary/5 border border-primary/20"}`}
|
||||
onClick={() => set("termsAccepted", !form.termsAccepted)}
|
||||
>
|
||||
<div
|
||||
className={`w-5 h-5 rounded flex items-center justify-center shrink-0 transition-colors
|
||||
${form.termsAccepted ? "bg-primary text-primary-foreground" : "border border-border bg-background"}`}
|
||||
>
|
||||
{form.termsAccepted && (
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none">
|
||||
<path d="M2 6L5 9L10 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<span className={`text-sm font-medium ${errors.termsAccepted ? "text-destructive" : "text-primary"}`}>
|
||||
{t("I accept terms of contract") || "Şertnama bilen razylaşýaryn (Okamak üçin bas)"}
|
||||
</span>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ───────────────────────────────────────────────────────────
|
||||
|
||||
export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateCardOrder();
|
||||
const updateMutation = useUpdateCardOrder(initialData?.id ?? "");
|
||||
const createMutation = useCreateCard();
|
||||
const updateMutation = useUpdateCard(initialData?.id ?? 0);
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const {
|
||||
@@ -579,42 +484,16 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [submittedSteps, setSubmittedSteps] = useState<Set<number>>(new Set());
|
||||
|
||||
// ── Lookup data ────────────────────────────────────────────────────────────
|
||||
|
||||
const { data: reasons = [] } = useCardIssuanceReasons();
|
||||
const { data: cardTypes = [] } = useCardTypes();
|
||||
const { data: provinces = [] } = useProvinces();
|
||||
const { data: branches = [] } = useBranches(form.provinceId ? Number(form.provinceId) : undefined);
|
||||
|
||||
const toOptions = (arr: { id: number; name: string }[]): SelectOption[] => arr.map((x) => ({ value: String(x.id), label: x.name }));
|
||||
|
||||
const statusOptions: SelectOption[] = [
|
||||
{ value: "PENDING", label: t("cardOrder.status.pending", "Garaşylýar") },
|
||||
{ value: "APPROVED", label: t("cardOrder.status.approved", "Tassyklandy") },
|
||||
{ value: "REJECTED", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
||||
];
|
||||
|
||||
const citizenshipOptions: SelectOption[] = [
|
||||
{ value: "Turkmenistan", label: t("citizenship.tm", "Turkmenistan") },
|
||||
{ value: "Russia", label: t("citizenship.ru", "Russiýa") },
|
||||
{ value: "Other", label: t("citizenship.other", "Beýlekiler") },
|
||||
];
|
||||
|
||||
const passportSeriesOptions: SelectOption[] = [
|
||||
{ value: "1", label: "I" },
|
||||
{ value: "2", label: "II" },
|
||||
{ value: "3", label: "III" },
|
||||
];
|
||||
|
||||
// ── Computed step error state ──────────────────────────────────────────────
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i);
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, visited, i18n.language]);
|
||||
|
||||
// ── set helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -626,14 +505,19 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const currentStepErrors = useMemo(
|
||||
() => (submittedSteps.has(currentStep) ? STEPS[currentStep].validate(form, mode) : {}),
|
||||
[currentStep, form, mode, submittedSteps],
|
||||
);
|
||||
const allSubmittedErrors = useMemo(() => {
|
||||
const result: FlatErrors = {};
|
||||
for (const stepIdx of submittedSteps) {
|
||||
Object.assign(result, STEPS[stepIdx].validate(form));
|
||||
}
|
||||
return result;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form, submittedSteps, i18n.language]);
|
||||
|
||||
const errors = useMemo(() => {
|
||||
const fromRHF = flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>);
|
||||
return { ...fromRHF, ...currentStepErrors };
|
||||
}, [rhfErrors, currentStepErrors]);
|
||||
return { ...fromRHF, ...allSubmittedErrors };
|
||||
}, [rhfErrors, allSubmittedErrors]);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t }), [form, errors, set, t]);
|
||||
|
||||
@@ -646,7 +530,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
const handleNext = () => {
|
||||
markVisited(currentStep);
|
||||
markSubmitted(currentStep);
|
||||
const errs = STEPS[currentStep].validate(form, mode);
|
||||
const errs = STEPS[currentStep].validate(form);
|
||||
if (Object.keys(errs).length > 0) {
|
||||
Object.entries(errs).forEach(([key, msg]) => {
|
||||
setError(key as keyof OrderNewCardFormData, { type: "manual", message: msg });
|
||||
@@ -681,7 +565,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
setSubmittedSteps(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const allErrors: FlatErrors = {};
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode));
|
||||
for (const step of STEPS) Object.assign(allErrors, step.validate(form));
|
||||
|
||||
if (Object.keys(allErrors).length > 0) {
|
||||
Object.entries(allErrors).forEach(([key, msg]) => {
|
||||
@@ -689,7 +573,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
});
|
||||
toast.error(t("validation.fixErrors", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode)).length > 0) {
|
||||
if (Object.keys(STEPS[i].validate(form)).length > 0) {
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
@@ -703,7 +587,7 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
if (mode === "edit") {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
} else {
|
||||
await createMutation.mutateAsync(payload as CreateCardOrderPayload);
|
||||
await createMutation.mutateAsync(payload);
|
||||
}
|
||||
navigate("/order-new-card");
|
||||
} catch {
|
||||
@@ -733,12 +617,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{mode === "create" ? t("cardOrder.createTitle") || "Täze karz orderi" : t("cardOrder.editTitle") || "Karz orderini üýtget"}
|
||||
{mode === "create" ? t("cardOrder.createTitle", "Täze kart sargydy") : t("cardOrder.editTitle", "Kart sargydyny üýtget")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{mode === "create"
|
||||
? t("loanOrders.createDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."
|
||||
: t("loanOrders.editDescription") || "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň."}
|
||||
{t("loanOrders.createDescription", "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.")}
|
||||
</p>
|
||||
{/* Step bar */}
|
||||
<div className="bg-card border border-border rounded-xl p-3 overflow-x-auto">
|
||||
@@ -746,19 +628,10 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
</div>
|
||||
|
||||
{/* Step content */}
|
||||
{currentStep === 0 && (
|
||||
<StepCard
|
||||
{...stepProps}
|
||||
statusOptions={statusOptions}
|
||||
issuanceReasonOptions={toOptions(reasons)}
|
||||
cardTypeOptions={toOptions(cardTypes)}
|
||||
provinceOptions={toOptions(provinces)}
|
||||
branchOptions={toOptions(branches)}
|
||||
/>
|
||||
)}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} citizenshipOptions={citizenshipOptions} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} passportSeriesOptions={passportSeriesOptions} />}
|
||||
{currentStep === 3 && <StepFiles {...stepProps} mode={mode} initialData={initialData} />}
|
||||
{currentStep === 0 && <StepCard {...stepProps} />}
|
||||
{currentStep === 1 && <StepPersonal {...stepProps} />}
|
||||
{currentStep === 2 && <StepPassport {...stepProps} />}
|
||||
{currentStep === 3 && <StepContact {...stepProps} />}
|
||||
|
||||
{/* Actions */}
|
||||
<FormActions
|
||||
@@ -768,11 +641,11 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={mode === "create" ? t("cardOrder.submit") || "Kart sargyt dörediň" : t("common.save") || "Ýatda sakla"}
|
||||
loadingLabel={t("common.saving") || "Ýüklenilýär..."}
|
||||
cancelLabel={t("common.cancel") || "Ýatyr"}
|
||||
prevLabel={t("common.prev") || "Yza"}
|
||||
nextLabel={t("common.next") || "Indiki"}
|
||||
submitLabel={mode === "create" ? t("cardOrder.submit", "Kart sargyt dörediň") : t("common.save", "Ýatda sakla")}
|
||||
loadingLabel={t("common.saving", "Ýüklenilýär...")}
|
||||
cancelLabel={t("common.cancel", "Ýatyr")}
|
||||
prevLabel={t("common.prev", "Yza")}
|
||||
nextLabel={t("common.next", "Indiki")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -780,28 +653,34 @@ export function CardOrderForm({ mode, initialData }: CardOrderFormProps) {
|
||||
|
||||
function mapInitial(data: CardOrder): Partial<OrderNewCardFormData> {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
uniqueId: data.uniqueId,
|
||||
status: data.status,
|
||||
note: data.note ?? "",
|
||||
issuanceReasonId: String(data.issuanceReasonId),
|
||||
cardTypeId: String(data.cardTypeId),
|
||||
provinceId: String(data.provinceId),
|
||||
branchId: String(data.branchId),
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
middleName: data.middleName ?? "",
|
||||
formerLastName: data.formerLastName ?? "",
|
||||
birthDate: data.birthDate,
|
||||
phone: data.phone,
|
||||
phoneExtra: data.phoneExtra ?? "",
|
||||
citizenship: data.citizenship,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: String(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
paid: data.paid,
|
||||
cardStateId: String(data.cardStateId ?? ""),
|
||||
cardTypeId: String(data.cardTypeId ?? ""),
|
||||
region: data.region ?? "",
|
||||
branchId: String(data.branchId ?? ""),
|
||||
customerName: data.customerName,
|
||||
customerSurname: data.customerSurname,
|
||||
customerPatronicName: data.customerPatronicName ?? "",
|
||||
oldSurname: data.oldSurname ?? "",
|
||||
bornAt: data.bornAt ? data.bornAt.slice(0, 10) : "",
|
||||
bornPlace: data.bornPlace ?? "",
|
||||
citizenship: data.citizenship ?? "",
|
||||
phone: data.phone ?? "",
|
||||
phoneAdditional: data.phoneAdditional ?? "",
|
||||
passportSerie: data.passportSerie,
|
||||
passportId: data.passportId,
|
||||
passportOne: data.passportOne ?? "",
|
||||
passportTwo: data.passportTwo ?? "",
|
||||
passportThree: data.passportThree ?? "",
|
||||
passportFour: data.passportFour ?? "",
|
||||
passportGivenAt: data.passportGivenAt ? data.passportGivenAt.slice(0, 10) : "",
|
||||
passportGivenBy: data.passportGivenBy ?? "",
|
||||
passportAddress: data.passportAddress ?? "",
|
||||
realAddress: data.realAddress ?? "",
|
||||
jobLocation: data.jobLocation ?? "",
|
||||
userId: String(data.userId ?? ""),
|
||||
notes: data.notes ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,138 +1,87 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
fetchCardOrders,
|
||||
fetchCardOrderById,
|
||||
createCardOrder,
|
||||
updateCardOrder,
|
||||
deleteCardOrder,
|
||||
fetchCardIssuanceReasons,
|
||||
fetchCardTypes,
|
||||
fetchProvinces,
|
||||
fetchBranches,
|
||||
} from '../api/orderNewCardApi'
|
||||
import type {
|
||||
CardOrderFilters,
|
||||
CreateCardOrderPayload,
|
||||
UpdateCardOrderPayload,
|
||||
} from '../api/orderNewCardApi'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { fetchCardOrders, fetchCardOrderById, createCardOrder, updateCardOrder, deleteCardOrder } from "../api/orderNewCardApi";
|
||||
import type { CardOrderListParams, CreateCardOrderPayload, UpdateCardOrderPayload } from "../api/orderNewCardApi";
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const cardOrderKeys = {
|
||||
all: ['card-orders'] as const,
|
||||
lists: () => [...cardOrderKeys.all, 'list'] as const,
|
||||
list: (f: CardOrderFilters) => [...cardOrderKeys.lists(), f] as const,
|
||||
details: () => [...cardOrderKeys.all, 'detail'] as const,
|
||||
detail: (id: string) => [...cardOrderKeys.details(), id] as const,
|
||||
reasons: ['card-order-reasons'] as const,
|
||||
types: ['card-order-types'] as const,
|
||||
provinces: ['provinces'] as const,
|
||||
branches: (provinceId?: number) => ['branches', provinceId] as const,
|
||||
}
|
||||
all: ["card-orders"] as const,
|
||||
lists: () => [...cardOrderKeys.all, "list"] as const,
|
||||
list: (p: CardOrderListParams) => [...cardOrderKeys.lists(), p] as const,
|
||||
details: () => [...cardOrderKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...cardOrderKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── List ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardOrders(filters: CardOrderFilters) {
|
||||
export function useCards(params?: CardOrderListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params?.search ?? "");
|
||||
const queryParams: CardOrderListParams = { ...(params ?? {}), search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.list(filters),
|
||||
queryFn: () => fetchCardOrders(filters),
|
||||
queryKey: cardOrderKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchCardOrders(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Single ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardOrderById(id: string) {
|
||||
export function useCardById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.detail(id),
|
||||
queryFn: () => fetchCardOrderById(id),
|
||||
enabled: Boolean(id),
|
||||
})
|
||||
queryFn: () => fetchCardOrderById(id),
|
||||
enabled: Boolean(id),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateCardOrder() {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useCreateCard() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateCardOrderPayload) => createCardOrder(payload),
|
||||
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
|
||||
toast.success(t('cardOrder.createSuccess', 'Kart sargyt üstünlikli döredildi'))
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.createSuccess", "Kart sargydy üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateCardOrder(id: string) {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useUpdateCard(id: number) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateCardOrderPayload) => updateCardOrder(id, payload),
|
||||
|
||||
onSuccess: (updated) => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
|
||||
qc.setQueryData(cardOrderKeys.detail(id), updated)
|
||||
toast.success(t('cardOrder.updateSuccess', 'Kart sargyt üstünlikli täzelendi'))
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.updateSuccess", "Kart sargydy üstünlikli täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Delete ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteCardOrder() {
|
||||
const { t } = useTranslation()
|
||||
const qc = useQueryClient()
|
||||
export function useDeleteCard() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => deleteCardOrder(id),
|
||||
mutationFn: (id: number) => deleteCardOrder(id),
|
||||
|
||||
onSuccess: (_, id) => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.lists() })
|
||||
qc.removeQueries({ queryKey: cardOrderKeys.detail(id) })
|
||||
toast.success(t('cardOrder.deleteSuccess', 'Kart sargyt üstünlikli pozuldy'))
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: cardOrderKeys.all });
|
||||
toast.success(t("cardOrder.deleteSuccess", "Kart sargydy üstünlikli pozuldy"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Lookup hooks ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCardIssuanceReasons() {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.reasons,
|
||||
queryFn: fetchCardIssuanceReasons,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCardTypes() {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.types,
|
||||
queryFn: fetchCardTypes,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
}
|
||||
|
||||
export function useProvinces() {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.provinces,
|
||||
queryFn: fetchProvinces,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
}
|
||||
|
||||
export function useBranches(provinceId?: number) {
|
||||
return useQuery({
|
||||
queryKey: cardOrderKeys.branches(provinceId),
|
||||
queryFn: () => fetchBranches(provinceId),
|
||||
enabled: provinceId !== undefined && provinceId !== 0,
|
||||
staleTime: Infinity,
|
||||
})
|
||||
}
|
||||
@@ -1,122 +1,72 @@
|
||||
import { z } from "zod";
|
||||
import i18next from "i18next";
|
||||
import type { CardOrderStatus } from "../api/orderNewCardApi";
|
||||
import type { CreateCardOrderPayload } from "../api/orderNewCardApi";
|
||||
|
||||
const fileRequired = z.custom<File>((val) => val instanceof File, "validation.requiredFile");
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
const optional = () => z.string().default("");
|
||||
|
||||
export const orderNewCardFormSchema = z.object({
|
||||
isPaid: z.boolean(),
|
||||
uniqueId: z.string().min(1, "validation.required"),
|
||||
status: z.string().min(1, "validation.required"),
|
||||
note: z.string().optional(),
|
||||
issuanceReasonId: z.string().min(1, "validation.required"),
|
||||
paid: z.boolean(),
|
||||
cardStateId: z.string().min(1, "validation.required"),
|
||||
cardTypeId: z.string().min(1, "validation.required"),
|
||||
provinceId: z.string().min(1, "validation.required"),
|
||||
region: z.string().min(1, "validation.required"),
|
||||
branchId: z.string().min(1, "validation.required"),
|
||||
firstName: z.string().min(1, "validation.required"),
|
||||
lastName: z.string().min(1, "validation.required"),
|
||||
middleName: z.string().optional(),
|
||||
formerLastName: z.string().optional(),
|
||||
birthDate: z.string().min(1, "validation.required"),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, "validation.required")
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
const prefix = digits.slice(0, 2);
|
||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
),
|
||||
phoneExtra: z
|
||||
.string()
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: "validation.invalidPhone" },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.replace(/\D/g, "").length === 0) return true;
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return VALID_PHONE_PREFIXES.includes(digits.slice(0, 2));
|
||||
},
|
||||
{ message: "validation.invalidPhonePrefix" },
|
||||
)
|
||||
.optional(),
|
||||
customerName: z.string().min(1, "validation.required"),
|
||||
customerSurname: z.string().min(1, "validation.required"),
|
||||
customerPatronicName: optional(),
|
||||
oldSurname: optional(),
|
||||
bornAt: optional(),
|
||||
bornPlace: optional(),
|
||||
citizenship: z.string().min(1, "validation.required"),
|
||||
registeredAddress: z.string().min(1, "validation.required"),
|
||||
currentAddress: z.string().min(1, "validation.required"),
|
||||
workplace: z.string().min(1, "validation.required"),
|
||||
passportSeriesId: z.string().min(1, "validation.required"),
|
||||
passportNumber: z.string().min(1, "validation.required"),
|
||||
passportIssueDate: z.string().min(1, "validation.required"),
|
||||
passportIssuedBy: z.string().min(1, "validation.required"),
|
||||
passportBirthPlace: z.string().min(1, "validation.required"),
|
||||
passportPage1: z.custom<File | null>().nullable(),
|
||||
passportPage23: z.custom<File | null>().nullable(),
|
||||
passportPage89: z.custom<File | null>().nullable(),
|
||||
passportPage32: z.custom<File | null>().nullable(),
|
||||
termsAccepted: z.boolean(),
|
||||
phone: z.string().min(1, "validation.required"),
|
||||
phoneAdditional: optional(),
|
||||
passportSerie: z.string().min(1, "validation.required"),
|
||||
passportId: z.string().min(1, "validation.required"),
|
||||
passportOne: optional(),
|
||||
passportTwo: optional(),
|
||||
passportThree: optional(),
|
||||
passportFour: optional(),
|
||||
passportGivenAt: optional(),
|
||||
passportGivenBy: optional(),
|
||||
passportAddress: optional(),
|
||||
realAddress: optional(),
|
||||
jobLocation: optional(),
|
||||
userId: z.string().min(1, "validation.required"),
|
||||
notes: optional(),
|
||||
});
|
||||
|
||||
export type OrderNewCardFormData = z.infer<typeof orderNewCardFormSchema>;
|
||||
|
||||
export const stepSchemas: Record<number, z.ZodType<Partial<OrderNewCardFormData>>> = {
|
||||
0: orderNewCardFormSchema.pick({
|
||||
uniqueId: true,
|
||||
status: true,
|
||||
issuanceReasonId: true,
|
||||
cardStateId: true,
|
||||
cardTypeId: true,
|
||||
provinceId: true,
|
||||
region: true,
|
||||
branchId: true,
|
||||
}),
|
||||
1: orderNewCardFormSchema.pick({
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
birthDate: true,
|
||||
phone: true,
|
||||
phoneExtra: true,
|
||||
customerName: true,
|
||||
customerSurname: true,
|
||||
citizenship: true,
|
||||
registeredAddress: true,
|
||||
currentAddress: true,
|
||||
workplace: true,
|
||||
phone: true,
|
||||
}),
|
||||
2: orderNewCardFormSchema.pick({
|
||||
passportSeriesId: true,
|
||||
passportNumber: true,
|
||||
passportIssueDate: true,
|
||||
passportIssuedBy: true,
|
||||
passportBirthPlace: true,
|
||||
passportSerie: true,
|
||||
passportId: true,
|
||||
}),
|
||||
3: z.object({
|
||||
passportPage1: fileRequired,
|
||||
passportPage23: fileRequired,
|
||||
passportPage89: fileRequired,
|
||||
passportPage32: fileRequired,
|
||||
termsAccepted: z.literal(true, { message: "validation.requiredTerms" }),
|
||||
3: orderNewCardFormSchema.pick({
|
||||
userId: true,
|
||||
}),
|
||||
};
|
||||
|
||||
export function validateStep(
|
||||
stepIndex: number,
|
||||
form: OrderNewCardFormData,
|
||||
mode: "create" | "edit",
|
||||
): Partial<Record<keyof OrderNewCardFormData, string>> {
|
||||
if (stepIndex === 3 && mode === "edit") return {};
|
||||
export function validateStep(stepIndex: number, form: OrderNewCardFormData): Partial<Record<keyof OrderNewCardFormData, string>> {
|
||||
const schema = stepSchemas[stepIndex];
|
||||
const result = schema.safeParse(form);
|
||||
if (result.success) return {};
|
||||
|
||||
const errors: Partial<Record<keyof OrderNewCardFormData, string>> = {};
|
||||
for (const issue of result.error.issues) {
|
||||
const key = issue.path[0] as keyof OrderNewCardFormData;
|
||||
@@ -129,64 +79,67 @@ export function validateStep(
|
||||
}
|
||||
|
||||
export const DEFAULT_FORM_VALUES: OrderNewCardFormData = {
|
||||
isPaid: false,
|
||||
uniqueId: "",
|
||||
status: "",
|
||||
note: "",
|
||||
issuanceReasonId: "",
|
||||
paid: false,
|
||||
cardStateId: "",
|
||||
cardTypeId: "",
|
||||
provinceId: "",
|
||||
region: "",
|
||||
branchId: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
middleName: "",
|
||||
formerLastName: "",
|
||||
birthDate: "",
|
||||
customerName: "",
|
||||
customerSurname: "",
|
||||
customerPatronicName: "",
|
||||
oldSurname: "",
|
||||
bornAt: "",
|
||||
bornPlace: "",
|
||||
citizenship: "",
|
||||
phone: "",
|
||||
phoneExtra: "",
|
||||
citizenship: "Turkmenistan",
|
||||
registeredAddress: "",
|
||||
currentAddress: "",
|
||||
workplace: "",
|
||||
passportSeriesId: "",
|
||||
passportNumber: "",
|
||||
passportIssueDate: "",
|
||||
passportIssuedBy: "",
|
||||
passportBirthPlace: "",
|
||||
passportPage1: null,
|
||||
passportPage23: null,
|
||||
passportPage89: null,
|
||||
passportPage32: null,
|
||||
termsAccepted: false,
|
||||
phoneAdditional: "",
|
||||
passportSerie: "",
|
||||
passportId: "",
|
||||
passportOne: "",
|
||||
passportTwo: "",
|
||||
passportThree: "",
|
||||
passportFour: "",
|
||||
passportGivenAt: "",
|
||||
passportGivenBy: "",
|
||||
passportAddress: "",
|
||||
realAddress: "",
|
||||
jobLocation: "",
|
||||
userId: "",
|
||||
notes: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: OrderNewCardFormData) {
|
||||
export function buildPayload(data: OrderNewCardFormData): CreateCardOrderPayload {
|
||||
return {
|
||||
isPaid: data.isPaid,
|
||||
status: data.status as CardOrderStatus,
|
||||
note: data.note || null,
|
||||
issuanceReasonId: Number(data.issuanceReasonId),
|
||||
uniqueId: data.uniqueId.trim(),
|
||||
status: data.status.trim(),
|
||||
paid: data.paid,
|
||||
cardStateId: Number(data.cardStateId),
|
||||
cardTypeId: Number(data.cardTypeId),
|
||||
provinceId: Number(data.provinceId),
|
||||
region: data.region.trim(),
|
||||
branchId: Number(data.branchId),
|
||||
firstName: data.firstName,
|
||||
lastName: data.lastName,
|
||||
middleName: data.middleName || null,
|
||||
formerLastName: data.formerLastName || null,
|
||||
birthDate: data.birthDate,
|
||||
phone: data.phone,
|
||||
phoneExtra: data.phoneExtra || null,
|
||||
citizenship: data.citizenship,
|
||||
registeredAddress: data.registeredAddress,
|
||||
currentAddress: data.currentAddress,
|
||||
workplace: data.workplace,
|
||||
passportSeriesId: Number(data.passportSeriesId),
|
||||
passportNumber: data.passportNumber,
|
||||
passportIssueDate: data.passportIssueDate,
|
||||
passportIssuedBy: data.passportIssuedBy,
|
||||
passportBirthPlace: data.passportBirthPlace,
|
||||
...(data.passportPage1 && { passportPage1: data.passportPage1 }),
|
||||
...(data.passportPage23 && { passportPage23: data.passportPage23 }),
|
||||
...(data.passportPage89 && { passportPage89: data.passportPage89 }),
|
||||
...(data.passportPage32 && { passportPage32: data.passportPage32 }),
|
||||
customerName: data.customerName.trim(),
|
||||
customerSurname: data.customerSurname.trim(),
|
||||
customerPatronicName: data.customerPatronicName.trim(),
|
||||
oldSurname: data.oldSurname.trim(),
|
||||
bornAt: data.bornAt.trim(),
|
||||
bornPlace: data.bornPlace.trim(),
|
||||
citizenship: data.citizenship.trim(),
|
||||
phone: data.phone.trim(),
|
||||
phoneAdditional: data.phoneAdditional.trim(),
|
||||
passportSerie: data.passportSerie.trim(),
|
||||
passportId: data.passportId.trim(),
|
||||
passportOne: data.passportOne.trim(),
|
||||
passportTwo: data.passportTwo.trim(),
|
||||
passportThree: data.passportThree.trim(),
|
||||
passportFour: data.passportFour.trim(),
|
||||
passportGivenAt: data.passportGivenAt.trim(),
|
||||
passportGivenBy: data.passportGivenBy.trim(),
|
||||
passportAddress: data.passportAddress.trim(),
|
||||
realAddress: data.realAddress.trim(),
|
||||
jobLocation: data.jobLocation.trim(),
|
||||
userId: Number(data.userId),
|
||||
notes: data.notes.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,134 +1,66 @@
|
||||
// import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface PermissionTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
}
|
||||
|
||||
export interface AuditLog {
|
||||
id: number
|
||||
action: string
|
||||
by: string
|
||||
target: string
|
||||
status: string
|
||||
date: string
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: number
|
||||
code: string
|
||||
name: PermissionTranslation
|
||||
guard_name: string
|
||||
audit_logs?: AuditLog[]
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PermissionPayload {
|
||||
code: string
|
||||
name: PermissionTranslation
|
||||
guard_name: string
|
||||
export interface PermissionsListResponse {
|
||||
count: number;
|
||||
permissions: Permission[];
|
||||
}
|
||||
|
||||
export interface PermissionsListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
export interface PermissionPayload {
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_PERMISSIONS: Permission[] = [
|
||||
{ id: 1, code: 'users.view', guard_name: 'web', name: { tk: 'Ulanyjylary görmek', ru: 'Просмотр пользователей', en: 'View users' } },
|
||||
{ id: 2, code: 'users.create', guard_name: 'web', name: { tk: 'Ulanyjy döretmek', ru: 'Создание пользователя', en: 'Create user' } },
|
||||
{ id: 3, code: 'users.edit', guard_name: 'web', name: { tk: 'Ulanyjyny üýtgetmek', ru: 'Редактирование пользователя', en: 'Edit user' } },
|
||||
{ id: 4, code: 'users.delete', guard_name: 'web', name: { tk: 'Ulanyjyny pozmak', ru: 'Удаление пользователя', en: 'Delete user' } },
|
||||
{ id: 5, code: 'roles.view', guard_name: 'web', name: { tk: 'Rollary görmek', ru: 'Просмотр ролей', en: 'View roles' } },
|
||||
{ id: 6, code: 'roles.create', guard_name: 'web', name: { tk: 'Rol döretmek', ru: 'Создание роли', en: 'Create role' } },
|
||||
{ id: 7, code: 'roles.edit', guard_name: 'web', name: { tk: 'Roly üýtgetmek', ru: 'Редактирование роли', en: 'Edit role' } },
|
||||
{ id: 8, code: 'roles.delete', guard_name: 'web', name: { tk: 'Roly pozmak', ru: 'Удаление роли', en: 'Delete role' } },
|
||||
{ id: 9, code: 'permissions.view', guard_name: 'web', name: { tk: 'Rugsatlary görmek', ru: 'Просмотр разрешений', en: 'View permissions' } },
|
||||
{ id: 10, code: 'permissions.edit', guard_name: 'web', name: { tk: 'Rugsady üýtgetmek', ru: 'Редактирование разрешения', en: 'Edit permission' } },
|
||||
]
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionsApi = {
|
||||
getAll: async (params?: PermissionsListParams): Promise<{ data: PaginatedResponse<Permission> }> => {
|
||||
await delay()
|
||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
||||
|
||||
let filtered = [...MOCK_PERMISSIONS]
|
||||
if (search) {
|
||||
const s = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(p) =>
|
||||
p.code.toLowerCase().includes(s) ||
|
||||
p.name.tk.toLowerCase().includes(s) ||
|
||||
p.name.ru.toLowerCase().includes(s) ||
|
||||
p.name.en.toLowerCase().includes(s)
|
||||
)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const last_page = Math.ceil(total / per_page)
|
||||
const start = (page - 1) * per_page
|
||||
const data = filtered.slice(start, start + per_page)
|
||||
|
||||
return {
|
||||
data: {
|
||||
data,
|
||||
meta: {
|
||||
current_page: page,
|
||||
last_page,
|
||||
per_page,
|
||||
total,
|
||||
},
|
||||
},
|
||||
}
|
||||
/** GET /permissions — backend filters by `permission_name` */
|
||||
getAll: async (params: PermissionsListParams = {}, signal?: AbortSignal): Promise<PermissionsListResponse> => {
|
||||
const { search, page, limit } = params;
|
||||
const { data } = await apiClient.get<PermissionsListResponse>("/permissions", {
|
||||
params: { page, limit, permission_name: search },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const item = MOCK_PERMISSIONS.find((p) => p.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { data: item }
|
||||
/** GET /permissions/:id */
|
||||
getById: async (id: number): Promise<Permission> => {
|
||||
const { data } = await apiClient.get<Permission>(`/permissions/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (payload: PermissionPayload): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const newItem: Permission = {
|
||||
...payload,
|
||||
id: Math.floor(Math.random() * 10000),
|
||||
}
|
||||
MOCK_PERMISSIONS.push(newItem)
|
||||
return { data: newItem }
|
||||
/** POST /permissions */
|
||||
create: async (payload: PermissionPayload): Promise<Permission> => {
|
||||
const { data } = await apiClient.post<Permission>("/permissions", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: number, payload: PermissionPayload): Promise<{ data: Permission }> => {
|
||||
await delay()
|
||||
const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id)
|
||||
if (index === -1) throw new Error('Not found')
|
||||
MOCK_PERMISSIONS[index] = { ...MOCK_PERMISSIONS[index], ...payload }
|
||||
return { data: MOCK_PERMISSIONS[index] }
|
||||
/** PUT /permissions/:id */
|
||||
update: async (id: number, payload: PermissionPayload): Promise<Permission> => {
|
||||
const { data } = await apiClient.put<Permission>(`/permissions/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** DELETE /permissions/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await delay()
|
||||
const index = MOCK_PERMISSIONS.findIndex((p) => p.id === id)
|
||||
if (index !== -1) MOCK_PERMISSIONS.splice(index, 1)
|
||||
await apiClient.delete(`/permissions/${id}`);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,12 +5,12 @@ import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { useCreatePermission, useUpdatePermission } from "../hooks/usePermissions";
|
||||
import { createPermissionFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/permission.schema";
|
||||
import type { PermissionFormData } from "../schemas/permission.schema";
|
||||
import type { Permission } from "../api/permissionsApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface PermissionFormProps {
|
||||
@@ -18,12 +18,6 @@ interface PermissionFormProps {
|
||||
initialData?: Permission;
|
||||
}
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: "web", label: "web" },
|
||||
{ value: "api", label: "api" },
|
||||
{ value: "sanctum", label: "sanctum" },
|
||||
];
|
||||
|
||||
type FlatErrors = Partial<Record<keyof PermissionFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
@@ -65,10 +59,8 @@ export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
nameTk: initialData.name.tk,
|
||||
nameRu: initialData.name.ru,
|
||||
nameEn: initialData.name.en,
|
||||
guard_name: initialData.guard_name,
|
||||
name: initialData.name,
|
||||
guardName: initialData.guardName,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
@@ -84,33 +76,6 @@ export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const nameFields = {
|
||||
tk: {
|
||||
value: form.nameTk,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameTk", v);
|
||||
clearErrors("nameTk");
|
||||
},
|
||||
error: errors.nameTk,
|
||||
},
|
||||
ru: {
|
||||
value: form.nameRu,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameRu", v);
|
||||
clearErrors("nameRu");
|
||||
},
|
||||
error: errors.nameRu,
|
||||
},
|
||||
en: {
|
||||
value: form.nameEn,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameEn", v);
|
||||
clearErrors("nameEn");
|
||||
},
|
||||
error: errors.nameEn,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
@@ -159,22 +124,27 @@ export function PermissionForm({ mode, initialData }: PermissionFormProps) {
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
type="text"
|
||||
label={t("permissions.fields.guardName", "Guard name")}
|
||||
value={form.guard_name}
|
||||
onChange={setField("guard_name")}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
value={form.guardName}
|
||||
onChange={setField("guardName")}
|
||||
placeholder="operator"
|
||||
error={errors.guardName}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("permissions.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("permissions.fields.name", "Ady")} disabled={isPending} />
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("permissions.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={setField("name")}
|
||||
placeholder={t("permissions.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
permissionsApi,
|
||||
type PermissionPayload,
|
||||
type PermissionsListParams,
|
||||
} from '../api/permissionsApi'
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { permissionsApi, type PermissionPayload, type PermissionsListParams } from "../api/permissionsApi";
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const permissionKeys = {
|
||||
all: ['permissions'] as const,
|
||||
list: (params: PermissionsListParams) => ['permissions', 'list', params] as const,
|
||||
detail: (id: number) => ['permissions', 'detail', id] as const,
|
||||
}
|
||||
all: ["permissions"] as const,
|
||||
lists: () => ["permissions", "list"] as const,
|
||||
list: (params: PermissionsListParams) => ["permissions", "list", params] as const,
|
||||
detail: (id: number) => ["permissions", "detail", id] as const,
|
||||
};
|
||||
|
||||
// ─── usePermissions (list) ────────────────────────────────────────────────────
|
||||
|
||||
export function usePermissions(params: PermissionsListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: PermissionsListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.list(params),
|
||||
queryFn: () => permissionsApi.getAll(params).then((r) => r.data),
|
||||
})
|
||||
queryKey: permissionKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => permissionsApi.getAll(queryParams, signal),
|
||||
});
|
||||
}
|
||||
|
||||
// ─── usePermission (single) ───────────────────────────────────────────────────
|
||||
@@ -29,55 +30,53 @@ export function usePermissions(params: PermissionsListParams) {
|
||||
export function usePermission(id: number) {
|
||||
return useQuery({
|
||||
queryKey: permissionKeys.detail(id),
|
||||
queryFn: () => permissionsApi.getById(id).then((r) => r.data),
|
||||
enabled: !!id,
|
||||
})
|
||||
queryFn: () => permissionsApi.getById(id),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useCreatePermission() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) =>
|
||||
permissionsApi.create(payload).then((r) => r.data),
|
||||
mutationFn: (payload: PermissionPayload) => permissionsApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
toast.success(t('permissions.toast.created', 'Rugsat üstünlikli döredildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
toast.success(t("permissions.toast.created", "Rugsat üstünlikli döredildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdatePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdatePermission(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: PermissionPayload) =>
|
||||
permissionsApi.update(id, payload).then((r) => r.data),
|
||||
mutationFn: (payload: PermissionPayload) => permissionsApi.update(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.detail(id) })
|
||||
toast.success(t('permissions.toast.updated', 'Rugsat üstünlikli üýtgedildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.detail(id) });
|
||||
toast.success(t("permissions.toast.updated", "Rugsat üstünlikli üýtgedildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeletePermission ──────────────────────────────────────────────────────
|
||||
|
||||
export function useDeletePermission() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => permissionsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all })
|
||||
toast.success(t('permissions.toast.deleted', 'Rugsat üstünlikli pozuldy!'))
|
||||
queryClient.invalidateQueries({ queryKey: permissionKeys.all });
|
||||
toast.success(t("permissions.toast.deleted", "Rugsat üstünlikli pozuldy!"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
import { z } from 'zod'
|
||||
import type { PermissionPayload } from '../api/permissionsApi'
|
||||
import { z } from "zod";
|
||||
import type { PermissionPayload } from "../api/permissionsApi";
|
||||
|
||||
export function createPermissionFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
guardName: z.string().min(1, t("validation.required", "validation.required")),
|
||||
});
|
||||
}
|
||||
|
||||
export type PermissionFormData = z.infer<ReturnType<typeof createPermissionFormSchema>>
|
||||
export type PermissionFormData = z.infer<ReturnType<typeof createPermissionFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: PermissionFormData = {
|
||||
code: '',
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
guard_name: 'web',
|
||||
}
|
||||
code: "",
|
||||
name: "",
|
||||
guardName: "",
|
||||
};
|
||||
|
||||
export function buildPayload(data: PermissionFormData): PermissionPayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: {
|
||||
tk: data.nameTk,
|
||||
ru: data.nameRu,
|
||||
en: data.nameEn,
|
||||
},
|
||||
guard_name: data.guard_name,
|
||||
}
|
||||
name: data.name,
|
||||
guardName: data.guardName,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,163 +1,70 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LoanDocumentTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
export interface LoanDocument {
|
||||
id: number;
|
||||
name: string;
|
||||
value: string;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface LoanDocument {
|
||||
id: number
|
||||
name: LoanDocumentTranslation
|
||||
description: LoanDocumentTranslation
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
export interface LoanDocumentListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
active?: string;
|
||||
}
|
||||
|
||||
export interface LoanDocumentListResponse {
|
||||
count: number;
|
||||
loansDocuments: LoanDocument[];
|
||||
}
|
||||
|
||||
export interface LoanDocumentPayload {
|
||||
name: LoanDocumentTranslation
|
||||
description: LoanDocumentTranslation
|
||||
active: boolean;
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
}
|
||||
|
||||
export interface ListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_LOAN_DOCUMENTS: LoanDocument[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: {
|
||||
tk: 'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyryldy!',
|
||||
ru: 'Уважаемый клиент! Ваше обращение удовлетворено!',
|
||||
en: 'Dear customer! Your request has been approved!',
|
||||
},
|
||||
description: {
|
||||
tk: 'Siziň karz sargydyňyz üstünlikli kabul edildi we tassyklandy.',
|
||||
ru: 'Ваша заявка на кредит успешно принята и подтверждена.',
|
||||
en: 'Your loan application has been successfully received and confirmed.',
|
||||
},
|
||||
createdAt: '2026-01-15T10:30:00Z',
|
||||
updatedAt: '2026-01-15T10:30:00Z',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: {
|
||||
tk: 'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyrylmady!',
|
||||
ru: 'Уважаемый клиент! Ваше обращение не удовлетворено!',
|
||||
en: 'Dear customer! Your request has been rejected!',
|
||||
},
|
||||
description: {
|
||||
tk: 'Siziň bank kart maglumatlaryňyz tapylmandygy sebäpli Siziň ýüztutmaňyz kanagatlandyrylmady! Bank kartyňyz boýunça hyzmat ediji bankyňyza ýüz tutmagyňyzy Sizden haýyş edýäris.',
|
||||
ru: 'Ваше обращение не удовлетворено в связи с тем, что данные вашей банковской карты не найдены! Просим вас обратиться в банк, обслуживающий вашу банковскую карту.',
|
||||
en: 'Your request has been rejected because your bank card information was not found! We kindly ask you to contact the bank that services your card.',
|
||||
},
|
||||
createdAt: '2026-02-20T14:15:00Z',
|
||||
updatedAt: '2026-03-10T09:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: {
|
||||
tk: 'Karz resminama talap edilýär',
|
||||
ru: 'Требуется документ для кредита',
|
||||
en: 'Loan document required',
|
||||
},
|
||||
description: {
|
||||
tk: 'Karz almak üçin zerur resminamalary tabşyrmagyňyzy haýyş edýäris.',
|
||||
ru: 'Просим вас предоставить необходимые документы для получения кредита.',
|
||||
en: 'Please submit the required documents to obtain the loan.',
|
||||
},
|
||||
createdAt: '2026-03-05T08:00:00Z',
|
||||
updatedAt: '2026-03-05T08:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
let mockStore = [...MOCK_LOAN_DOCUMENTS]
|
||||
let nextId = mockStore.length + 1
|
||||
|
||||
// ─── Simulated delay ──────────────────────────────────────────────────────────
|
||||
|
||||
const delay = (ms = 400) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchLoanDocuments(
|
||||
params: ListParams = {}
|
||||
): Promise<PaginatedResponse<LoanDocument>> {
|
||||
await delay()
|
||||
const { page = 1, perPage = 10, search = '' } = params
|
||||
|
||||
let filtered = mockStore
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = mockStore.filter(
|
||||
(d) =>
|
||||
d.name.tk.toLowerCase().includes(q) ||
|
||||
d.name.ru.toLowerCase().includes(q) ||
|
||||
d.name.en.toLowerCase().includes(q)
|
||||
)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage)
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
export async function fetchLoanDocuments(params: LoanDocumentListParams = {}, signal?: AbortSignal): Promise<LoanDocumentListResponse> {
|
||||
const { page, limit, search, active } = params;
|
||||
const { data } = await apiClient.get<LoanDocumentListResponse>("/loans-documents", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
document_name: search || undefined,
|
||||
active: active || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function fetchLoanDocumentById(id: number): Promise<LoanDocument> {
|
||||
await delay()
|
||||
const doc = mockStore.find((d) => d.id === id)
|
||||
if (!doc) throw new Error(`LoanDocument with id ${id} not found`)
|
||||
return { ...doc }
|
||||
const { data } = await apiClient.get<LoanDocument>(`/loans-documents/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createLoanDocument(
|
||||
payload: LoanDocumentPayload
|
||||
): Promise<LoanDocument> {
|
||||
await delay(600)
|
||||
const now = new Date().toISOString()
|
||||
const newDoc: LoanDocument = {
|
||||
id: nextId++,
|
||||
...payload,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
mockStore = [newDoc, ...mockStore]
|
||||
return { ...newDoc }
|
||||
export async function createLoanDocument(payload: LoanDocumentPayload): Promise<LoanDocument> {
|
||||
const { data } = await apiClient.post<LoanDocument>("/loans-documents", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateLoanDocument(
|
||||
id: number,
|
||||
payload: LoanDocumentPayload
|
||||
): Promise<LoanDocument> {
|
||||
await delay(600)
|
||||
const index = mockStore.findIndex((d) => d.id === id)
|
||||
if (index === -1) throw new Error(`LoanDocument with id ${id} not found`)
|
||||
const updated: LoanDocument = {
|
||||
...mockStore[index],
|
||||
...payload,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
mockStore = mockStore.map((d) => (d.id === id ? updated : d))
|
||||
return { ...updated }
|
||||
export async function updateLoanDocument(id: number, payload: LoanDocumentPayload): Promise<LoanDocument> {
|
||||
const { data } = await apiClient.put<LoanDocument>(`/loans-documents/${id}`, payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteLoanDocument(id: number): Promise<void> {
|
||||
await delay(400)
|
||||
const exists = mockStore.some((d) => d.id === id)
|
||||
if (!exists) throw new Error(`LoanDocument with id ${id} not found`)
|
||||
mockStore = mockStore.filter((d) => d.id !== id)
|
||||
}
|
||||
await apiClient.delete(`/loans-documents/${id}`);
|
||||
}
|
||||
|
||||
export async function updateLoanDocumentActive(id: number, active: boolean): Promise<LoanDocument> {
|
||||
const { data } = await apiClient.put<LoanDocument>(`/loans-documents/${id}/active`, { active });
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,381 +1,34 @@
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
|
||||
import { useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useEditor, EditorContent } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import Underline from "@tiptap/extension-underline";
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Strikethrough,
|
||||
Link2,
|
||||
Heading2,
|
||||
Quote,
|
||||
Code,
|
||||
List,
|
||||
ListOrdered,
|
||||
Minus,
|
||||
WrapText,
|
||||
Paperclip,
|
||||
Type,
|
||||
X,
|
||||
FileText,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateRequiredDocument, useUpdateRequiredDocument } from "../hooks/useRequiredDocuments";
|
||||
import type { LoanDocument } from "../api/requiredDocumentsApi";
|
||||
import { createRequiredDocumentFormSchema, DEFAULT_FORM_VALUES, buildPayload, mapInitial } from "../schemas/requiredDocument.schema";
|
||||
import type { RequiredDocumentFormData } from "../schemas/requiredDocument.schema";
|
||||
import type { LoanDocument, LoanDocumentTranslation } from "../api/requiredDocumentsApi";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type Locale = "tk" | "ru" | "en";
|
||||
type FormMode = "create" | "edit";
|
||||
|
||||
interface RequiredDocumentFormProps {
|
||||
mode: "create" | "edit";
|
||||
mode: FormMode;
|
||||
initialData?: LoanDocument;
|
||||
}
|
||||
|
||||
// ─── Lang tabs ────────────────────────────────────────────────────────────────
|
||||
type FlatErrors = Partial<Record<keyof RequiredDocumentFormData, string>>;
|
||||
|
||||
const LOCALES: Locale[] = ["tk", "ru", "en"];
|
||||
|
||||
// ─── Tiptap Toolbar ───────────────────────────────────────────────────────────
|
||||
|
||||
interface RichTextToolbarProps {
|
||||
editor: ReturnType<typeof useEditor>;
|
||||
onFileAttach?: (file: File) => void;
|
||||
}
|
||||
|
||||
// ─── RichTextToolbar ─────────────────────────────────────────────────────────
|
||||
|
||||
function RichTextToolbar({ editor, onFileAttach }: RichTextToolbarProps) {
|
||||
const [showLinkModal, setShowLinkModal] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
if (!editor) return null;
|
||||
|
||||
const handleLinkConfirm = (url: string) => {
|
||||
if (url) {
|
||||
const href = url.startsWith("http") ? url : `https://${url}`;
|
||||
editor.chain().focus().setLink({ href }).run();
|
||||
}
|
||||
setShowLinkModal(false);
|
||||
};
|
||||
|
||||
const handleAttachmentClick = () => fileInputRef.current?.click();
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
onFileAttach?.(file);
|
||||
|
||||
editor.chain().focus().insertContent(`<span>📎 ${file.name}</span> `).run();
|
||||
|
||||
e.target.value = "";
|
||||
};
|
||||
|
||||
const tools = [
|
||||
{
|
||||
icon: Bold,
|
||||
action: () => editor.chain().focus().toggleBold().run(),
|
||||
active: editor.isActive("bold"),
|
||||
title: "Bold",
|
||||
},
|
||||
{
|
||||
icon: Italic,
|
||||
action: () => editor.chain().focus().toggleItalic().run(),
|
||||
active: editor.isActive("italic"),
|
||||
title: "Italic",
|
||||
},
|
||||
{
|
||||
icon: Strikethrough,
|
||||
action: () => editor.chain().focus().toggleStrike().run(),
|
||||
active: editor.isActive("strike"),
|
||||
title: "Strike",
|
||||
},
|
||||
{
|
||||
icon: Link2,
|
||||
action: () => setShowLinkModal(true),
|
||||
active: editor.isActive("link"),
|
||||
title: "Link",
|
||||
},
|
||||
{
|
||||
icon: Heading2,
|
||||
action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
|
||||
active: editor.isActive("heading", { level: 2 }),
|
||||
title: "H2",
|
||||
},
|
||||
{
|
||||
icon: Quote,
|
||||
action: () => editor.chain().focus().toggleBlockquote().run(),
|
||||
active: editor.isActive("blockquote"),
|
||||
title: "Quote",
|
||||
},
|
||||
{
|
||||
icon: Code,
|
||||
action: () => editor.chain().focus().toggleCodeBlock().run(),
|
||||
active: editor.isActive("codeBlock"),
|
||||
title: "Code Block",
|
||||
},
|
||||
{
|
||||
icon: List,
|
||||
action: () => editor.chain().focus().toggleBulletList().run(),
|
||||
active: editor.isActive("bulletList"),
|
||||
title: "Bullet List",
|
||||
},
|
||||
{
|
||||
icon: ListOrdered,
|
||||
action: () => editor.chain().focus().toggleOrderedList().run(),
|
||||
active: editor.isActive("orderedList"),
|
||||
title: "Ordered List",
|
||||
},
|
||||
{
|
||||
icon: Minus,
|
||||
action: () => editor.chain().focus().setHorizontalRule().run(),
|
||||
active: false,
|
||||
title: "Divider",
|
||||
},
|
||||
{
|
||||
icon: WrapText,
|
||||
action: () => editor.chain().focus().setHardBreak().run(),
|
||||
active: false,
|
||||
title: "Hard Break",
|
||||
},
|
||||
{
|
||||
icon: Paperclip,
|
||||
action: handleAttachmentClick,
|
||||
active: false,
|
||||
title: "Attachment",
|
||||
},
|
||||
{
|
||||
icon: Type,
|
||||
action: () => editor.chain().focus().selectAll().clearNodes().unsetAllMarks().run(),
|
||||
active: false,
|
||||
title: "Clear format",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-0.5 p-1.5 border-b border-border bg-muted/30">
|
||||
{
|
||||
// eslint-disable-next-line react-hooks/refs
|
||||
tools.map(({ icon: Icon, action, active, title }) => (
|
||||
<button
|
||||
key={title}
|
||||
type="button"
|
||||
title={title}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
action();
|
||||
}}
|
||||
className={cn(
|
||||
"flex items-center justify-center w-7 h-7 rounded text-muted-foreground",
|
||||
"hover:bg-muted hover:text-foreground transition-colors",
|
||||
active && "bg-primary/10 text-primary",
|
||||
)}
|
||||
>
|
||||
<Icon size={14} />
|
||||
</button>
|
||||
))
|
||||
}
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={handleFileChange} />
|
||||
</div>
|
||||
|
||||
{/* Link modal */}
|
||||
{showLinkModal && <LinkModal onConfirm={handleLinkConfirm} onClose={() => setShowLinkModal(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Link Modal ───────────────────────────────────────────────────────────────
|
||||
|
||||
function LinkModal({ onConfirm, onClose }: { onConfirm: (url: string) => void; onClose: () => void }) {
|
||||
const [url, setUrl] = useState("");
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div className="bg-background border border-border rounded-lg shadow-lg p-4 w-80 flex flex-col gap-3">
|
||||
<p className="text-sm font-medium">URL giriziň</p>
|
||||
<input
|
||||
autoFocus
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onConfirm(url);
|
||||
if (e.key === "Escape") onClose();
|
||||
}}
|
||||
placeholder="https://..."
|
||||
className="border border-input rounded px-2 py-1.5 text-sm w-full focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button type="button" onClick={onClose} className="text-sm px-3 py-1 rounded hover:bg-muted text-muted-foreground">
|
||||
Ýatyr
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onConfirm(url)}
|
||||
className="text-sm px-3 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
Goş
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── RichTextEditor ───────────────────────────────────────────────────────────
|
||||
|
||||
interface RichTextEditorProps {
|
||||
value: string;
|
||||
onChange: (html: string) => void;
|
||||
error?: string;
|
||||
onFileAttach?: (file: File) => void;
|
||||
}
|
||||
|
||||
function RichTextEditor({ value, onChange, error, onFileAttach }: RichTextEditorProps) {
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit.configure({
|
||||
heading: { levels: [1, 2, 3] },
|
||||
code: {},
|
||||
blockquote: {},
|
||||
bulletList: {},
|
||||
orderedList: {},
|
||||
horizontalRule: {},
|
||||
hardBreak: {},
|
||||
}),
|
||||
Underline,
|
||||
Link.configure({
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
HTMLAttributes: {
|
||||
rel: "noopener noreferrer",
|
||||
target: "_blank",
|
||||
},
|
||||
}),
|
||||
],
|
||||
content: value,
|
||||
onUpdate: ({ editor }) => onChange(editor.getHTML()),
|
||||
});
|
||||
|
||||
// Sync external value changes (e.g. tab switch)
|
||||
useEffect(() => {
|
||||
if (editor && editor.getHTML() !== value) {
|
||||
editor.commands.setContent(value, { emitUpdate: false });
|
||||
}
|
||||
}, [value, editor]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border bg-background overflow-hidden",
|
||||
error ? "border-destructive" : "border-input",
|
||||
"focus-within:ring-1 focus-within:ring-ring",
|
||||
)}
|
||||
>
|
||||
<RichTextToolbar editor={editor} onFileAttach={onFileAttach} />
|
||||
<EditorContent
|
||||
editor={editor}
|
||||
className="min-h-[120px] px-3 py-2 text-sm text-foreground prose prose-sm dark:prose-invert max-w-none focus:outline-none [&_.ProseMirror]:focus:outline-none [&_.ProseMirror_a]:text-primary [&_.ProseMirror_a]:underline [&_.ProseMirror_a]:cursor-pointer"
|
||||
/>
|
||||
{error && (
|
||||
<p className="px-3 pb-2 text-xs text-destructive font-medium flex items-center gap-1.5">
|
||||
<span className="inline-block w-1 h-1 rounded-full bg-destructive shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── AttachedFilesList ────────────────────────────────────────────────────────
|
||||
|
||||
interface AttachedFilesListProps {
|
||||
files: File[];
|
||||
onRemove: (index: number) => void;
|
||||
}
|
||||
|
||||
function AttachedFilesList({ files, onRemove }: AttachedFilesListProps) {
|
||||
if (files.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-2 flex flex-col gap-1">
|
||||
{files.map((file, i) => (
|
||||
<div key={`${file.name}-${i}`} className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/40 rounded px-2 py-1.5">
|
||||
<FileText size={12} className="shrink-0 text-primary" />
|
||||
<span className="flex-1 truncate">{file.name}</span>
|
||||
<span className="shrink-0 text-muted-foreground/60">{(file.size / 1024).toFixed(1)} KB</span>
|
||||
<button type="button" onClick={() => onRemove(i)} className="shrink-0 hover:text-destructive transition-colors ml-1">
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── LangTabs ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface LangTabsProps {
|
||||
active: Locale;
|
||||
onChange: (locale: Locale) => void;
|
||||
}
|
||||
|
||||
function LangTabs({ active, onChange }: LangTabsProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-3 mb-2">
|
||||
{LOCALES.map((code) => (
|
||||
<button
|
||||
key={code}
|
||||
type="button"
|
||||
onClick={() => onChange(code)}
|
||||
className={cn(
|
||||
"text-sm transition-colors",
|
||||
active === code ? "text-primary font-semibold underline underline-offset-4" : "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Error helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
type LegacyErrorKey = `name_${Locale}` | `desc_${Locale}`;
|
||||
|
||||
const RHF_TO_LEGACY_KEY: Record<string, LegacyErrorKey> = {
|
||||
nameTk: "name_tk",
|
||||
nameRu: "name_ru",
|
||||
nameEn: "name_en",
|
||||
descTk: "desc_tk",
|
||||
descRu: "desc_ru",
|
||||
descEn: "desc_en",
|
||||
};
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): Partial<Record<LegacyErrorKey, string>> {
|
||||
const result: Partial<Record<LegacyErrorKey, string>> = {};
|
||||
for (const [key, err] of Object.entries(errors)) {
|
||||
const legacyKey = RHF_TO_LEGACY_KEY[key];
|
||||
if (legacyKey && err?.message) {
|
||||
result[legacyKey] = err.message;
|
||||
}
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof RequiredDocumentFormData] = msg;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -390,21 +43,6 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Per-field locale tabs (UI only, not form state)
|
||||
const [nameLang, setNameLang] = useState<Locale>("tk");
|
||||
const [descLang, setDescLang] = useState<Locale>("tk");
|
||||
|
||||
// ── Attached files — stored as File[] for FormData submission ──────────────
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
|
||||
const handleFileAttach = useCallback((file: File) => {
|
||||
setAttachedFiles((prev) => [...prev, file]);
|
||||
}, []);
|
||||
|
||||
const handleFileRemove = useCallback((index: number) => {
|
||||
setAttachedFiles((prev) => prev.filter((_, i) => i !== index));
|
||||
}, []);
|
||||
|
||||
const createMutation = useCreateRequiredDocument();
|
||||
const updateMutation = useUpdateRequiredDocument(initialData?.id ?? 0);
|
||||
|
||||
@@ -415,9 +53,10 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
getValues,
|
||||
} = useForm<RequiredDocumentFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
@@ -428,84 +67,37 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
|
||||
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language]);
|
||||
|
||||
const name: LoanDocumentTranslation = useMemo(
|
||||
() => ({ tk: form.nameTk, ru: form.nameRu, en: form.nameEn }),
|
||||
[form.nameTk, form.nameRu, form.nameEn],
|
||||
);
|
||||
|
||||
const description: LoanDocumentTranslation = useMemo(
|
||||
() => ({ tk: form.descTk, ru: form.descRu, en: form.descEn }),
|
||||
[form.descTk, form.descRu, form.descEn],
|
||||
);
|
||||
|
||||
const setName = useCallback(
|
||||
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
|
||||
const current = getValues();
|
||||
const prev: LoanDocumentTranslation = {
|
||||
tk: current.nameTk,
|
||||
ru: current.nameRu,
|
||||
en: current.nameEn,
|
||||
};
|
||||
const next = updater(prev);
|
||||
setValue("nameTk", next.tk);
|
||||
setValue("nameRu", next.ru);
|
||||
setValue("nameEn", next.en);
|
||||
const set = useCallback(
|
||||
(key: keyof RequiredDocumentFormData) => (value: string | boolean) => {
|
||||
(setValue as (k: keyof RequiredDocumentFormData, v: string | boolean) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, getValues],
|
||||
);
|
||||
|
||||
const setDescription = useCallback(
|
||||
(updater: (prev: LoanDocumentTranslation) => LoanDocumentTranslation) => {
|
||||
const current = getValues();
|
||||
const prev: LoanDocumentTranslation = {
|
||||
tk: current.descTk,
|
||||
ru: current.descRu,
|
||||
en: current.descEn,
|
||||
};
|
||||
const next = updater(prev);
|
||||
setValue("descTk", next.tk);
|
||||
setValue("descRu", next.ru);
|
||||
setValue("descEn", next.en);
|
||||
},
|
||||
[setValue, getValues],
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const handleSubmit = async (e?: React.FormEvent) => {
|
||||
e?.preventDefault();
|
||||
const handleSubmit = async () => {
|
||||
const isValid = await trigger();
|
||||
if (!isValid) return;
|
||||
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
// Build FormData — JSON fields + all attached File objects
|
||||
const formData = new FormData();
|
||||
formData.append("name[tk]", payload.name.tk);
|
||||
formData.append("name[ru]", payload.name.ru);
|
||||
formData.append("name[en]", payload.name.en);
|
||||
formData.append("description[tk]", payload.description.tk);
|
||||
formData.append("description[ru]", payload.description.ru);
|
||||
formData.append("description[en]", payload.description.en);
|
||||
attachedFiles.forEach((file) => {
|
||||
formData.append("files", file, file.name);
|
||||
});
|
||||
|
||||
if (mode === "create") {
|
||||
await createMutation.mutateAsync(payload);
|
||||
navigate("/settings/loan/loan-documents");
|
||||
const result = await createMutation.mutateAsync(payload);
|
||||
navigate(`/settings/loan/required-documents/${result.id}`);
|
||||
} else {
|
||||
await updateMutation.mutateAsync(payload);
|
||||
navigate("/settings/loan/loan-documents");
|
||||
navigate(`/settings/loan/required-documents/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const submitLabel =
|
||||
mode === "create"
|
||||
? t("loanDocuments.form.create", "Karz gerekli resminamalary döretiň")
|
||||
: t("loanDocuments.form.update", "Karz gerekli resminamalary täzele");
|
||||
const handleCancel = () => navigate("/settings/loan/required-documents");
|
||||
|
||||
// ── Render ──────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
@@ -514,58 +106,49 @@ export function RequiredDocumentForm({ mode, initialData }: RequiredDocumentForm
|
||||
? t("loanDocuments.createTitle", "Karz gerekli resminama dörediň")
|
||||
: t("loanDocuments.editTitle", "Karz gerekli resminama üýtgetmek")}
|
||||
</h1>
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("loanDocuments.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<LangTabs active={nameLang} onChange={setNameLang} />
|
||||
<FormInput
|
||||
type="text"
|
||||
value={name[nameLang]}
|
||||
onChange={(val) => setName((prev) => ({ ...prev, [nameLang]: val }))}
|
||||
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
|
||||
error={errors[`name_${nameLang}`]}
|
||||
/>
|
||||
{LOCALES.filter((l) => l !== nameLang && errors[`name_${l}`]).map((code) => (
|
||||
<p key={code} className="text-xs text-destructive/70">
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`name_${code}`]}
|
||||
</p>
|
||||
))}
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("loanDocuments.fields.description", "Yazgy")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<LangTabs active={descLang} onChange={setDescLang} />
|
||||
<RichTextEditor
|
||||
value={description[descLang]}
|
||||
onChange={(val) => setDescription((prev) => ({ ...prev, [descLang]: val }))}
|
||||
error={errors[`desc_${descLang}`]}
|
||||
onFileAttach={handleFileAttach}
|
||||
/>
|
||||
<AttachedFilesList files={attachedFiles} onRemove={handleFileRemove} />
|
||||
{LOCALES.filter((l) => l !== descLang && errors[`desc_${l}`]).map((code) => (
|
||||
<p key={code} className="text-xs text-destructive/70">
|
||||
{t("languages." + code, code === "tk" ? "Türkmen" : code === "ru" ? "Русский" : "English")}: {errors[`desc_${code}`]}
|
||||
</p>
|
||||
))}
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => navigate("/settings/loan/loan-documents")}
|
||||
cancelVariant="ghost"
|
||||
loadingLabel={t("common.saving", "Saklanylýar...")}
|
||||
submitLabel={submitLabel}
|
||||
className="mt-4"
|
||||
/>
|
||||
</form>
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanDocuments.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={set("name")}
|
||||
placeholder={t("loanDocuments.fields.namePlaceholder", "Ady")}
|
||||
error={errors.name}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("loanDocuments.fields.value", "Baha")}
|
||||
value={form.value}
|
||||
onChange={set("value")}
|
||||
placeholder={t("loanDocuments.fields.valuePlaceholder", "Baha")}
|
||||
error={errors.value}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<span className="text-sm font-semibold text-muted-foreground">{t("loanDocuments.fields.isActive", "Işjeň")}</span>
|
||||
<Checkbox id="isActive" checked={form.active} onCheckedChange={(checked) => set("active")(!!checked)} />
|
||||
<Label htmlFor="isActive" className="text-sm text-foreground cursor-pointer">
|
||||
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
</Label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("loanDocuments.form.create", "Karz gerekli resminamalary döretiň")
|
||||
: t("loanDocuments.form.update", "Karz gerekli resminamalary täzele")
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,87 +1,108 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchLoanDocuments,
|
||||
fetchLoanDocumentById,
|
||||
createLoanDocument,
|
||||
updateLoanDocument,
|
||||
updateLoanDocumentActive,
|
||||
deleteLoanDocument,
|
||||
type ListParams,
|
||||
type LoanDocumentListParams,
|
||||
type LoanDocumentPayload,
|
||||
} from '../api/requiredDocumentsApi'
|
||||
} from "../api/requiredDocumentsApi";
|
||||
|
||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const requiredDocumentsKeys = {
|
||||
all: ['requiredDocuments'] as const,
|
||||
lists: () => [...requiredDocumentsKeys.all, 'list'] as const,
|
||||
list: (params: ListParams) => [...requiredDocumentsKeys.lists(), params] as const,
|
||||
details: () => [...requiredDocumentsKeys.all, 'detail'] as const,
|
||||
all: ["requiredDocuments"] as const,
|
||||
lists: () => [...requiredDocumentsKeys.all, "list"] as const,
|
||||
list: (params: LoanDocumentListParams) => [...requiredDocumentsKeys.lists(), params] as const,
|
||||
details: () => [...requiredDocumentsKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...requiredDocumentsKeys.details(), id] as const,
|
||||
};
|
||||
|
||||
// ─── useGetRequiredDocuments ──────────────────────────────────────────────────
|
||||
|
||||
export function useGetRequiredDocuments(params: LoanDocumentListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: LoanDocumentListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: requiredDocumentsKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchLoanDocuments(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useGetLoanDocuments ──────────────────────────────────────────────────────
|
||||
// ─── useGetRequiredDocumentById ───────────────────────────────────────────────
|
||||
|
||||
export function useGetRequiredDocuments(params: ListParams) {
|
||||
export function useGetRequiredDocumentById(id: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: requiredDocumentsKeys.list(params),
|
||||
queryFn: () => fetchLoanDocuments(params),
|
||||
})
|
||||
}
|
||||
|
||||
// ─── useGetLoanDocumentById ───────────────────────────────────────────────────
|
||||
|
||||
export function useGetRequiredDocumentById(id: number) {
|
||||
return useQuery({
|
||||
queryKey: requiredDocumentsKeys.detail(id),
|
||||
queryFn: () => fetchLoanDocumentById(id),
|
||||
queryKey: requiredDocumentsKeys.detail(id!),
|
||||
queryFn: () => fetchLoanDocumentById(id!),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateLoanDocument ────────────────────────────────────────────────────
|
||||
// ─── useCreateRequiredDocument ────────────────────────────────────────────────
|
||||
|
||||
export function useCreateRequiredDocument() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanDocumentPayload) => createLoanDocument(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
|
||||
toast.success(t('loanDocuments.toast.created', 'Resminama üstünlikli döredildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
|
||||
toast.success(t("loanDocuments.toast.created", "Resminama üstünlikli döredildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateLoanDocument ────────────────────────────────────────────────────
|
||||
// ─── useUpdateRequiredDocument ────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateRequiredDocument(id: number) {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: LoanDocumentPayload) => updateLoanDocument(id, payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.detail(id) })
|
||||
toast.success(t('loanDocuments.toast.updated', 'Resminama üstünlikli täzelendi!'))
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.detail(id) });
|
||||
toast.success(t("loanDocuments.toast.updated", "Resminama üstünlikli täzelendi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteLoanDocument ────────────────────────────────────────────────────
|
||||
// ─── useUpdateRequiredDocumentActive ──────────────────────────────────────────
|
||||
|
||||
export function useUpdateRequiredDocumentActive() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, active }: { id: number; active: boolean }) => updateLoanDocumentActive(id, active),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
|
||||
toast.success(t("loanDocuments.toast.statusUpdated", "Resminama statusy üstünlikli täzelendi!"));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteRequiredDocument ────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteRequiredDocument() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => deleteLoanDocument(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() })
|
||||
toast.success(t('loanDocuments.toast.deleted', 'Resminama üstünlikli öçürildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: requiredDocumentsKeys.lists() });
|
||||
toast.success(t("loanDocuments.toast.deleted", "Resminama üstünlikli öçürildi!"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,42 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import type { LoanDocument, LoanDocumentPayload } from '../api/requiredDocumentsApi'
|
||||
import { z } from "zod";
|
||||
import type { LoanDocument, LoanDocumentPayload } from "../api/requiredDocumentsApi";
|
||||
|
||||
export function createRequiredDocumentFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
descEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
value: z.string().min(1, t("validation.required", "validation.required")),
|
||||
active: z.boolean(),
|
||||
});
|
||||
}
|
||||
|
||||
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>
|
||||
export type RequiredDocumentFormData = z.infer<ReturnType<typeof createRequiredDocumentFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: RequiredDocumentFormData = {
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
descTk: '',
|
||||
descRu: '',
|
||||
descEn: '',
|
||||
}
|
||||
name: "",
|
||||
value: "",
|
||||
active: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: RequiredDocumentFormData): LoanDocumentPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
description: { tk: data.descTk.trim(), ru: data.descRu.trim(), en: data.descEn.trim() },
|
||||
}
|
||||
name: data.name.trim(),
|
||||
value: data.value.trim(),
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapInitial(data: LoanDocument): RequiredDocumentFormData {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
descTk: data.description.tk,
|
||||
descRu: data.description.ru,
|
||||
descEn: data.description.en,
|
||||
}
|
||||
name: data.name,
|
||||
value: data.value,
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,118 +1,66 @@
|
||||
// import {apiClient} from '@/lib/api/client'
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface RoleTranslation {
|
||||
tk: string
|
||||
ru: string
|
||||
en: string
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: number
|
||||
code: string
|
||||
name: RoleTranslation
|
||||
guard_name: string
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface RolePayload {
|
||||
code: string
|
||||
name: RoleTranslation
|
||||
guard_name: string
|
||||
export interface RolesListResponse {
|
||||
count: number;
|
||||
roles: Role[];
|
||||
}
|
||||
|
||||
export interface RolesListParams {
|
||||
search?: string
|
||||
page?: number
|
||||
per_page?: number
|
||||
search?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[]
|
||||
meta: {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
export interface RolePayload {
|
||||
code: string;
|
||||
name: string;
|
||||
guardName: string;
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_ROLES: Role[] = [
|
||||
{ id: 1, code: 'admin', guard_name: 'web', name: { tk: 'Administrator', ru: 'Администратор', en: 'Administrator' } },
|
||||
{ id: 2, code: 'operator', guard_name: 'web', name: { tk: 'Operator', ru: 'Оператор', en: 'Operator' } },
|
||||
{ id: 3, code: 'manager', guard_name: 'web', name: { tk: 'Menijer', ru: 'Менеджер', en: 'Manager' } },
|
||||
{ id: 4, code: 'editor', guard_name: 'web', name: { tk: 'Redaktor', ru: 'Редактор', en: 'Editor' } },
|
||||
]
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const rolesApi = {
|
||||
getAll: async (params?: RolesListParams): Promise<{ data: PaginatedResponse<Role> }> => {
|
||||
await delay()
|
||||
const { search = '', page = 1, per_page = 25 } = params ?? {}
|
||||
|
||||
let filtered = [...MOCK_ROLES]
|
||||
if (search) {
|
||||
const s = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(r) =>
|
||||
r.code.toLowerCase().includes(s) ||
|
||||
r.name.tk.toLowerCase().includes(s) ||
|
||||
r.name.ru.toLowerCase().includes(s) ||
|
||||
r.name.en.toLowerCase().includes(s)
|
||||
)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const last_page = Math.ceil(total / per_page)
|
||||
const start = (page - 1) * per_page
|
||||
const data = filtered.slice(start, start + per_page)
|
||||
|
||||
return {
|
||||
data: {
|
||||
data,
|
||||
meta: {
|
||||
current_page: page,
|
||||
last_page,
|
||||
per_page,
|
||||
total,
|
||||
},
|
||||
},
|
||||
}
|
||||
/** GET /roles — backend filters by `role_name` */
|
||||
getAll: async (params: RolesListParams = {}, signal?: AbortSignal): Promise<RolesListResponse> => {
|
||||
const { search, page, limit } = params;
|
||||
const { data } = await apiClient.get<RolesListResponse>("/roles", {
|
||||
params: { page, limit, role_name: search },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
getById: async (id: number): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const item = MOCK_ROLES.find((r) => r.id === id)
|
||||
if (!item) throw new Error('Not found')
|
||||
return { data: item }
|
||||
/** GET /roles/:id */
|
||||
getById: async (id: number): Promise<Role> => {
|
||||
const { data } = await apiClient.get<Role>(`/roles/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
create: async (payload: RolePayload): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const newItem: Role = {
|
||||
...payload,
|
||||
id: Math.floor(Math.random() * 10000),
|
||||
}
|
||||
MOCK_ROLES.push(newItem)
|
||||
return { data: newItem }
|
||||
/** POST /roles */
|
||||
create: async (payload: RolePayload): Promise<Role> => {
|
||||
const { data } = await apiClient.post<Role>("/roles", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
update: async (id: number, payload: RolePayload): Promise<{ data: Role }> => {
|
||||
await delay()
|
||||
const index = MOCK_ROLES.findIndex((r) => r.id === id)
|
||||
if (index === -1) throw new Error('Not found')
|
||||
MOCK_ROLES[index] = { ...MOCK_ROLES[index], ...payload }
|
||||
return { data: MOCK_ROLES[index] }
|
||||
/** PUT /roles/:id */
|
||||
update: async (id: number, payload: RolePayload): Promise<Role> => {
|
||||
const { data } = await apiClient.put<Role>(`/roles/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/** DELETE /roles/:id */
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await delay()
|
||||
const index = MOCK_ROLES.findIndex((r) => r.id === id)
|
||||
if (index !== -1) MOCK_ROLES.splice(index, 1)
|
||||
await apiClient.delete(`/roles/${id}`);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,12 +5,12 @@ import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { useCreateRole, useUpdateRole } from "../hooks/useRoles";
|
||||
import { createRoleFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/role.schema";
|
||||
import type { RoleFormData } from "../schemas/role.schema";
|
||||
import type { Role } from "../api/rolesApi";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface RoleFormProps {
|
||||
@@ -18,12 +18,6 @@ interface RoleFormProps {
|
||||
initialData?: Role;
|
||||
}
|
||||
|
||||
const GUARD_OPTIONS = [
|
||||
{ value: "web", label: "web" },
|
||||
{ value: "api", label: "api" },
|
||||
{ value: "sanctum", label: "sanctum" },
|
||||
];
|
||||
|
||||
type FlatErrors = Partial<Record<keyof RoleFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
@@ -65,10 +59,8 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
? {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
code: initialData.code,
|
||||
nameTk: initialData.name.tk,
|
||||
nameRu: initialData.name.ru,
|
||||
nameEn: initialData.name.en,
|
||||
guard_name: initialData.guard_name,
|
||||
name: initialData.name,
|
||||
guardName: initialData.guardName,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
@@ -84,33 +76,6 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const nameFields = {
|
||||
tk: {
|
||||
value: form.nameTk,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameTk", v);
|
||||
clearErrors("nameTk");
|
||||
},
|
||||
error: errors.nameTk,
|
||||
},
|
||||
ru: {
|
||||
value: form.nameRu,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameRu", v);
|
||||
clearErrors("nameRu");
|
||||
},
|
||||
error: errors.nameRu,
|
||||
},
|
||||
en: {
|
||||
value: form.nameEn,
|
||||
onChange: (v: string) => {
|
||||
setValue("nameEn", v);
|
||||
clearErrors("nameEn");
|
||||
},
|
||||
error: errors.nameEn,
|
||||
},
|
||||
};
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (Object.keys(rhfErrors).length > 0) trigger();
|
||||
@@ -159,22 +124,27 @@ export function RoleForm({ mode, initialData }: RoleFormProps) {
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="select"
|
||||
type="text"
|
||||
label={t("roles.fields.guardName", "Guard name")}
|
||||
value={form.guard_name}
|
||||
onChange={setField("guard_name")}
|
||||
options={GUARD_OPTIONS}
|
||||
error={errors.guard_name}
|
||||
value={form.guardName}
|
||||
onChange={setField("guardName")}
|
||||
placeholder="operator"
|
||||
error={errors.guardName}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard span="full">
|
||||
<p className="text-sm font-semibold text-muted-foreground mb-1">
|
||||
{t("roles.fields.name", "Ady")}
|
||||
<span className="text-destructive ml-0.5">*</span>
|
||||
</p>
|
||||
<MultiLangInput fields={nameFields} placeholder={t("roles.fields.name", "Ady")} disabled={isPending} />
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("roles.fields.name", "Ady")}
|
||||
value={form.name}
|
||||
onChange={setField("name")}
|
||||
placeholder={t("roles.fields.name", "Ady")}
|
||||
error={errors.name}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
<FormActions
|
||||
|
||||
@@ -1,23 +1,50 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { rolesApi, type RolePayload, type RolesListParams } from '../api/rolesApi'
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { rolesApi, type RolePayload, type RolesListParams } from "../api/rolesApi";
|
||||
|
||||
// ─── Query keys ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const roleKeys = {
|
||||
all: ['roles'] as const,
|
||||
list: (params: RolesListParams) => ['roles', 'list', params] as const,
|
||||
detail: (id: number) => ['roles', 'detail', id] as const,
|
||||
}
|
||||
all: ["roles"] as const,
|
||||
lists: () => ["roles", "list"] as const,
|
||||
list: (params: RolesListParams) => ["roles", "list", params] as const,
|
||||
detail: (id: number) => ["roles", "detail", id] as const,
|
||||
infinite: (search: string) => ["roles", "infinite", search] as const,
|
||||
};
|
||||
|
||||
// ─── useRoles (list) ──────────────────────────────────────────────────────────
|
||||
|
||||
export function useRoles(params: RolesListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: RolesListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: roleKeys.list(params),
|
||||
queryFn: () => rolesApi.getAll(params).then((r) => r.data),
|
||||
})
|
||||
queryKey: roleKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => rolesApi.getAll(queryParams, signal),
|
||||
});
|
||||
}
|
||||
|
||||
const ROLE_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Paginated roles for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteRoles(search = "") {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: roleKeys.infinite(effectiveSearch),
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) => rolesApi.getAll({ page: pageParam, limit: ROLE_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + p.roles.length, 0);
|
||||
return loaded < lastPage.count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useRole (single) ─────────────────────────────────────────────────────────
|
||||
@@ -25,53 +52,53 @@ export function useRoles(params: RolesListParams) {
|
||||
export function useRole(id: number) {
|
||||
return useQuery({
|
||||
queryKey: roleKeys.detail(id),
|
||||
queryFn: () => rolesApi.getById(id).then((r) => r.data),
|
||||
queryFn: () => rolesApi.getById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useCreateRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useCreateRole() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.create(payload).then((r) => r.data),
|
||||
mutationFn: (payload: RolePayload) => rolesApi.create(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
toast.success(t('roles.toast.created', 'Rol üstünlikli döredildi!'))
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||
toast.success(t("roles.toast.created", "Rol üstünlikli döredildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useUpdateRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useUpdateRole(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload).then((r) => r.data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.detail(id) })
|
||||
toast.success(t('roles.toast.updated', 'Rol üstünlikli üýtgedildi!'))
|
||||
mutationFn: (payload: RolePayload) => rolesApi.update(id, payload),
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.detail(data.id) });
|
||||
toast.success(t("roles.toast.updated", "Rol üstünlikli üýtgedildi!"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
// ─── useDeleteRole ────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDeleteRole() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => rolesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all })
|
||||
toast.success(t('roles.toast.deleted', 'Rol üstünlikli pozuldy!'))
|
||||
queryClient.invalidateQueries({ queryKey: roleKeys.all });
|
||||
toast.success(t("roles.toast.deleted", "Rol üstünlikli pozuldy!"));
|
||||
},
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
import { z } from 'zod'
|
||||
import type { RolePayload } from '../api/rolesApi'
|
||||
import { z } from "zod";
|
||||
import type { RolePayload } from "../api/rolesApi";
|
||||
|
||||
export function createRoleFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
code: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameTk: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameRu: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
nameEn: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
guard_name: z.string().min(1, t('validation.required', 'validation.required')),
|
||||
})
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
guardName: z.string().min(1, t("validation.required", "validation.required")),
|
||||
});
|
||||
}
|
||||
|
||||
export type RoleFormData = z.infer<ReturnType<typeof createRoleFormSchema>>
|
||||
export type RoleFormData = z.infer<ReturnType<typeof createRoleFormSchema>>;
|
||||
|
||||
export const DEFAULT_FORM_VALUES: RoleFormData = {
|
||||
code: '',
|
||||
nameTk: '',
|
||||
nameRu: '',
|
||||
nameEn: '',
|
||||
guard_name: 'web',
|
||||
}
|
||||
code: "",
|
||||
name: "",
|
||||
guardName: "operator",
|
||||
};
|
||||
|
||||
export function buildPayload(data: RoleFormData): RolePayload {
|
||||
return {
|
||||
code: data.code,
|
||||
name: {
|
||||
tk: data.nameTk,
|
||||
ru: data.nameRu,
|
||||
en: data.nameEn,
|
||||
},
|
||||
guard_name: data.guard_name,
|
||||
}
|
||||
name: data.name,
|
||||
guardName: data.guardName,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -165,7 +165,6 @@ export function VisaMasterSettingForm({ mode, initialData }: VisaMasterSettingFo
|
||||
isPending={isPending}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={handleCancel}
|
||||
cancelVariant="ghost"
|
||||
submitLabel={
|
||||
mode === "create"
|
||||
? t("visaMasterSettings.actions.create", "Visa/Master, Sber sazlamalar dörediň")
|
||||
|
||||
31
src/hooks/useDebouncedSearch.ts
Normal file
31
src/hooks/useDebouncedSearch.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/** Delay before a search term is applied to the server query. */
|
||||
export const SEARCH_DEBOUNCE_MS = 400;
|
||||
|
||||
/** Minimum number of characters before a server-side search is triggered. */
|
||||
export const MIN_SEARCH_LENGTH = 3;
|
||||
|
||||
/**
|
||||
* Returns `value` after `delay` ms of no change.
|
||||
* Used to debounce server-side search so requests are not sent on every keystroke.
|
||||
*/
|
||||
export function useDebouncedValue<T>(value: T, delay = SEARCH_DEBOUNCE_MS): T {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebounced(value), delay);
|
||||
return () => clearTimeout(timer);
|
||||
}, [value, delay]);
|
||||
|
||||
return debounced;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims the search term and drops it until it is at least `MIN_SEARCH_LENGTH`
|
||||
* characters long. Returning "" means "no server-side filter" (show all).
|
||||
*/
|
||||
export function normalizeSearch(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length >= MIN_SEARCH_LENGTH ? trimmed : "";
|
||||
}
|
||||
@@ -1,17 +1,40 @@
|
||||
import axios from "axios";
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from "axios";
|
||||
import { useAuthStore } from "@/app/store/authStore";
|
||||
|
||||
// ---- API Envelope Types ----
|
||||
export interface ApiSuccessResponse<T> {
|
||||
status: true;
|
||||
message: string;
|
||||
code: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
status: false;
|
||||
message: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface RetryableRequestConfig extends InternalAxiosRequestConfig {
|
||||
_retry?: boolean;
|
||||
}
|
||||
|
||||
interface QueueItem {
|
||||
resolve: (token: string) => void;
|
||||
reject: (error: unknown) => void;
|
||||
}
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL,
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || "/api/admin",
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
let isRefreshing = false;
|
||||
let failedQueue: any[] = [];
|
||||
let failedQueue: QueueItem[] = [];
|
||||
|
||||
const processQueue = (error: any, token: string | null = null) => {
|
||||
const processQueue = (error: unknown, token: string | null = null) => {
|
||||
failedQueue.forEach((prom) => {
|
||||
if (error) prom.reject(error);
|
||||
if (error || !token) prom.reject(error);
|
||||
else prom.resolve(token);
|
||||
});
|
||||
failedQueue = [];
|
||||
@@ -29,14 +52,22 @@ apiClient.interceptors.request.use(
|
||||
);
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
// Başarılı response'larda envelope'u soyup direkt `data`yı döndürüyoruz.
|
||||
// Böylece feature API fonksiyonları `response.data.data` yerine `response.data` yazar.
|
||||
(response) => {
|
||||
response.data = (response.data as ApiSuccessResponse<unknown>)?.data;
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError<ApiErrorResponse>) => {
|
||||
const originalRequest = error.config as RetryableRequestConfig;
|
||||
const status = error.response?.status;
|
||||
const url = originalRequest?.url || "";
|
||||
|
||||
if (status === 401 && !originalRequest._retry) {
|
||||
const isAuthEndpoint = url.includes("/login") || url.includes("/token");
|
||||
|
||||
if (status === 401 && !originalRequest._retry && !isAuthEndpoint) {
|
||||
if (isRefreshing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject });
|
||||
})
|
||||
.then((token) => {
|
||||
@@ -72,4 +103,15 @@ apiClient.interceptors.response.use(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Backend'in standart hata mesajını çıkarır.
|
||||
* QueryCache.onError / MutationCache.onError içinde toast.error() için kullanılacak.
|
||||
*/
|
||||
export function extractErrorMessage(error: unknown, fallback = "Bir hata oluştu"): string {
|
||||
if (axios.isAxiosError<ApiErrorResponse>(error)) {
|
||||
return error.response?.data?.message || fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export default apiClient;
|
||||
|
||||
@@ -417,6 +417,46 @@
|
||||
"loanPaidOffLetters.columns.passportNumber": "PASSPORT NUMBER",
|
||||
"loanPaidOffLetters.columns.loanAccount": "LOAN ACCOUNT",
|
||||
"loanPaidOffLetters.columns.issuedAt": "ISSUED AT",
|
||||
"loanPaidOffLetters.columns.uniqueId": "UNIQUE ID",
|
||||
"loanPaidOffLetters.columns.customerName": "CUSTOMER",
|
||||
"loanPaidOffLetters.columns.phone": "PHONE",
|
||||
"loanPaidOffLetters.columns.status": "STATUS",
|
||||
"loanPaidOffLetters.status.pending": "Pending",
|
||||
"loanPaidOffLetters.status.approved": "Approved",
|
||||
"loanPaidOffLetters.status.rejected": "Rejected",
|
||||
"loanPaidOffLetters.regions.AG": "Ashgabat",
|
||||
"loanPaidOffLetters.regions.AH": "Ahal",
|
||||
"loanPaidOffLetters.regions.BA": "Balkan",
|
||||
"loanPaidOffLetters.regions.DA": "Dashoguz",
|
||||
"loanPaidOffLetters.regions.LE": "Lebap",
|
||||
"loanPaidOffLetters.regions.MA": "Mary",
|
||||
"loanPaidOffLetters.sections.info": "Main info",
|
||||
"loanPaidOffLetters.sections.customer": "Customer info",
|
||||
"loanPaidOffLetters.sections.passport": "Passport",
|
||||
"loanPaidOffLetters.sections.loan": "Loan info",
|
||||
"loanPaidOffLetters.sections.additional": "Additional",
|
||||
"loanPaidOffLetters.fields.customerName": "Name",
|
||||
"loanPaidOffLetters.fields.customerSurname": "Surname",
|
||||
"loanPaidOffLetters.fields.customerPatronicName": "Patronymic",
|
||||
"loanPaidOffLetters.fields.bornAt": "Date of birth",
|
||||
"loanPaidOffLetters.fields.phone": "Phone",
|
||||
"loanPaidOffLetters.fields.passportSerie": "Passport series",
|
||||
"loanPaidOffLetters.fields.passportId": "Passport number",
|
||||
"loanPaidOffLetters.fields.loanContractNumber": "Loan contract number",
|
||||
"loanPaidOffLetters.fields.loanContractDate": "Loan contract date",
|
||||
"loanPaidOffLetters.fields.loanAmount": "Loan amount",
|
||||
"loanPaidOffLetters.fields.loanReason": "Loan reason",
|
||||
"loanPaidOffLetters.fields.loanFile": "File",
|
||||
"loanPaidOffLetters.fields.region": "Region",
|
||||
"loanPaidOffLetters.fields.branchId": "Branch ID",
|
||||
"loanPaidOffLetters.fields.userId": "User ID",
|
||||
"loanPaidOffLetters.fields.status": "Status",
|
||||
"loanPaidOffLetters.fields.uniqueId": "Unique ID",
|
||||
"loanPaidOffLetters.fields.notes": "Notes",
|
||||
"loanPaidOffLetters.view.title": "Certificate info",
|
||||
"loanPaidOffLetters.deleteSuccess": "Certificate deleted successfully",
|
||||
"loanPaidOffLetters.createSuccess": "Created successfully",
|
||||
"loanPaidOffLetters.updateSuccess": "Updated successfully",
|
||||
"loanRemaining.title": "Loan Remaining Balance",
|
||||
"loanRemaining.createButton": "Create Loan Remaining Record",
|
||||
"loanRemaining.deleteConfirm": "Are you sure you want to delete this record?",
|
||||
@@ -452,6 +492,14 @@
|
||||
"loanDocuments.toast.updateError": "Error updating document!",
|
||||
"loanDocuments.toast.deleted": "Document deleted successfully!",
|
||||
"loanDocuments.toast.deleteError": "Error deleting document!",
|
||||
"loanDocuments.toast.statusUpdated": "Document status updated successfully!",
|
||||
"loanDocuments.columns.value": "VALUE",
|
||||
"loanDocuments.columns.isActive": "ACTIVE",
|
||||
"loanDocuments.fields.value": "Value",
|
||||
"loanDocuments.fields.valuePlaceholder": "Value",
|
||||
"loanDocuments.fields.isActive": "Active",
|
||||
"common.active": "Active",
|
||||
"common.inactive": "Inactive",
|
||||
"common.cancel": "Cancel",
|
||||
"common.confirm": "Confirm",
|
||||
"common.back": "Back",
|
||||
@@ -472,6 +520,7 @@
|
||||
"validation.minLength": "At least {length} characters",
|
||||
"validation.invalidEmail": "Invalid email format",
|
||||
"validation.invalidPhonePrefix": "Invalid operator code (61-65, 71)",
|
||||
"validation.invalidUrl": "Invalid URL format",
|
||||
"Status": "Status",
|
||||
"Card (Salary)": "Card (Salary)",
|
||||
"1. Guarantor": "1. Guarantor",
|
||||
@@ -552,6 +601,17 @@
|
||||
"cardOrder.col.status": "Status",
|
||||
"cardOrder.create": "Create card order",
|
||||
"cardOrder.deleteConfirm": "Delete this order?",
|
||||
"cardOrder.col.number": "Card number",
|
||||
"cardOrder.col.expiry": "Expiry",
|
||||
"cardOrder.col.userId": "User ID",
|
||||
"cardOrder.field.name": "Card holder name",
|
||||
"cardOrder.field.number": "Card number",
|
||||
"cardOrder.field.expiry": "Expiry",
|
||||
"cardOrder.field.updatedAt": "Updated at",
|
||||
"cardOrder.field.userId": "User ID",
|
||||
"cardOrder.createSuccess": "Card created successfully",
|
||||
"cardOrder.updateSuccess": "Card updated successfully",
|
||||
"cardOrder.deleteSuccess": "Card deleted successfully",
|
||||
"citizenship.tm": "Turkmenistan",
|
||||
"citizenship.ru": "Russia",
|
||||
"citizenship.other": "Other",
|
||||
@@ -749,7 +809,7 @@
|
||||
"branches.form.subtitle": "Fill in all fields and proceed step by step.",
|
||||
"branches.sections.address": "Address and contact",
|
||||
"branches.sections.basic": "Basic information",
|
||||
"branches.sections.hours": "Working hours",
|
||||
"branches.sections.billing": "Billing credentials",
|
||||
"branches.viewTitle": "Branch detail",
|
||||
"cardBalance.createTitle": "Create card balance",
|
||||
"cardBalance.editTitle": "Edit card balance",
|
||||
@@ -765,10 +825,13 @@
|
||||
"cardReasons.actions.create": "Create reason",
|
||||
"cardReasons.actions.update": "Update reason",
|
||||
"cardReasons.deleteConfirm": "Are you sure you want to delete this reason?",
|
||||
"cardReasons.fields.description": "DESCRIPTION",
|
||||
"cardReasons.fields.isActive": "ACTIVE",
|
||||
"cardReasons.fields.name": "NAME",
|
||||
"cardReasons.fields.value": "VALUE",
|
||||
"cardReasons.fields.notes": "NOTES",
|
||||
"cardReasons.fields.price": "PRICE",
|
||||
"cardReasons.toast.createSuccess": "Reason created",
|
||||
"cardReasons.toast.updateSuccess": "Reason updated",
|
||||
"cardReasons.toast.deleteSuccess": "Reason deleted",
|
||||
"cardReasons.viewTitle": "Reason detail",
|
||||
"cardRequisites.createTitle": "Create card requisites",
|
||||
"cardRequisites.editTitle": "Edit card requisites",
|
||||
@@ -784,6 +847,12 @@
|
||||
"cardTypes.fields.name": "NAME",
|
||||
"cardTypes.fields.value": "VALUE",
|
||||
"cardTypes.view.title": "Card type detail",
|
||||
"cardTypes.fields.price": "PRICE",
|
||||
"cardTypes.fields.notes": "NOTES",
|
||||
"cardTypes.toast.createSuccess": "Card type created",
|
||||
"cardTypes.toast.updateSuccess": "Card type updated",
|
||||
"cardTypes.toast.deleteSuccess": "Card type deleted",
|
||||
"cardTypes.toast.statusUpdated": "Card type status updated!",
|
||||
"clients.createTitle": "Create client",
|
||||
"clients.editTitle": "Edit client",
|
||||
"clients.title": "Clients",
|
||||
@@ -797,9 +866,9 @@
|
||||
"districts.actions.create": "Create district",
|
||||
"districts.actions.update": "Update district",
|
||||
"districts.deleteConfirm": "Are you sure you want to delete this district?",
|
||||
"districts.fields.description": "NOTES",
|
||||
"districts.fields.isActive": "ACTIVE",
|
||||
"districts.fields.name": "NAME",
|
||||
"districts.fields.region": "REGION",
|
||||
"districts.viewTitle": "District detail",
|
||||
"intlPayment.createTitle": "Create Visa/Master payment",
|
||||
"intlPayment.editTitle": "Edit Visa/Master payment",
|
||||
@@ -823,6 +892,7 @@
|
||||
"loanTypes.deleteDialog.title": "Delete",
|
||||
"loanTypes.fields.isActive": "Active",
|
||||
"loanTypes.fields.loanTerm": "Loan term",
|
||||
"loanTypes.placeholders.loanTerm": "12, 24, 36",
|
||||
"loanTypes.fields.name": "Name",
|
||||
"loanTypes.fields.notes": "Notes",
|
||||
"loanTypes.fields.tax": "Tax",
|
||||
@@ -1112,14 +1182,15 @@
|
||||
"branches.fields.uniqueCode": "UNIQUE CODE",
|
||||
"branches.fields.isActive": "ACTIVE",
|
||||
"branches.fields.billingIbr": "BILLING USERNAME (IBR)",
|
||||
"branches.fields.billingPassword": "BILLING PASSWORD",
|
||||
"branches.fields.billingSber": "BILLING USERNAME (SBER)",
|
||||
"branches.fields.billingSberPassword": "PASSWORD (SBER)",
|
||||
"branches.fields.billingSwift": "BILLING USERNAME (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "PASSWORD (SWIFT)",
|
||||
"branches.fields.address": "ADDRESS",
|
||||
"branches.fields.billingVisa": "BILLING USERNAME (VISA)",
|
||||
"branches.fields.code": "CODE",
|
||||
"branches.fields.description": "NOTES",
|
||||
"branches.fields.email": "EMAIL",
|
||||
"branches.fields.phone": "PHONE",
|
||||
"branches.fields.workingHours": "WORKING HOURS",
|
||||
"branches.fields.billingVisaPassword": "PASSWORD (VISA)",
|
||||
"branches.fields.phoneNumbers": "PHONE NUMBERS",
|
||||
"users.title": "All users",
|
||||
"users.searchPlaceholder": "Search",
|
||||
"users.createTitle": "Add New User",
|
||||
@@ -1138,6 +1209,17 @@
|
||||
"users.fields.passwordHint": "At least 6 characters",
|
||||
"users.fields.phoneVerified": "Phone verified",
|
||||
"users.fields.phoneVerifiedHint": "Verified via SMS",
|
||||
"users.fields.avatar": "Avatar URL",
|
||||
"users.fields.firstName": "First name",
|
||||
"users.fields.lastName": "Last name",
|
||||
"users.fields.lightMode": "Light mode",
|
||||
"users.fields.role": "Role",
|
||||
"users.fields.socialMedia": "Social media",
|
||||
"users.fields.facebook": "Facebook",
|
||||
"users.fields.instagram": "Instagram",
|
||||
"users.fields.telegram": "Telegram",
|
||||
"users.fields.createdAt": "Created at",
|
||||
"users.fields.updatedAt": "Updated at",
|
||||
"users.actions.create": "Create user",
|
||||
"users.actions.save": "Save",
|
||||
"users.sections.roles": "Roles",
|
||||
|
||||
@@ -417,6 +417,46 @@
|
||||
"loanPaidOffLetters.columns.passportNumber": "НОМЕР ПАСПОРТА",
|
||||
"loanPaidOffLetters.columns.loanAccount": "КРЕДИТНЫЙ СЧЕТ",
|
||||
"loanPaidOffLetters.columns.issuedAt": "ДАТА ВЫДАЧИ",
|
||||
"loanPaidOffLetters.columns.uniqueId": "УНИКАЛЬНЫЙ ID",
|
||||
"loanPaidOffLetters.columns.customerName": "КЛИЕНТ",
|
||||
"loanPaidOffLetters.columns.phone": "ТЕЛЕФОН",
|
||||
"loanPaidOffLetters.columns.status": "СТАТУС",
|
||||
"loanPaidOffLetters.status.pending": "В ожидании",
|
||||
"loanPaidOffLetters.status.approved": "Одобрено",
|
||||
"loanPaidOffLetters.status.rejected": "Отклонено",
|
||||
"loanPaidOffLetters.regions.AG": "Ашхабад",
|
||||
"loanPaidOffLetters.regions.AH": "Ахал",
|
||||
"loanPaidOffLetters.regions.BA": "Балкан",
|
||||
"loanPaidOffLetters.regions.DA": "Дашогуз",
|
||||
"loanPaidOffLetters.regions.LE": "Лебап",
|
||||
"loanPaidOffLetters.regions.MA": "Мары",
|
||||
"loanPaidOffLetters.sections.info": "Основная информация",
|
||||
"loanPaidOffLetters.sections.customer": "Информация о клиенте",
|
||||
"loanPaidOffLetters.sections.passport": "Паспорт",
|
||||
"loanPaidOffLetters.sections.loan": "Информация о кредите",
|
||||
"loanPaidOffLetters.sections.additional": "Дополнительно",
|
||||
"loanPaidOffLetters.fields.customerName": "Имя",
|
||||
"loanPaidOffLetters.fields.customerSurname": "Фамилия",
|
||||
"loanPaidOffLetters.fields.customerPatronicName": "Отчество",
|
||||
"loanPaidOffLetters.fields.bornAt": "Дата рождения",
|
||||
"loanPaidOffLetters.fields.phone": "Телефон",
|
||||
"loanPaidOffLetters.fields.passportSerie": "Серия паспорта",
|
||||
"loanPaidOffLetters.fields.passportId": "Номер паспорта",
|
||||
"loanPaidOffLetters.fields.loanContractNumber": "Номер кредитного договора",
|
||||
"loanPaidOffLetters.fields.loanContractDate": "Дата кредитного договора",
|
||||
"loanPaidOffLetters.fields.loanAmount": "Сумма кредита",
|
||||
"loanPaidOffLetters.fields.loanReason": "Причина кредита",
|
||||
"loanPaidOffLetters.fields.loanFile": "Файл",
|
||||
"loanPaidOffLetters.fields.region": "Регион",
|
||||
"loanPaidOffLetters.fields.branchId": "ID филиала",
|
||||
"loanPaidOffLetters.fields.userId": "ID пользователя",
|
||||
"loanPaidOffLetters.fields.status": "Статус",
|
||||
"loanPaidOffLetters.fields.uniqueId": "Уникальный ID",
|
||||
"loanPaidOffLetters.fields.notes": "Заметки",
|
||||
"loanPaidOffLetters.view.title": "Информация о справке",
|
||||
"loanPaidOffLetters.deleteSuccess": "Справка успешно удалена",
|
||||
"loanPaidOffLetters.createSuccess": "Успешно создано",
|
||||
"loanPaidOffLetters.updateSuccess": "Успешно обновлено",
|
||||
"loanRemaining.title": "Остаток кредита",
|
||||
"loanRemaining.createButton": "Создать запись об остатке кредита",
|
||||
"loanRemaining.deleteConfirm": "Вы уверены, что хотите удалить эту запись?",
|
||||
@@ -452,6 +492,14 @@
|
||||
"loanDocuments.toast.updateError": "Ошибка при обновлении документа!",
|
||||
"loanDocuments.toast.deleted": "Документ успешно удален!",
|
||||
"loanDocuments.toast.deleteError": "Ошибка при удалении документа!",
|
||||
"loanDocuments.toast.statusUpdated": "Статус документа успешно обновлен!",
|
||||
"loanDocuments.columns.value": "ЗНАЧЕНИЕ",
|
||||
"loanDocuments.columns.isActive": "АКТИВНЫЙ",
|
||||
"loanDocuments.fields.value": "Значение",
|
||||
"loanDocuments.fields.valuePlaceholder": "Значение",
|
||||
"loanDocuments.fields.isActive": "Активный",
|
||||
"common.active": "Активный",
|
||||
"common.inactive": "Неактивный",
|
||||
"common.cancel": "Отмена",
|
||||
"common.confirm": "Подтвердить",
|
||||
"common.back": "Назад",
|
||||
@@ -472,6 +520,7 @@
|
||||
"validation.minLength": "Минимум {length} символов",
|
||||
"validation.invalidEmail": "Неверный формат email",
|
||||
"validation.invalidPhonePrefix": "Неверный код оператора (61-65, 71)",
|
||||
"validation.invalidUrl": "Неверный формат URL",
|
||||
"Status": "Статус",
|
||||
"Card (Salary)": "Карта (Зарплата)",
|
||||
"1. Guarantor": "1. Поручитель",
|
||||
@@ -552,6 +601,17 @@
|
||||
"cardOrder.col.status": "Статус",
|
||||
"cardOrder.create": "Создать заказ карты",
|
||||
"cardOrder.deleteConfirm": "Удалить этот заказ?",
|
||||
"cardOrder.col.number": "Номер карты",
|
||||
"cardOrder.col.expiry": "Срок действия",
|
||||
"cardOrder.col.userId": "ID пользователя",
|
||||
"cardOrder.field.name": "Имя держателя карты",
|
||||
"cardOrder.field.number": "Номер карты",
|
||||
"cardOrder.field.expiry": "Срок действия",
|
||||
"cardOrder.field.updatedAt": "Дата обновления",
|
||||
"cardOrder.field.userId": "ID пользователя",
|
||||
"cardOrder.createSuccess": "Карта успешно создана",
|
||||
"cardOrder.updateSuccess": "Карта успешно обновлена",
|
||||
"cardOrder.deleteSuccess": "Карта успешно удалена",
|
||||
"citizenship.tm": "Туркменистан",
|
||||
"citizenship.ru": "Россия",
|
||||
"citizenship.other": "Другое",
|
||||
@@ -750,7 +810,7 @@
|
||||
"branches.form.subtitle": "Заполните все поля и проходите шаг за шагом.",
|
||||
"branches.sections.address": "Адрес и контакты",
|
||||
"branches.sections.basic": "Основная информация",
|
||||
"branches.sections.hours": "Рабочее время",
|
||||
"branches.sections.billing": "Учетные данные биллинга",
|
||||
"branches.viewTitle": "Детали филиала",
|
||||
"cardBalance.createTitle": "Создать остаток карты",
|
||||
"cardBalance.editTitle": "Редактировать остаток карты",
|
||||
@@ -766,10 +826,13 @@
|
||||
"cardReasons.actions.create": "Создать причину",
|
||||
"cardReasons.actions.update": "Обновить причину",
|
||||
"cardReasons.deleteConfirm": "Вы уверены, что хотите удалить эту причину?",
|
||||
"cardReasons.fields.description": "ОПИСАНИЕ",
|
||||
"cardReasons.fields.isActive": "АКТИВНЫЙ",
|
||||
"cardReasons.fields.name": "НАЗВАНИЕ",
|
||||
"cardReasons.fields.value": "ЗНАЧЕНИЕ",
|
||||
"cardReasons.fields.notes": "ЗАМЕТКИ",
|
||||
"cardReasons.fields.price": "ЦЕНА",
|
||||
"cardReasons.toast.createSuccess": "Причина создана",
|
||||
"cardReasons.toast.updateSuccess": "Причина обновлена",
|
||||
"cardReasons.toast.deleteSuccess": "Причина удалена",
|
||||
"cardReasons.viewTitle": "Детали причины",
|
||||
"cardRequisites.createTitle": "Создать реквизиты карты",
|
||||
"cardRequisites.editTitle": "Редактировать реквизиты карты",
|
||||
@@ -785,6 +848,12 @@
|
||||
"cardTypes.fields.name": "НАЗВАНИЕ",
|
||||
"cardTypes.fields.value": "ЗНАЧЕНИЕ",
|
||||
"cardTypes.view.title": "Детали типа карты",
|
||||
"cardTypes.fields.price": "ЦЕНА",
|
||||
"cardTypes.fields.notes": "ЗАМЕТКИ",
|
||||
"cardTypes.toast.createSuccess": "Тип карты создан",
|
||||
"cardTypes.toast.updateSuccess": "Тип карты обновлен",
|
||||
"cardTypes.toast.deleteSuccess": "Тип карты удален",
|
||||
"cardTypes.toast.statusUpdated": "Статус типа карты обновлен!",
|
||||
"clients.createTitle": "Создать клиента",
|
||||
"clients.editTitle": "Редактировать клиента",
|
||||
"clients.title": "Клиенты",
|
||||
@@ -798,9 +867,9 @@
|
||||
"districts.actions.create": "Создать район",
|
||||
"districts.actions.update": "Обновить район",
|
||||
"districts.deleteConfirm": "Вы уверены, что хотите удалить этот район?",
|
||||
"districts.fields.description": "ПРИМЕЧАНИЯ",
|
||||
"districts.fields.isActive": "АКТИВНЫЙ",
|
||||
"districts.fields.name": "НАЗВАНИЕ",
|
||||
"districts.fields.region": "РЕГИОН",
|
||||
"districts.viewTitle": "Детали района",
|
||||
"intlPayment.createTitle": "Создать платеж Visa/Master",
|
||||
"intlPayment.editTitle": "Редактировать платеж Visa/Master",
|
||||
@@ -824,6 +893,7 @@
|
||||
"loanTypes.deleteDialog.title": "Удалить",
|
||||
"loanTypes.fields.isActive": "Активный",
|
||||
"loanTypes.fields.loanTerm": "Срок кредита",
|
||||
"loanTypes.placeholders.loanTerm": "12, 24, 36",
|
||||
"loanTypes.fields.name": "Название",
|
||||
"loanTypes.fields.notes": "Примечания",
|
||||
"loanTypes.fields.tax": "Налог",
|
||||
@@ -1113,14 +1183,15 @@
|
||||
"branches.fields.uniqueCode": "УНИКАЛЬНЫЙ КОД",
|
||||
"branches.fields.isActive": "АКТИВНЫЙ",
|
||||
"branches.fields.billingIbr": "ЛОГИН БИЛЛИНГА (IBR)",
|
||||
"branches.fields.billingPassword": "ПАРОЛЬ БИЛЛИНГА",
|
||||
"branches.fields.billingSber": "ЛОГИН БИЛЛИНГА (SBER)",
|
||||
"branches.fields.billingSberPassword": "ПАРОЛЬ (SBER)",
|
||||
"branches.fields.billingSwift": "ЛОГИН БИЛЛИНГА (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "ПАРОЛЬ (SWIFT)",
|
||||
"branches.fields.address": "АДРЕС",
|
||||
"branches.fields.billingVisa": "ЛОГИН БИЛЛИНГА (VISA)",
|
||||
"branches.fields.code": "КОД",
|
||||
"branches.fields.description": "ПРИМЕЧАНИЯ",
|
||||
"branches.fields.email": "EMAIL",
|
||||
"branches.fields.phone": "ТЕЛЕФОН",
|
||||
"branches.fields.workingHours": "РАБОЧЕЕ ВРЕМЯ",
|
||||
"branches.fields.billingVisaPassword": "ПАРОЛЬ (VISA)",
|
||||
"branches.fields.phoneNumbers": "ТЕЛЕФОНЫ",
|
||||
"users.title": "Все пользователи",
|
||||
"users.searchPlaceholder": "Поиск",
|
||||
"users.createTitle": "Создание пользователя",
|
||||
@@ -1139,6 +1210,17 @@
|
||||
"users.fields.passwordHint": "Минимум 6 символов",
|
||||
"users.fields.phoneVerified": "Телефон подтвержден",
|
||||
"users.fields.phoneVerifiedHint": "Подтверждено через SMS",
|
||||
"users.fields.avatar": "URL аватара",
|
||||
"users.fields.firstName": "Имя",
|
||||
"users.fields.lastName": "Фамилия",
|
||||
"users.fields.lightMode": "Светлый режим",
|
||||
"users.fields.role": "Роль",
|
||||
"users.fields.socialMedia": "Соцсети",
|
||||
"users.fields.facebook": "Facebook",
|
||||
"users.fields.instagram": "Instagram",
|
||||
"users.fields.telegram": "Telegram",
|
||||
"users.fields.createdAt": "Дата создания",
|
||||
"users.fields.updatedAt": "Дата обновления",
|
||||
"users.actions.create": "Создать пользователя",
|
||||
"users.actions.save": "Сохранить",
|
||||
"users.sections.roles": "Роли",
|
||||
|
||||
@@ -417,6 +417,46 @@
|
||||
"loanPaidOffLetters.columns.passportNumber": "PASPORT BELGISI",
|
||||
"loanPaidOffLetters.columns.loanAccount": "KARZ HASABY",
|
||||
"loanPaidOffLetters.columns.issuedAt": "BERLEN WAGTY",
|
||||
"loanPaidOffLetters.columns.uniqueId": "UNIKAL ID",
|
||||
"loanPaidOffLetters.columns.customerName": "MÜŞDERI",
|
||||
"loanPaidOffLetters.columns.phone": "TELEFON",
|
||||
"loanPaidOffLetters.columns.status": "STATUS",
|
||||
"loanPaidOffLetters.status.pending": "Garaşylýar",
|
||||
"loanPaidOffLetters.status.approved": "Tassyklandy",
|
||||
"loanPaidOffLetters.status.rejected": "Red edildi",
|
||||
"loanPaidOffLetters.regions.AG": "Aşgabat",
|
||||
"loanPaidOffLetters.regions.AH": "Ahal",
|
||||
"loanPaidOffLetters.regions.BA": "Balkan",
|
||||
"loanPaidOffLetters.regions.DA": "Daşoguz",
|
||||
"loanPaidOffLetters.regions.LE": "Lebap",
|
||||
"loanPaidOffLetters.regions.MA": "Mary",
|
||||
"loanPaidOffLetters.sections.info": "Esasy maglumatlar",
|
||||
"loanPaidOffLetters.sections.customer": "Müşderi maglumatlary",
|
||||
"loanPaidOffLetters.sections.passport": "Pasport",
|
||||
"loanPaidOffLetters.sections.loan": "Karz maglumatlary",
|
||||
"loanPaidOffLetters.sections.additional": "Goşmaça",
|
||||
"loanPaidOffLetters.fields.customerName": "Ady",
|
||||
"loanPaidOffLetters.fields.customerSurname": "Familiýasy",
|
||||
"loanPaidOffLetters.fields.customerPatronicName": "Atasynyň ady",
|
||||
"loanPaidOffLetters.fields.bornAt": "Doglan senesi",
|
||||
"loanPaidOffLetters.fields.phone": "Telefon",
|
||||
"loanPaidOffLetters.fields.passportSerie": "Pasport seriýasy",
|
||||
"loanPaidOffLetters.fields.passportId": "Pasport belgisi",
|
||||
"loanPaidOffLetters.fields.loanContractNumber": "Karz şertnamasy belgisi",
|
||||
"loanPaidOffLetters.fields.loanContractDate": "Karz şertnamasy senesi",
|
||||
"loanPaidOffLetters.fields.loanAmount": "Karz möçberi",
|
||||
"loanPaidOffLetters.fields.loanReason": "Karz sebäbi",
|
||||
"loanPaidOffLetters.fields.loanFile": "Faýl",
|
||||
"loanPaidOffLetters.fields.region": "Sebit",
|
||||
"loanPaidOffLetters.fields.branchId": "Şahamça ID",
|
||||
"loanPaidOffLetters.fields.userId": "Ulanyjy ID",
|
||||
"loanPaidOffLetters.fields.status": "Status",
|
||||
"loanPaidOffLetters.fields.uniqueId": "Unikal ID",
|
||||
"loanPaidOffLetters.fields.notes": "Bellikler",
|
||||
"loanPaidOffLetters.view.title": "Güwanama maglumaty",
|
||||
"loanPaidOffLetters.deleteSuccess": "Güwanama üstünlikli pozuldy",
|
||||
"loanPaidOffLetters.createSuccess": "Üstünlikli döredildi",
|
||||
"loanPaidOffLetters.updateSuccess": "Üstünlikli üýtgedildi",
|
||||
"loanRemaining.title": "Karzyň galyndysy",
|
||||
"loanRemaining.createButton": "Karzyň galyndysy dörediň",
|
||||
"loanRemaining.deleteConfirm": "Bu ýazgy pozulsynmy?",
|
||||
@@ -452,6 +492,14 @@
|
||||
"loanDocuments.toast.updateError": "Resminama täzelenende ýalňyşlyk ýüze çykdy!",
|
||||
"loanDocuments.toast.deleted": "Resminama üstünlikli öçürildi!",
|
||||
"loanDocuments.toast.deleteError": "Resminama öçürilende ýalňyşlyk ýüze çykdy!",
|
||||
"loanDocuments.toast.statusUpdated": "Resminama statusy üstünlikli täzelendi!",
|
||||
"loanDocuments.columns.value": "BAHA",
|
||||
"loanDocuments.columns.isActive": "IŞJEŇ",
|
||||
"loanDocuments.fields.value": "Baha",
|
||||
"loanDocuments.fields.valuePlaceholder": "Baha",
|
||||
"loanDocuments.fields.isActive": "Işjeň",
|
||||
"common.active": "Işjeň",
|
||||
"common.inactive": "Işjeň däl",
|
||||
"common.cancel": "Ýatyrmak",
|
||||
"common.confirm": "Tassykla",
|
||||
"common.back": "Yza gaýtmak",
|
||||
@@ -472,6 +520,7 @@
|
||||
"validation.minLength": "Iň az {length} harp giriziň",
|
||||
"validation.invalidEmail": "Nädogry e-poçta formaty",
|
||||
"validation.invalidPhonePrefix": "Nädogry operator kody (61-65, 71)",
|
||||
"validation.invalidUrl": "Nädogry URL formaty",
|
||||
"Status": "Ýagdaý",
|
||||
"Card (Salary)": "Kart (Zähmet haky)",
|
||||
"1. Guarantor": "1. Zamun",
|
||||
@@ -550,8 +599,19 @@
|
||||
"cardOrder.col.branch": "Şahamça",
|
||||
"cardOrder.col.name": "Ady",
|
||||
"cardOrder.col.status": "Status",
|
||||
"cardOrder.create": "Kart sargyt dörediň",
|
||||
"cardOrder.deleteConfirm": "Bu sargyt pozulsynmy?",
|
||||
"cardOrder.create": "Kart dörediň",
|
||||
"cardOrder.deleteConfirm": "Bu kart pozulsynmy?",
|
||||
"cardOrder.col.number": "Kart belgisi",
|
||||
"cardOrder.col.expiry": "Möhleti",
|
||||
"cardOrder.col.userId": "Ulanyjy ID",
|
||||
"cardOrder.field.name": "Kart eýesiniň ady",
|
||||
"cardOrder.field.number": "Kart belgisi",
|
||||
"cardOrder.field.expiry": "Kart möhleti",
|
||||
"cardOrder.field.updatedAt": "Täzelenen wagty",
|
||||
"cardOrder.field.userId": "Ulanyjy ID",
|
||||
"cardOrder.createSuccess": "Kart üstünlikli döredildi",
|
||||
"cardOrder.updateSuccess": "Kart üstünlikli täzelendi",
|
||||
"cardOrder.deleteSuccess": "Kart üstünlikli pozuldy",
|
||||
"citizenship.tm": "Türkmenistan",
|
||||
"citizenship.ru": "Russiýa",
|
||||
"citizenship.other": "Beýlekiler",
|
||||
@@ -748,7 +808,7 @@
|
||||
"branches.form.subtitle": "Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.",
|
||||
"branches.sections.address": "Salgy we habarlaşmak",
|
||||
"branches.sections.basic": "Esasy maglumatlar",
|
||||
"branches.sections.hours": "Iş wagty",
|
||||
"branches.sections.billing": "Billing maglumatlary",
|
||||
"branches.viewTitle": "Şahamça giňişleýin",
|
||||
"cardBalance.createTitle": "Kart galyndy döretmek",
|
||||
"cardBalance.editTitle": "Kart galyndy üýtgetmek",
|
||||
@@ -764,10 +824,13 @@
|
||||
"cardReasons.actions.create": "Kartyň çykarylmagynyň sebäbini döretdiň",
|
||||
"cardReasons.actions.update": "Sebäbi täzelemek",
|
||||
"cardReasons.deleteConfirm": "Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?",
|
||||
"cardReasons.fields.description": "BELLIKLER",
|
||||
"cardReasons.fields.isActive": "IŞJEŇ",
|
||||
"cardReasons.fields.name": "ADY",
|
||||
"cardReasons.fields.value": "BAHA",
|
||||
"cardReasons.fields.notes": "BELLIKLER",
|
||||
"cardReasons.fields.price": "BAHA",
|
||||
"cardReasons.toast.createSuccess": "Sebäp döredildi",
|
||||
"cardReasons.toast.updateSuccess": "Sebäp täzelendi",
|
||||
"cardReasons.toast.deleteSuccess": "Sebäp öçürildi",
|
||||
"cardReasons.viewTitle": "Sebäp giňişleýin",
|
||||
"cardRequisites.createTitle": "Kart rekwizit döretmek",
|
||||
"cardRequisites.editTitle": "Kart rekwizit üýtgetmek",
|
||||
@@ -783,6 +846,12 @@
|
||||
"cardTypes.fields.name": "ADY",
|
||||
"cardTypes.fields.value": "BAHA",
|
||||
"cardTypes.view.title": "Kart görnüşi giňişleýin",
|
||||
"cardTypes.fields.price": "BAHA",
|
||||
"cardTypes.fields.notes": "BELLIKLER",
|
||||
"cardTypes.toast.createSuccess": "Kart görnüşi döredildi",
|
||||
"cardTypes.toast.updateSuccess": "Kart görnüşi täzelendi",
|
||||
"cardTypes.toast.deleteSuccess": "Kart görnüşi öçürildi",
|
||||
"cardTypes.toast.statusUpdated": "Kart görnüşi statusy täzelendi!",
|
||||
"clients.createTitle": "Müşderi döretmek",
|
||||
"clients.editTitle": "Müşderi üýtgetmek",
|
||||
"clients.title": "Müşderiler",
|
||||
@@ -796,9 +865,9 @@
|
||||
"districts.actions.create": "Etrap döret",
|
||||
"districts.actions.update": "Etraby täzelemek",
|
||||
"districts.deleteConfirm": "Bu etrapy öçürmek isleýärsiňizmi?",
|
||||
"districts.fields.description": "BELLIKLER",
|
||||
"districts.fields.isActive": "IŞJEŇ",
|
||||
"districts.fields.name": "ADY",
|
||||
"districts.fields.region": "SEBIT",
|
||||
"districts.viewTitle": "Etrap giňişleýin",
|
||||
"intlPayment.createTitle": "Visa/Master töleg döretmek",
|
||||
"intlPayment.editTitle": "Visa/Master töleg üýtgetmek",
|
||||
@@ -822,6 +891,7 @@
|
||||
"loanTypes.deleteDialog.title": "Pozmak",
|
||||
"loanTypes.fields.isActive": "Işjeň",
|
||||
"loanTypes.fields.loanTerm": "Karz möhleti",
|
||||
"loanTypes.placeholders.loanTerm": "12, 24, 36",
|
||||
"loanTypes.fields.name": "Ady",
|
||||
"loanTypes.fields.notes": "Bellikler",
|
||||
"loanTypes.fields.tax": "Salgyt",
|
||||
@@ -1111,14 +1181,15 @@
|
||||
"branches.fields.uniqueCode": "UNIKAL BELGI",
|
||||
"branches.fields.isActive": "IŞJEŇ",
|
||||
"branches.fields.billingIbr": "BILLING ULANYJY ADY",
|
||||
"branches.fields.billingPassword": "BILLING PAROL",
|
||||
"branches.fields.billingSber": "BILLING USERNAME (SBER)",
|
||||
"branches.fields.billingSberPassword": "PAROL (SBER)",
|
||||
"branches.fields.billingSwift": "BILLING ULANYJY ADY (SWIFT)",
|
||||
"branches.fields.billingSwiftPassword": "PAROL (SWIFT)",
|
||||
"branches.fields.address": "SALGY",
|
||||
"branches.fields.billingVisa": "BILLING USERNAME (VISA)",
|
||||
"branches.fields.code": "KOD",
|
||||
"branches.fields.description": "BELLIKLER",
|
||||
"branches.fields.email": "E-POÇTA",
|
||||
"branches.fields.phone": "TELEFON",
|
||||
"branches.fields.workingHours": "IŞ WAGTY",
|
||||
"branches.fields.billingVisaPassword": "PAROL (VISA)",
|
||||
"branches.fields.phoneNumbers": "TELEFONLAR",
|
||||
"users.title": "Ähli ulanyjylar",
|
||||
"users.searchPlaceholder": "Gözlemek",
|
||||
"users.createTitle": "Ulanyjy döretmek",
|
||||
@@ -1137,6 +1208,17 @@
|
||||
"users.fields.passwordHint": "Iň az 6 harp",
|
||||
"users.fields.phoneVerified": "Telefon tassyklanan",
|
||||
"users.fields.phoneVerifiedHint": "SMS arkaly tassyklandy",
|
||||
"users.fields.avatar": "Awatar URL",
|
||||
"users.fields.firstName": "Ady (at)",
|
||||
"users.fields.lastName": "Familiýasy",
|
||||
"users.fields.lightMode": "Light režimi",
|
||||
"users.fields.role": "Roly",
|
||||
"users.fields.socialMedia": "Sosial media",
|
||||
"users.fields.facebook": "Facebook",
|
||||
"users.fields.instagram": "Instagram",
|
||||
"users.fields.telegram": "Telegram",
|
||||
"users.fields.createdAt": "Döredilen wagty",
|
||||
"users.fields.updatedAt": "Täzelenen wagty",
|
||||
"users.actions.create": "Ulanyjy dörediň",
|
||||
"users.actions.save": "Ýatda sakla",
|
||||
"users.sections.roles": "Rollar",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export * from "./utils/dateUtils";
|
||||
export * from "./utils/phoneUtils";
|
||||
|
||||
57
src/lib/utils/dateUtils.ts
Normal file
57
src/lib/utils/dateUtils.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* UI'daki 'YYYY-MM-DD' veya Date nesnesini backend'in PUT/POST isteklerinde beklediği ISO UTC formatına çevirir.
|
||||
* Örn: '1987-04-08' -> '1987-04-08T00:00:00Z'
|
||||
*/
|
||||
export function formatToApiDate(dateStr?: string | Date | null): string {
|
||||
if (!dateStr) return "";
|
||||
|
||||
if (typeof dateStr === "string") {
|
||||
const trimmed = dateStr.trim();
|
||||
if (!trimmed) return "";
|
||||
|
||||
// Zaten ISO UTC formatındaysa (örn: 1987-04-08T00:00:00Z)
|
||||
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/i.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// YYYY-MM-DD formatında ise T00:00:00Z ekle
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
|
||||
return `${trimmed}T00:00:00Z`;
|
||||
}
|
||||
|
||||
// Diğer tarih formatları için JavaScript Date nesnesi üzerinden UTC dönüştür
|
||||
const d = new Date(trimmed);
|
||||
if (!isNaN(d.getTime())) {
|
||||
const year = d.getUTCFullYear();
|
||||
const month = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}T00:00:00Z`;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (dateStr instanceof Date && !isNaN(dateStr.getTime())) {
|
||||
const year = dateStr.getUTCFullYear();
|
||||
const month = String(dateStr.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(dateStr.getUTCDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}T00:00:00Z`;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Backend'den gelen ISO UTC tarih formatını UI datepicker/input'unun beklediği 'YYYY-MM-DD' formatına çevirir.
|
||||
* Örn: '1987-04-08T00:00:00Z' -> '1987-04-08'
|
||||
*/
|
||||
export function formatFromApiDate(isoStr?: string | null): string {
|
||||
if (!isoStr) return "";
|
||||
const trimmed = isoStr.trim();
|
||||
if (!trimmed) return "";
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}/.test(trimmed)) {
|
||||
return trimmed.slice(0, 10);
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
47
src/lib/utils/phoneUtils.ts
Normal file
47
src/lib/utils/phoneUtils.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Backend'den gelen (+993 61 09 76 51 veya +99361097651) veya UI girdisini
|
||||
* UI input'unun görüntülemesi için temiz 8 haneli yerel rakam dizesine çevirir.
|
||||
* Örn: "+993 61 09 76 51" -> "61097651"
|
||||
* Örn: "+99361097651" -> "61097651"
|
||||
* Örn: "61 09 76 51" -> "61097651"
|
||||
*/
|
||||
export function cleanPhoneNumber(phoneStr?: string | null): string {
|
||||
if (!phoneStr) return "";
|
||||
|
||||
let digits = phoneStr.replace(/\D/g, "");
|
||||
|
||||
if (digits.startsWith("993") && digits.length === 11) {
|
||||
digits = digits.slice(3);
|
||||
}
|
||||
|
||||
return digits.slice(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Backend'den gelen veriyi UI input'una basarken 8 haneli yerel numaraya çevirir.
|
||||
*/
|
||||
export function formatFromApiPhone(phoneStr?: string | null): string {
|
||||
return cleanPhoneNumber(phoneStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* UI'daki 8 haneli telefon numarasını backend PUT/POST isteğine gönderilirken "+993" ülke kodlu formata çevirir.
|
||||
* Örn: "61097651" -> "+99361097651"
|
||||
* Örn: "61 09 76 51" -> "+99361097651"
|
||||
* Örn: "+993 61 09 76 51" -> "+99361097651"
|
||||
*/
|
||||
export function formatToApiPhone(phoneStr?: string | null): string {
|
||||
const digits = cleanPhoneNumber(phoneStr);
|
||||
if (!digits) return "";
|
||||
return `+993${digits}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* İsteğe bağlı: Temizlenmiş 8 haneli telefon numarasını UI gösteriminde boşluklu formatlama
|
||||
* Örn: "61097651" -> "61 09 76 51" veya "61 097651"
|
||||
*/
|
||||
export function formatPhoneForDisplay(phoneStr?: string | null): string {
|
||||
const digits = cleanPhoneNumber(phoneStr);
|
||||
if (digits.length <= 2) return digits;
|
||||
return `${digits.slice(0, 2)} ${digits.slice(2)}`;
|
||||
}
|
||||
@@ -1,117 +1,195 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import { DataTableToolbar, type ColumnMeta, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
|
||||
import { useCardPins, useDeleteCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
import { type CardPinStatus, type CardPinItem } from "@/features/cardPins/api/cardPinApi";
|
||||
|
||||
// ─── Status Badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import type { CardPinOrder } from "@/features/cardPins/api/cardPinApi";
|
||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
|
||||
// ─── Filter field IDs ──────────────────────────────────────────────────────────
|
||||
|
||||
const FILTER_IDS = ["status", "branch_id", "user_id", "card_type_id", "region"] as const;
|
||||
type FilterId = (typeof FILTER_IDS)[number];
|
||||
|
||||
const INITIAL_FILTERS: ActiveFilter[] = FILTER_IDS.map((fieldId) => ({ fieldId, value: "" }));
|
||||
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
pending: {
|
||||
label: "Garaşylýar",
|
||||
variant: "warning" as StatusBadgeVariant,
|
||||
icon: AlertCircle,
|
||||
},
|
||||
approved: {
|
||||
label: "Tassyklandy",
|
||||
variant: "success" as StatusBadgeVariant,
|
||||
icon: CheckCircle2,
|
||||
},
|
||||
rejected: {
|
||||
label: "Ýatyryldy",
|
||||
variant: "error" as StatusBadgeVariant,
|
||||
icon: XCircle,
|
||||
},
|
||||
} satisfies Record<CardPinStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }>;
|
||||
const PENDING_STATUSES = [
|
||||
"pending",
|
||||
"garaşylýar",
|
||||
"garaşilyar",
|
||||
"garasylýar",
|
||||
"garasilyar",
|
||||
"garasylyar",
|
||||
"kutilyor",
|
||||
"kutiliyor",
|
||||
"waiting",
|
||||
"beklemede",
|
||||
];
|
||||
const APPROVED_STATUSES = [
|
||||
"approved",
|
||||
"tassyklandy",
|
||||
"tassyklanan",
|
||||
"tassyklandy",
|
||||
"tassyklanyldy",
|
||||
"accepted",
|
||||
"confirmed",
|
||||
"success",
|
||||
"completed",
|
||||
"approve",
|
||||
];
|
||||
const REJECTED_STATUSES = [
|
||||
"rejected",
|
||||
"reject",
|
||||
"ret",
|
||||
"ýatyryldy",
|
||||
"yatyryldy",
|
||||
"canceled",
|
||||
"cancelled",
|
||||
"cancelled",
|
||||
"declined",
|
||||
"failed",
|
||||
"error",
|
||||
"reject",
|
||||
"red edildi",
|
||||
];
|
||||
|
||||
function CardPinStatusStatusBadge({ status }: { status: CardPinStatus }) {
|
||||
const cfg = STATUS_CONFIG[status];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{String(status)}</span>;
|
||||
function statusConfig(status: string): { label: string; variant: StatusBadgeVariant; icon?: React.ElementType } {
|
||||
const key = status.trim().toLowerCase();
|
||||
if (PENDING_STATUSES.includes(key)) return { label: "Garaşylýar", variant: "warning", icon: AlertCircle };
|
||||
if (APPROVED_STATUSES.includes(key)) return { label: "Tassyklandy", variant: "success", icon: CheckCircle2 };
|
||||
if (REJECTED_STATUSES.includes(key)) return { label: "Ýatyryldy", variant: "error", icon: XCircle };
|
||||
return { label: status, variant: "default" };
|
||||
}
|
||||
|
||||
function StatusCell({ status }: { status: string }) {
|
||||
const cfg = statusConfig(status);
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const PER_PAGE = 25;
|
||||
|
||||
export default function CardPinsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [search, setSearch] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<CardPinStatus | "">("");
|
||||
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
|
||||
const [deleteTarget, setDeleteTarget] = useState<CardPinItem | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<CardPinOrder | null>(null);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
||||
|
||||
const { data, isLoading } = useCardPins({
|
||||
page,
|
||||
per_page: perPage,
|
||||
search,
|
||||
status: statusFilter,
|
||||
});
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const { data: branchesData } = useBranches({ page, limit: 25 });
|
||||
const { data: districtsData } = useDistricts({ page, limit: 25 });
|
||||
const { data: cardTypesData } = useCardTypes({ page, limit: 25 });
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
search: search || undefined,
|
||||
page,
|
||||
limit: perPage,
|
||||
status: getFilter("status") || undefined,
|
||||
branch_id: getFilter("branch_id") || undefined,
|
||||
user_id: getFilter("user_id") || undefined,
|
||||
card_type_id: getFilter("card_type_id") || undefined,
|
||||
region: getFilter("region") || undefined,
|
||||
}),
|
||||
[search, page, perPage, getFilter],
|
||||
);
|
||||
|
||||
const { data, isLoading } = useCardPins(queryParams);
|
||||
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin();
|
||||
|
||||
const columns: ColumnDef<CardPinItem>[] = [
|
||||
const columns: ColumnDef<CardPinOrder>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
cell: ({ row }) => <span className="font-mono text-xs text-muted-foreground">{row.original.id}</span>,
|
||||
header: t("cardPin.col.id", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button className="text-primary font-medium hover:underline text-left" onClick={() => navigate(`/card-pins/${row.original.id}`)}>
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
accessorKey: "card_type_label",
|
||||
header: t("cardPin.cardType", "Görnüşi"),
|
||||
cell: ({ row }) => <span className="text-sm font-medium text-primary">{row.original.card_type_label}</span>,
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("cardPin.col.uniqueId", "Sargyt belgisi"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.uniqueId}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: t("cardPin.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground whitespace-nowrap">{row.original.created_at}</span>,
|
||||
id: "cardNumber",
|
||||
accessorKey: "cardNumber",
|
||||
header: t("cardPin.col.cardNumber", "Kart belgisi"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.cardNumber}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "province_label",
|
||||
header: t("cardPin.province", "Welaýat"),
|
||||
id: "customerName",
|
||||
accessorKey: "customerName",
|
||||
header: t("cardPin.col.customer", "Müşderi"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">
|
||||
{row.original.customerName} {row.original.customerSurname}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "branch_label",
|
||||
header: t("cardPin.branch", "Şahamça"),
|
||||
cell: ({ row }) => <span className="text-primary font-medium">{row.original.branch_label}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "first_name",
|
||||
header: t("cardPin.firstName", "Ady"),
|
||||
},
|
||||
{
|
||||
accessorKey: "last_name",
|
||||
header: t("cardPin.lastName", "Familiýasy"),
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("cardPin.col.region", "Sebit"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("cardPin.phone", "Telefon"),
|
||||
header: t("cardPin.col.phone", "Telefon"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.phone}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("cardPin.status", "Status"),
|
||||
cell: ({ row }) => <CardPinStatusStatusBadge status={row.original.status} />,
|
||||
header: t("cardPin.col.status", "Statusy"),
|
||||
cell: ({ row }) => <StatusCell status={row.original.status} />,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("cardPin.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.createdAt ? new Date(row.original.createdAt).toLocaleString() : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
@@ -121,16 +199,74 @@ export default function CardPinsPage() {
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
];
|
||||
|
||||
const columnMeta = columns
|
||||
.filter((c) => ("accessorKey" in c || "id" in c) && c.id !== "actions")
|
||||
.map((c) => {
|
||||
const id = ("accessorKey" in c ? String(c.accessorKey) : c.id) as string;
|
||||
const label = typeof c.header === "string" ? c.header : "accessorKey" in c ? String(c.accessorKey) : id;
|
||||
return { id, label };
|
||||
});
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
|
||||
// ── Filter fields ──────────────────────────────────────────────────────────
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("cardPin.filter.status", "Status"),
|
||||
options: [
|
||||
{ value: "pending", label: t("cardPin.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardPin.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("cardPin.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "branch_id",
|
||||
label: t("cardPin.filter.branch", "Şahamça"),
|
||||
options: (branchesData?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
label: t("cardPin.filter.region", "Sebit"),
|
||||
options: (districtsData?.provinces ?? []).map((d) => ({
|
||||
value: d.region?.tm || d.name.tm,
|
||||
label: d.name[lang] || d.name.tm,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "user_id",
|
||||
label: t("cardPin.filter.userId", "Ulanyjy ID"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: "card_type_id",
|
||||
label: t("cardPin.filter.cardTypeId", "Kart görnüşi"),
|
||||
options: (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||
value: String(ct.id),
|
||||
label: ct.title[lang] || ct.title.tm,
|
||||
})),
|
||||
},
|
||||
],
|
||||
[t, lang, branchesData, districtsData, cardTypesData],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters(INITIAL_FILTERS);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -161,47 +297,32 @@ export default function CardPinsPage() {
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
filterFields={[
|
||||
{
|
||||
id: "status",
|
||||
label: t("cardPin.status", "Status"),
|
||||
options: [
|
||||
{ value: "pending", label: "Garaşylýar" },
|
||||
{ value: "approved", label: "Tassyklandy" },
|
||||
{ value: "rejected", label: "Ret edildi" },
|
||||
],
|
||||
},
|
||||
]}
|
||||
activeFilters={[{ fieldId: "status", value: statusFilter }]}
|
||||
onFilterChange={(fieldId, value) => {
|
||||
if (fieldId === "status") setStatusFilter(value as CardPinStatus | "");
|
||||
setPage(1);
|
||||
}}
|
||||
onFilterReset={() => {
|
||||
setStatusFilter("");
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardPinOrders ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
currentPage={data?.meta?.current_page ?? 1}
|
||||
totalPages={data?.meta?.last_page ?? 1}
|
||||
totalCount={data?.meta?.total}
|
||||
getRowId={(row) => row.id.toString()}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
@@ -213,7 +334,7 @@ export default function CardPinsPage() {
|
||||
if (!o) setDeleteTarget(null);
|
||||
}}
|
||||
title={t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")}
|
||||
description={`${t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} ${deleteTarget?.id ?? ""}`}
|
||||
description={t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")}
|
||||
onConfirm={() => {
|
||||
if (deleteTarget) {
|
||||
deletePin(deleteTarget.id, {
|
||||
|
||||
@@ -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 { CardPinForm } from '@/features/cardPins/components/cardPinForm'
|
||||
import { useCardPin } from '@/features/cardPins/hooks/useCardPins'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageSpinner } from "@/components/pageSpinner";
|
||||
import { PageError } from "@/components/pageError";
|
||||
import { CardPinForm } from "@/features/cardPins/components/cardPinForm";
|
||||
import { useCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
|
||||
export default function CardPinEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const { data, isLoading, isError } = useCardPin(id ?? '')
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { t } = useTranslation();
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading, isError } = useCardPin(numericId);
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (isError || !data) return <PageError message={t('common.notFound', 'Maglumat tapylmady')} />
|
||||
if (isLoading) return <PageSpinner />;
|
||||
if (isError || !data) return <PageError message={t("common.notFound", "Maglumat tapylmady")} />;
|
||||
|
||||
return <CardPinForm mode="edit" initialData={data} />
|
||||
return <CardPinForm mode="edit" initialData={data} />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useCardPin, useDeleteCardPin } from "@/features/cardPins/hooks/useCardPins";
|
||||
import type { CardPinStatus } from "@/features/cardPins/api/cardPinApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
@@ -14,31 +16,63 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
|
||||
// ─── Status config ────────────────────────────────────────────────────────────
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_VARIANT: Record<CardPinStatus, StatusBadgeVariant> = {
|
||||
pending: "warning",
|
||||
approved: "success",
|
||||
rejected: "error",
|
||||
};
|
||||
const PENDING_STATUSES = [
|
||||
"pending",
|
||||
"garaşylýar",
|
||||
"garaşilyar",
|
||||
"garasylýar",
|
||||
"garasilyar",
|
||||
"garasylyar",
|
||||
"kutilyor",
|
||||
"kutiliyor",
|
||||
"waiting",
|
||||
"beklemede",
|
||||
];
|
||||
const APPROVED_STATUSES = [
|
||||
"approved",
|
||||
"tassyklandy",
|
||||
"tassyklanan",
|
||||
"tassyklandy",
|
||||
"tassyklanyldy",
|
||||
"accepted",
|
||||
"confirmed",
|
||||
"success",
|
||||
"completed",
|
||||
"approve",
|
||||
];
|
||||
const REJECTED_STATUSES = [
|
||||
"rejected",
|
||||
"reject",
|
||||
"ret",
|
||||
"ýatyryldy",
|
||||
"yatyryldy",
|
||||
"canceled",
|
||||
"cancelled",
|
||||
"cancelled",
|
||||
"declined",
|
||||
"failed",
|
||||
"error",
|
||||
"reject",
|
||||
"red edildi",
|
||||
];
|
||||
|
||||
const STATUS_ICON: Record<CardPinStatus, React.ElementType> = {
|
||||
pending: AlertCircle,
|
||||
approved: CheckCircle2,
|
||||
rejected: XCircle,
|
||||
};
|
||||
function statusConfig(status: string): { label: string; variant: StatusBadgeVariant; icon?: React.ElementType } {
|
||||
const key = status.trim().toLowerCase();
|
||||
if (PENDING_STATUSES.includes(key)) return { label: "Garaşylýar", variant: "warning", icon: AlertCircle };
|
||||
if (APPROVED_STATUSES.includes(key)) return { label: "Tassyklandy", variant: "success", icon: CheckCircle2 };
|
||||
if (REJECTED_STATUSES.includes(key)) return { label: "Ýatyryldy", variant: "error", icon: XCircle };
|
||||
return { label: status, variant: "default" };
|
||||
}
|
||||
|
||||
function CardPinStatusBadge({ status }: { status: CardPinStatus }) {
|
||||
const { t } = useTranslation();
|
||||
const variant = STATUS_VARIANT[status];
|
||||
const Icon = STATUS_ICON[status];
|
||||
if (!variant) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(`cardPin.status.${status}`)} variant={variant} icon={Icon} />;
|
||||
function CardPinStatusBadge({ status }: { status: string }) {
|
||||
const cfg = statusConfig(status);
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── Skeleton ─────────────────────────────────────────────────────────────────
|
||||
@@ -68,37 +102,43 @@ export default function CardPinViewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data, isLoading, isError } = useCardPin(id!);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading, isError } = useCardPin(numericId);
|
||||
const { mutate: deletePin, isPending: isDeleting } = useDeleteCardPin();
|
||||
|
||||
if (isLoading) {
|
||||
return <CardPinViewSkeleton />;
|
||||
}
|
||||
if (isLoading) return <CardPinViewSkeleton />;
|
||||
|
||||
if (isError || !data) {
|
||||
return <div className="flex items-center justify-center py-24 text-muted-foreground">{t("common.notFound", "Maglumat tapylmady")}</div>;
|
||||
}
|
||||
|
||||
const fmtDate = (v?: string | null) => (v ? new Date(v).toLocaleDateString() : "—");
|
||||
|
||||
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("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: {data.id}
|
||||
{t("cardPin.viewTitle", "Kart pin bukja giňişleýin")}: <span className="text-primary font-mono">{data.uniqueId}</span>
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertDialog>
|
||||
<AlertDialogTitle asChild>
|
||||
<Button size="icon" variant="ghost" className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10">
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
title={t("common.delete", "Poz")}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
</AlertDialogTitle>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("cardPin.deleteTitle", "Pozmak isleýärsiňizmi?")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")} {data.id}
|
||||
</AlertDialogDescription>
|
||||
<AlertDialogDescription>{t("cardPin.deleteDesc", "Bu amal yzyna dolanyp bolmaz.")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
@@ -107,13 +147,19 @@ export default function CardPinViewPage() {
|
||||
className="bg-destructive hover:bg-destructive/90"
|
||||
onClick={() => deletePin(data.id, { onSuccess: () => navigate("/card-pins") })}
|
||||
>
|
||||
{t("common.delete", "Poz")}
|
||||
{isDeleting ? t("common.deleting", "Pozulýar...") : t("common.delete", "Poz")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
<Button size="icon" variant="ghost" className="h-8 w-8" onClick={() => navigate(`/card-pins/${id}/edit`)}>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-8 w-8"
|
||||
onClick={() => navigate(`/card-pins/${numericId}/edit`)}
|
||||
title={t("common.edit", "Düzet")}
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -123,53 +169,47 @@ export default function CardPinViewPage() {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard title={t("cardPin.metaSection", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
<InfoRow label={t("cardPin.createdAt", "Döredilen wagty")} value={data.created_at} />
|
||||
<InfoRow label={t("cardPin.status", "Status")}>
|
||||
<InfoRow label={t("cardPin.field.uniqueId", "Sargyt belgisi")} value={data.uniqueId} />
|
||||
<InfoRow label={t("cardPin.field.status", "Status")}>
|
||||
<CardPinStatusBadge status={data.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("cardPin.note", "Bellik")} value={data.note || undefined} />
|
||||
<InfoRow label={t("cardPin.createdBy", "Sargyt eden")} value={data.created_by_label} isLink />
|
||||
<InfoRow label={t("cardPin.field.notes", "Bellik")} value={data.notes || undefined} />
|
||||
<InfoRow
|
||||
label={t("cardPin.col.createdAt", "Döredilen wagty")}
|
||||
value={data.createdAt ? new Date(data.createdAt).toLocaleString() : "—"}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardPin.cardSection", "Kart")}>
|
||||
<InfoRow label={t("cardPin.cardNumber", "Kart belgisi")} value={data.card_number} />
|
||||
<InfoRow label={t("cardPin.cardExpireMonth", "Kart Möhleti (aý)")} value={null} />
|
||||
<InfoRow label={t("cardPin.cardExpireYear", "Kart Möhleti (ýyl)")} value={null} />
|
||||
<InfoRow label={t("cardPin.field.cardNumber", "Kart belgisi")} value={data.cardNumber} />
|
||||
<InfoRow label={t("cardPin.field.cardTypeId", "Kart görnüşi ID")} value={data.cardTypeId} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardPin.locationSection", "Lokasiýa")}>
|
||||
<InfoRow label={t("cardPin.province", "Welaýat")} value={data.province_label} />
|
||||
<InfoRow label={t("cardPin.branch", "Şahamça")} value={data.branch_label} isLink />
|
||||
<InfoRow label={t("cardPin.field.region", "Sebit")} value={data.region || undefined} />
|
||||
<InfoRow label={t("cardPin.field.branchId", "Şahamça ID")} value={data.branchId} />
|
||||
<InfoRow label={t("cardPin.field.userId", "Ulanyjy ID")} value={data.userId} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Şahsy + Pasport maglumatlary ─────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardPin.personalSection", "Şahsy maglumatlar")}>
|
||||
<InfoRow label={t("cardPin.fullName", "Doly ady")} value={`${data.last_name} ${data.first_name} ${data.father_name}`} />
|
||||
<InfoRow label={t("cardPin.birthDate", "Doglan güni")} value={data.birth_date} />
|
||||
<InfoRow label={t("cardPin.phone", "Telefon")} value={`+${data.phone}`} />
|
||||
<InfoRow
|
||||
label={t("cardPin.fullName", "Doly ady")}
|
||||
value={`${data.customerSurname} ${data.customerName} ${data.customerPatronicName ?? ""}`.trim()}
|
||||
/>
|
||||
<InfoRow label={t("cardPin.field.bornAt", "Doglan güni")} value={fmtDate(data.bornAt)} />
|
||||
<InfoRow label={t("cardPin.field.phone", "Telefon")} value={data.phone} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardPin.passportSection", "Pasport")}>
|
||||
<InfoRow label={t("cardPin.passportSeries", "Pasport seriýasy")} value={data.passport_series} />
|
||||
<InfoRow label={t("cardPin.passportNumber", "Pasport belgisi")} value={data.passport_number} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Passport images ───────────────────────────────────────── */}
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard title={t("cardPin.passportFile1", "Sahypa 1")}>
|
||||
<PassportImage label={t("cardPin.passportFile1", "Pasport (sahypa 1)")} url={data.passport_file_1} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardPin.passportFile2", "Sahypa 2-3")}>
|
||||
<PassportImage label={t("cardPin.passportFile2", "Pasport (2-3-nji sahypa)")} url={data.passport_file_2} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardPin.passportFile3", "Sahypa 8-9")}>
|
||||
<PassportImage label={t("cardPin.passportFile3", "Pasport (8-9 sahypa)")} url={data.passport_file_3} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardPin.passportFile4", "Sahypa 32")}>
|
||||
<PassportImage label={t("cardPin.passportFile4", "Pasport (32-nji sahypa)")} url={data.passport_file_4} />
|
||||
<InfoRow label={t("cardPin.field.passportSerie", "Pasport seriýasy")} value={data.passportSerie} />
|
||||
<InfoRow label={t("cardPin.field.passportId", "Pasport belgisi")} value={data.passportId} />
|
||||
<InfoRow label={t("cardPin.field.passportOne", "Pasport 1")} value={data.passportOne || "—"} />
|
||||
<InfoRow label={t("cardPin.field.passportTwo", "Pasport 2")} value={data.passportTwo || "—"} />
|
||||
<InfoRow label={t("cardPin.field.passportThree", "Pasport 3")} value={data.passportThree || "—"} />
|
||||
<InfoRow label={t("cardPin.field.passportFour", "Pasport 4")} value={data.passportFour || "—"} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState } 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";
|
||||
@@ -9,12 +8,8 @@ import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import {
|
||||
useCardTransactions,
|
||||
useDeleteCardTransaction,
|
||||
useDownloadCardTransaction,
|
||||
} from "@/features/cardTransactions/hooks/useCardTransactions";
|
||||
import type { CardTransaction } from "@/features/cardTransactions/api/cardTransactionsApi";
|
||||
import { useCardTransactions, useDeleteCardTransaction } from "@/features/cardTransactions/hooks/useCardTransactions";
|
||||
import type { Card } from "@/features/cardTransactions/api/cardTransactionsApi";
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -31,17 +26,16 @@ export default function CardTransactionsPage() {
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
|
||||
const { data, isLoading } = useCardTransactions({ page, per_page: perPage, search });
|
||||
const { data, isLoading } = useCardTransactions({ page, limit: perPage, search });
|
||||
const deleteMutation = useDeleteCardTransaction();
|
||||
const downloadMutation = useDownloadCardTransaction();
|
||||
|
||||
// ── Columns ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const columns: ColumnDef<CardTransaction>[] = [
|
||||
const columns: ColumnDef<Card>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("ID", "ID"),
|
||||
header: t("cardTransaction.col.id", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<button
|
||||
className="text-primary font-medium hover:underline text-left"
|
||||
@@ -50,36 +44,54 @@ export default function CardTransactionsPage() {
|
||||
{row.original.id}
|
||||
</button>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
id: "passport_series",
|
||||
accessorKey: "passport_series",
|
||||
header: t("Passport series", "PASPORT SERIYASY"),
|
||||
cell: ({ row }) => <span>{row.original.passport_series}</span>,
|
||||
id: "name",
|
||||
accessorKey: "name",
|
||||
header: t("cardTransaction.col.name", "Ady"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name}</span>,
|
||||
},
|
||||
{
|
||||
id: "passport_number",
|
||||
accessorKey: "passport_number",
|
||||
header: t("Passport number", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span>{row.original.passport_number}</span>,
|
||||
id: "number",
|
||||
accessorKey: "number",
|
||||
header: t("cardTransaction.col.number", "Kart belgisi"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.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: "type",
|
||||
accessorKey: "type",
|
||||
header: t("cardTransaction.col.type", "Görnüşi"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.type}</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: "expiry",
|
||||
accessorKey: "year",
|
||||
header: t("cardTransaction.col.expiry", "Möhleti"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.month}/{row.original.year}
|
||||
</span>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
{
|
||||
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: "userId",
|
||||
accessorKey: "userId",
|
||||
header: t("cardTransaction.col.userId", "Ulanyjy ID"),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.userId}</span>,
|
||||
size: 110,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("cardTransaction.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.createdAt ? new Date(row.original.createdAt).toLocaleString() : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -87,13 +99,13 @@ export default function CardTransactionsPage() {
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
extraActions={[{ icon: Download, title: t("Download", "Ýükle"), onClick: () => downloadMutation.mutate(row.original.id) }]}
|
||||
onView={() => navigate(`/card-transactions/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/card-transactions/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -108,7 +120,7 @@ export default function CardTransactionsPage() {
|
||||
|
||||
// ── Pagination ────────────────────────────────────────────────────────────────
|
||||
|
||||
const total = data?.total ?? 0;
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
|
||||
const handleDelete = async () => {
|
||||
@@ -121,7 +133,7 @@ export default function CardTransactionsPage() {
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card transactions", "Kart hereketleri")}</h1>
|
||||
<h1 className="text-xl font-semibold text-foreground">{t("Card transactions", "Kartlar")}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 justify-between">
|
||||
@@ -133,7 +145,7 @@ export default function CardTransactionsPage() {
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton label={t("Create card transaction", "Kart herekedi dörediň")} onClick={() => navigate("/card-transactions/create")} />
|
||||
<CreateButton label={t("Create card", "Kart dörediň")} onClick={() => navigate("/card-transactions/create")} />
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
@@ -163,7 +175,7 @@ export default function CardTransactionsPage() {
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cards ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -186,8 +198,8 @@ export default function CardTransactionsPage() {
|
||||
}}
|
||||
title={t("Are you sure?", "Eminsiňizmi?")}
|
||||
description={t(
|
||||
"This action cannot be undone. This will permanently delete the card transaction.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.",
|
||||
"This action cannot be undone. This will permanently delete the card.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart hemişelik öçüriler.",
|
||||
)}
|
||||
onConfirm={handleDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
|
||||
@@ -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,12 +14,8 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
useCardTransaction,
|
||||
useDeleteCardTransaction,
|
||||
useDownloadCardTransaction,
|
||||
} from "@/features/cardTransactions/hooks/useCardTransactions";
|
||||
import { InfoRow } from "@/components/viewPageComponents";
|
||||
import { useCardTransaction, useDeleteCardTransaction } from "@/features/cardTransactions/hooks/useCardTransactions";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -33,7 +29,6 @@ export default function CardTransactionViewPage() {
|
||||
const numericId = Number(id);
|
||||
const { data, isLoading } = useCardTransaction(numericId);
|
||||
const deleteMutation = useDeleteCardTransaction();
|
||||
const downloadMutation = useDownloadCardTransaction();
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(numericId);
|
||||
@@ -45,7 +40,7 @@ export default function CardTransactionViewPage() {
|
||||
<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: 7 }).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" />
|
||||
@@ -57,11 +52,7 @@ export default function CardTransactionViewPage() {
|
||||
}
|
||||
|
||||
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 (
|
||||
@@ -69,18 +60,9 @@ export default function CardTransactionViewPage() {
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("Card transaction detail", "Kart herekedi giňişleýin")}:
|
||||
{t("Card transaction detail", "Kart giňişleýin")}: <span className="text-primary font-mono">{data.number}</span>
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() => downloadMutation.mutate(numericId)}
|
||||
disabled={downloadMutation.isPending}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -97,54 +79,45 @@ export default function CardTransactionViewPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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 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}
|
||||
/>
|
||||
</div>
|
||||
{/* Detail cards */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardTransaction.section.card", "Kart")}>
|
||||
<InfoRow label={t("cardTransaction.col.id", "ID")} value={data.id} />
|
||||
<InfoRow label={t("cardTransaction.col.name", "Ady")} value={data.name} />
|
||||
<InfoRow label={t("cardTransaction.col.type", "Görnüşi")} value={data.type} />
|
||||
<InfoRow label={t("cardTransaction.col.number", "Kart belgisi")} value={data.number} />
|
||||
<InfoRow label={t("cardTransaction.col.expiry", "Möhleti")} value={`${data.month}/${data.year}`} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardTransaction.section.meta", "Belligi")}>
|
||||
<InfoRow label={t("cardTransaction.col.userId", "Ulanyjy ID")} value={data.userId} />
|
||||
<InfoRow
|
||||
label={t("cardTransaction.col.createdAt", "Döredilen wagty")}
|
||||
value={data.createdAt ? new Date(data.createdAt).toLocaleString() : "—"}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("cardTransaction.col.updatedAt", "Täzelenen wagty")}
|
||||
value={data.updatedAt ? new Date(data.updatedAt).toLocaleString() : "—"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* 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. This will permanently delete the card transaction.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart herekedi hemişelik öçüriler.",
|
||||
"This action cannot be undone. This will permanently delete the card.",
|
||||
"Bu amal yzyna gaýtarylmaz. Kart 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,229 +1,302 @@
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { useNavigate, Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CheckCircle2, XCircle, AlertCircle } from "lucide-react";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { DataTableToolbar, type ColumnMeta, type ActiveFilter, type FilterField } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { useCardOrders, useDeleteCardOrder, useProvinces, useBranches } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
import type { CardOrderListItem, CardOrderStatus } from "@/features/orderNewCard/api/orderNewCardApi";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { useCards, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
import type { CardOrder } from "@/features/orderNewCard/api/orderNewCardApi";
|
||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
import { useCardTypes } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
|
||||
const PER_PAGE = 25;
|
||||
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
function OrderNewCardStatusBadge({ status }: { status: CardOrderStatus }) {
|
||||
const PENDING_STATUSES = [
|
||||
"pending",
|
||||
"garaşylýar",
|
||||
"garaşilyar",
|
||||
"garasylýar",
|
||||
"garasilyar",
|
||||
"garasylyar",
|
||||
"kutilyor",
|
||||
"kutiliyor",
|
||||
"waiting",
|
||||
"beklemede",
|
||||
];
|
||||
const APPROVED_STATUSES = [
|
||||
"approved",
|
||||
"tassyklandy",
|
||||
"tassyklanan",
|
||||
"tassyklandy",
|
||||
"tassyklanyldy",
|
||||
"accepted",
|
||||
"confirmed",
|
||||
"success",
|
||||
"completed",
|
||||
"approve",
|
||||
];
|
||||
const REJECTED_STATUSES = [
|
||||
"rejected",
|
||||
"reject",
|
||||
"ret",
|
||||
"ýatyryldy",
|
||||
"yatyryldy",
|
||||
"canceled",
|
||||
"cancelled",
|
||||
"cancelled",
|
||||
"declined",
|
||||
"failed",
|
||||
"error",
|
||||
"reject",
|
||||
"red edildi",
|
||||
];
|
||||
|
||||
function CardOrderStatusBadge({ status }: { status: string }) {
|
||||
const { t } = useTranslation();
|
||||
const STATUS_CONFIG = {
|
||||
PENDING: { label: t("cardOrder.status.pending", "Garaşylýar"), variant: "warning" as StatusBadgeVariant, icon: AlertCircle },
|
||||
APPROVED: { label: t("cardOrder.status.approved", "Tassyklandy"), variant: "success" as StatusBadgeVariant, icon: CheckCircle2 },
|
||||
REJECTED: { label: t("cardOrder.status.rejected", "Ýatyryldy"), variant: "error" as StatusBadgeVariant, icon: XCircle },
|
||||
};
|
||||
const cfg = STATUS_CONFIG[status];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
const key = (status || "").trim().toLowerCase();
|
||||
|
||||
let variant: StatusBadgeVariant = "default";
|
||||
let icon: React.ElementType | undefined;
|
||||
let label = status;
|
||||
|
||||
if (PENDING_STATUSES.includes(key)) {
|
||||
variant = "warning";
|
||||
icon = AlertCircle;
|
||||
label = t("cardOrder.status.pending", "Garaşylýar");
|
||||
} else if (APPROVED_STATUSES.includes(key)) {
|
||||
variant = "success";
|
||||
icon = CheckCircle2;
|
||||
label = t("cardOrder.status.approved", "Tassyklandy");
|
||||
} else if (REJECTED_STATUSES.includes(key)) {
|
||||
variant = "error";
|
||||
icon = XCircle;
|
||||
label = t("cardOrder.status.rejected", "Ýatyryldy");
|
||||
} else {
|
||||
label = t(`cardOrder.status.${status}`, status);
|
||||
}
|
||||
|
||||
return <StatusBadge label={label} variant={variant} icon={icon} />;
|
||||
}
|
||||
|
||||
// ─── Coloured text helper ─────────────────────────────────────────────────────
|
||||
// ─── Filter field IDs ──────────────────────────────────────────────────────────
|
||||
|
||||
function HighlightText({ value, variant }: { value: string; variant: "teal" | "cyan" | "muted" }) {
|
||||
const cls =
|
||||
variant === "teal" ? "text-teal-400 font-semibold" : variant === "cyan" ? "text-cyan-400 font-semibold" : "text-muted-foreground";
|
||||
return <span className={cls}>{value}</span>;
|
||||
}
|
||||
const FILTER_IDS = ["status", "branch_id", "user_id", "card_state_id", "card_type_id", "region"] as const;
|
||||
type FilterId = (typeof FILTER_IDS)[number];
|
||||
|
||||
const SPECIAL_BRANCHES = ["Köpetdag", "Türkmenabat", "Türkmenbaşy", "Seýdi", "Çandybil", "Balkan", "Baş bank"];
|
||||
|
||||
// ─── CardOrdersPage ───────────────────────────────────────────────────────────
|
||||
const INITIAL_FILTERS: ActiveFilter[] = FILTER_IDS.map((fieldId) => ({ fieldId, value: "" }));
|
||||
|
||||
export default function CardOrdersPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteCardOrder();
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const deleteMutation = useDeleteCard();
|
||||
|
||||
// ── Column meta (toolbar toggle) ──────────────────────────────────────────
|
||||
const COLUMN_META = useMemo(
|
||||
() => [
|
||||
{ id: "id", label: t("cardOrder.col.id", "ID") },
|
||||
{ id: "issuanceReasonName", label: t("cardOrder.col.reason", "Sebäp") },
|
||||
{ id: "createdAt", label: t("cardOrder.col.createdAt", "Döredilen wagty") },
|
||||
{ id: "cardTypeName", label: t("cardOrder.col.cardType", "Görnüşi") },
|
||||
{ id: "provinceName", label: t("cardOrder.col.province", "Welaýat") },
|
||||
{ id: "branchName", label: t("cardOrder.col.branch", "Şahamça") },
|
||||
{ id: "fullName", label: t("cardOrder.col.name", "Ady") },
|
||||
{ id: "status", label: t("cardOrder.col.status", "Status") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
const DEFAULT_ORDER = useMemo(() => COLUMN_META.map((c) => c.id), [COLUMN_META]);
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(10);
|
||||
const [perPage, setPerPage] = useState(PER_PAGE);
|
||||
const [search, setSearch] = useState("");
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>(DEFAULT_ORDER);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([
|
||||
{ fieldId: "status", value: "" },
|
||||
{ fieldId: "provinceId", value: "" },
|
||||
{ fieldId: "branchId", value: "" },
|
||||
]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
||||
|
||||
// ── Lookup data ────────────────────────────────────────────────────────────
|
||||
const provinceId = activeFilters.find((f) => f.fieldId === "provinceId")?.value;
|
||||
const { data: provincesData } = useProvinces();
|
||||
const { data: branchesData } = useBranches(provinceId ? Number(provinceId) : undefined);
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const { data: branchesData } = useBranches({ page, limit: 25 });
|
||||
const { data: districtsData } = useDistricts({ page, limit: 25 });
|
||||
const { data: cardTypesData } = useCardTypes({ page, limit: 25 });
|
||||
|
||||
// ── Query params ───────────────────────────────────────────────────────────
|
||||
const queryParams = useMemo(() => {
|
||||
const filterMap = Object.fromEntries(activeFilters.map((f) => [f.fieldId, f.value]));
|
||||
return {
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
search: search || undefined,
|
||||
status: (filterMap.status as CardOrderStatus) || undefined,
|
||||
provinceId: filterMap.provinceId ? Number(filterMap.provinceId) : undefined,
|
||||
branchId: filterMap.branchId ? Number(filterMap.branchId) : undefined,
|
||||
page,
|
||||
perPage,
|
||||
};
|
||||
}, [search, activeFilters, page, perPage]);
|
||||
|
||||
const { data, isLoading } = useCardOrders(queryParams);
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => {
|
||||
const updated = prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f));
|
||||
if (fieldId === "provinceId") {
|
||||
return updated.map((f) => (f.fieldId === "branchId" ? { ...f, value: "" } : f));
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback((id: string) => {
|
||||
setDeleteId(id);
|
||||
}, []);
|
||||
|
||||
const confirmDelete = useCallback(() => {
|
||||
if (!deleteId) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
// ── Columns ────────────────────────────────────────────────────────────────
|
||||
const columns = useMemo<ColumnDef<CardOrderListItem>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: t("cardOrder.col.id", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<Link to={`/order-new-card/${row.original.id}`} className="font-mono text-xs text-primary hover:underline">
|
||||
{row.original.id}
|
||||
</Link>
|
||||
),
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
accessorKey: "issuanceReasonName",
|
||||
header: t("cardOrder.col.reason", "Sebäp"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.issuanceReasonName}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: t("cardOrder.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground whitespace-nowrap">{row.original.createdAt}</span>,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
accessorKey: "cardTypeName",
|
||||
header: t("cardOrder.col.cardType", "Görnüşi"),
|
||||
cell: ({ row }) => (
|
||||
<HighlightText value={row.original.cardTypeName} variant={row.original.cardTypeName === "Altyn Asyr" ? "cyan" : "teal"} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "provinceName",
|
||||
header: t("cardOrder.col.province", "Welaýat"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.provinceName}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "branchName",
|
||||
header: t("cardOrder.col.branch", "Şahamça"),
|
||||
cell: ({ row }) => (
|
||||
<HighlightText value={row.original.branchName} variant={SPECIAL_BRANCHES.includes(row.original.branchName) ? "cyan" : "muted"} />
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "fullName",
|
||||
header: t("cardOrder.col.name", "Ady"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">
|
||||
{row.original.lastName} {row.original.firstName}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("cardOrder.col.status", "Status"),
|
||||
cell: ({ row }) => <OrderNewCardStatusBadge status={row.original.status} />,
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/order-new-card/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/order-new-card/${row.original.id}/edit`)}
|
||||
onDelete={() => handleDelete(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
limit: perPage,
|
||||
status: getFilter("status") || undefined,
|
||||
branch_id: getFilter("branch_id") || undefined,
|
||||
user_id: getFilter("user_id") || undefined,
|
||||
card_state_id: getFilter("card_state_id") || undefined,
|
||||
card_type_id: getFilter("card_type_id") || undefined,
|
||||
region: getFilter("region") || undefined,
|
||||
}),
|
||||
[search, page, perPage, getFilter],
|
||||
);
|
||||
|
||||
const { data, isLoading } = useCards(queryParams);
|
||||
|
||||
const columns: ColumnDef<CardOrder>[] = [
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("cardOrder.col.id", "ID"),
|
||||
cell: ({ row }) => (
|
||||
<Link to={`/order-new-card/${row.original.id}`} className="font-mono text-xs text-primary hover:underline">
|
||||
{row.original.id}
|
||||
</Link>
|
||||
),
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("cardOrder.col.uniqueId", "Sargyt belgisi"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground font-mono">{row.original.uniqueId}</span>,
|
||||
},
|
||||
{
|
||||
id: "customerName",
|
||||
accessorKey: "customerName",
|
||||
header: t("cardOrder.col.customer", "Müşderi"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">
|
||||
{row.original.customerName} {row.original.customerSurname}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("cardOrder.col.phone", "Telefon"),
|
||||
cell: ({ row }) => <span className="font-mono text-sm">{row.original.phone}</span>,
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
accessorKey: "region",
|
||||
header: t("cardOrder.col.region", "Sebit"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.region}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("cardOrder.col.status", "Statusy"),
|
||||
cell: ({ row }) => <CardOrderStatusBadge status={row.original.status} />,
|
||||
},
|
||||
{
|
||||
id: "paid",
|
||||
accessorKey: "paid",
|
||||
header: t("cardOrder.col.paid", "Tölegli"),
|
||||
cell: ({ row }) => (
|
||||
<StatusBadge
|
||||
label={row.original.paid ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
variant={row.original.paid ? "success" : "error"}
|
||||
/>
|
||||
),
|
||||
size: 90,
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: t("cardOrder.col.createdAt", "Döredilen wagty"),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{row.original.createdAt ? new Date(row.original.createdAt).toLocaleString() : "—"}
|
||||
</span>
|
||||
),
|
||||
size: 180,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "",
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<TableActions
|
||||
onView={() => navigate(`/order-new-card/${row.original.id}`)}
|
||||
onEdit={() => navigate(`/order-new-card/${row.original.id}/edit`)}
|
||||
onDelete={() => setDeleteId(row.original.id)}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
),
|
||||
size: 100,
|
||||
},
|
||||
];
|
||||
|
||||
const columnMeta: ColumnMeta[] = columns
|
||||
.filter((c) => c.id !== "actions")
|
||||
.map((c) => ({
|
||||
id: c.id!,
|
||||
label: typeof c.header === "string" ? c.header : c.id!,
|
||||
}));
|
||||
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.ceil(total / perPage);
|
||||
|
||||
// ── Filter fields ──────────────────────────────────────────────────────────
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("cardOrder.col.status", "Status"),
|
||||
label: t("cardOrder.filter.status", "Status"),
|
||||
options: [
|
||||
{ value: "PENDING", label: t("cardOrder.status.pending", "Garaşylýar") },
|
||||
{ value: "APPROVED", label: t("cardOrder.status.approved", "Tassyklandy") },
|
||||
{ value: "REJECTED", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
||||
{ value: "pending", label: t("cardOrder.status.pending", "Garaşylýar") },
|
||||
{ value: "approved", label: t("cardOrder.status.approved", "Tassyklandy") },
|
||||
{ value: "rejected", label: t("cardOrder.status.rejected", "Ýatyryldy") },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "provinceId",
|
||||
label: t("cardOrder.col.province", "Welaýat"),
|
||||
options: provincesData?.map((p) => ({ value: String(p.id), label: p.name })) ?? [],
|
||||
id: "branch_id",
|
||||
label: t("cardOrder.filter.branch", "Şahamça"),
|
||||
options: (branchesData?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "branchId",
|
||||
label: t("cardOrder.col.branch", "Şahamça"),
|
||||
options: branchesData?.map((b) => ({ value: String(b.id), label: b.name })) ?? [],
|
||||
id: "region",
|
||||
label: t("cardOrder.filter.region", "Sebit"),
|
||||
options: (districtsData?.provinces ?? []).map((d) => ({
|
||||
value: d.region?.tm || d.name.tm,
|
||||
label: d.name[lang] || d.name.tm,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "user_id",
|
||||
label: t("cardOrder.filter.userId", "Ulanyjy ID"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: "card_state_id",
|
||||
label: t("cardOrder.filter.cardStateId", "Kart ýagdaýy ID"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: "card_type_id",
|
||||
label: t("cardOrder.filter.cardTypeId", "Kart görnüşi"),
|
||||
options: (cardTypesData?.paymentCards ?? []).map((ct) => ({
|
||||
value: String(ct.id),
|
||||
label: ct.title[lang] || ct.title.tm,
|
||||
})),
|
||||
},
|
||||
],
|
||||
[t, provincesData, branchesData],
|
||||
[t, lang, branchesData, districtsData, cardTypesData],
|
||||
);
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters(INITIAL_FILTERS);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
if (deleteId === null) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
}, [deleteId, deleteMutation]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -239,7 +312,7 @@ export default function CardOrdersPage() {
|
||||
}}
|
||||
placeholder={t("common.search", "Gözlemek")}
|
||||
/>
|
||||
<CreateButton label={t("cardOrder.create", "Kart sargyt dörediň")} onClick={() => navigate("/order-new-card/create")} />
|
||||
<CreateButton label={t("cardOrder.create", "Kart dörediň")} onClick={() => navigate("/order-new-card/create")} />
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
@@ -250,38 +323,38 @@ export default function CardOrdersPage() {
|
||||
setPage(1);
|
||||
}}
|
||||
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||
columns={COLUMN_META}
|
||||
columns={columnMeta}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
hideSearch
|
||||
hideAction
|
||||
perPageOptions={[10, 25, 50, 100]}
|
||||
perPage={perPage}
|
||||
onPerPageChange={(v) => {
|
||||
setPerPage(v);
|
||||
setPage(1);
|
||||
}}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.cardOrders ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
enableRowSelection
|
||||
getRowId={(row) => row.id}
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.totalCount}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
@@ -291,8 +364,9 @@ export default function CardOrdersPage() {
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteId(null);
|
||||
}}
|
||||
title={t("cardOrder.deleteConfirm", "Bu sargyt pozulsynmy?")}
|
||||
onConfirm={confirmDelete}
|
||||
title={t("cardOrder.deleteConfirm", "Bu kart pozulsynmy?")}
|
||||
description={t("cardOrder.deleteDescription", "Bu kart hemişelik pozular. Bu işi yzyna gaýtaryp bolmaz.")}
|
||||
onConfirm={handleDelete}
|
||||
isLoading={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PageSpinner } from '@/components/pageSpinner'
|
||||
import { PageError } from '@/components/pageError'
|
||||
import { CardOrderForm } from '@/features/orderNewCard/components/orderNewCardForm'
|
||||
import { useCardOrderById } from '@/features/orderNewCard/hooks/useOrderNewCard'
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageSpinner } from "@/components/pageSpinner";
|
||||
import { PageError } from "@/components/pageError";
|
||||
import { CardOrderForm } from "@/features/orderNewCard/components/orderNewCardForm";
|
||||
import { useCardById } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
|
||||
export default function CardOrderEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const { t } = useTranslation()
|
||||
const { data: order, isLoading } = useCardOrderById(id ?? '')
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { t } = useTranslation();
|
||||
const { data: card, isLoading } = useCardById(Number(id));
|
||||
|
||||
if (isLoading) return <PageSpinner />
|
||||
if (!order) return <PageError message={t('common.notFound', 'Tapylmady')} />
|
||||
if (isLoading) return <PageSpinner />;
|
||||
if (!card) return <PageError message={t("common.notFound", "Tapylmady")} />;
|
||||
|
||||
return <CardOrderForm mode="edit" initialData={order} />
|
||||
return <CardOrderForm mode="edit" initialData={card} />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Link } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Printer, Download, Trash2, Pencil, AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Printer, Download, Trash2, Pencil } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -14,24 +14,64 @@ import {
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useCardOrderById, useDeleteCardOrder } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
import type { CardOrderStatus } from "@/features/orderNewCard/api/orderNewCardApi";
|
||||
import { BentoGrid, BentoCard, InfoRow, PassportImage } from "@/components/viewPageComponents";
|
||||
import { useCardById, useDeleteCard } from "@/features/orderNewCard/hooks/useOrderNewCard";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { AlertCircle, CheckCircle2, XCircle } from "lucide-react";
|
||||
|
||||
// ─── Status badge ─────────────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_CONFIG: Record<CardOrderStatus, { label: string; variant: StatusBadgeVariant; icon: React.ElementType }> = {
|
||||
PENDING: { label: "Garaşylýar", variant: "warning", icon: AlertCircle },
|
||||
APPROVED: { label: "Tassyklandy", variant: "success", icon: CheckCircle2 },
|
||||
REJECTED: { label: "Ýatyryldy", variant: "error", icon: XCircle },
|
||||
};
|
||||
const PENDING_STATUSES = [
|
||||
"pending",
|
||||
"garaşylýar",
|
||||
"garaşilyar",
|
||||
"garasylýar",
|
||||
"garasilyar",
|
||||
"garasylyar",
|
||||
"kutilyor",
|
||||
"kutiliyor",
|
||||
"waiting",
|
||||
"beklemede",
|
||||
];
|
||||
const APPROVED_STATUSES = [
|
||||
"approved",
|
||||
"tassyklandy",
|
||||
"tassyklanan",
|
||||
"tassyklandy",
|
||||
"tassyklanyldy",
|
||||
"accepted",
|
||||
"confirmed",
|
||||
"success",
|
||||
"completed",
|
||||
"approve",
|
||||
];
|
||||
const REJECTED_STATUSES = [
|
||||
"rejected",
|
||||
"reject",
|
||||
"ret",
|
||||
"ýatyryldy",
|
||||
"yatyryldy",
|
||||
"canceled",
|
||||
"cancelled",
|
||||
"cancelled",
|
||||
"declined",
|
||||
"failed",
|
||||
"error",
|
||||
"reject",
|
||||
"red edildi",
|
||||
];
|
||||
|
||||
function CardOrderStatusBadge({ status }: { status: CardOrderStatus }) {
|
||||
const { t } = useTranslation();
|
||||
const cfg = STATUS_CONFIG[status];
|
||||
if (!cfg) return <span className="text-xs text-muted-foreground">{status}</span>;
|
||||
return <StatusBadge label={t(`cardOrder.status.${status.toLowerCase()}`)} variant={cfg.variant} icon={cfg.icon} />;
|
||||
function statusConfig(status: string): { label: string; variant: StatusBadgeVariant; icon?: React.ElementType } {
|
||||
const key = status.trim().toLowerCase();
|
||||
if (PENDING_STATUSES.includes(key)) return { label: "Garaşylýar", variant: "warning", icon: AlertCircle };
|
||||
if (APPROVED_STATUSES.includes(key)) return { label: "Tassyklandy", variant: "success", icon: CheckCircle2 };
|
||||
if (REJECTED_STATUSES.includes(key)) return { label: "Ýatyryldy", variant: "error", icon: XCircle };
|
||||
return { label: status, variant: "default" };
|
||||
}
|
||||
|
||||
function CardOrderStatusBadge({ status }: { status: string }) {
|
||||
const cfg = statusConfig(status);
|
||||
return <StatusBadge label={cfg.label} variant={cfg.variant} icon={cfg.icon} />;
|
||||
}
|
||||
|
||||
// ─── Skeleton ─────────────────────────────────────────────────────────────────
|
||||
@@ -63,24 +103,26 @@ export default function CardOrderDetailPage() {
|
||||
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const { data: order, isLoading } = useCardOrderById(id ?? "");
|
||||
const deleteMutation = useDeleteCardOrder();
|
||||
const { data: order, isLoading } = useCardById(Number(id));
|
||||
const deleteMutation = useDeleteCard();
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!id) return;
|
||||
await deleteMutation.mutateAsync(id);
|
||||
await deleteMutation.mutateAsync(Number(id));
|
||||
navigate("/order-new-card");
|
||||
};
|
||||
|
||||
if (isLoading) return <DetailSkeleton />;
|
||||
if (!order) return <p className="text-muted-foreground text-sm">{t("common.notFound", "Tapylmady")}</p>;
|
||||
|
||||
const fmtDate = (v?: string | null) => (v ? new Date(v).toLocaleDateString() : "—");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* ── Page header ──────────────────────────────────────────────────── */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}: <span className="text-primary font-mono">{order.id}</span>
|
||||
{t("cardOrder.detailTitle", "Kart sargyt giriş üçin")}: <span className="text-primary font-mono">{order.uniqueId}</span>
|
||||
</h1>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
@@ -112,65 +154,76 @@ export default function CardOrderDetailPage() {
|
||||
<BentoGrid cols={3}>
|
||||
<BentoCard title={t("cardOrder.section.meta", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={order.id} />
|
||||
<InfoRow label={t("cardOrder.field.createdAt", "Döredilen wagty")} value={order.createdAt} />
|
||||
<InfoRow label={t("cardOrder.field.uniqueId", "Sargyt belgisi")} value={order.uniqueId} />
|
||||
<InfoRow label={t("cardOrder.field.status", "Status")}>
|
||||
<CardOrderStatusBadge status={order.status} />
|
||||
</InfoRow>
|
||||
<InfoRow label={t("cardOrder.field.isPaid", "Tölenen")}>
|
||||
<InfoRow label={t("cardOrder.field.paid", "Tölenen")}>
|
||||
<span
|
||||
className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold ${order.isPaid ? "bg-emerald-500/15 text-emerald-400" : "bg-red-500/15 text-red-400"}`}
|
||||
className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold ${order.paid ? "bg-emerald-500/15 text-emerald-400" : "bg-red-500/15 text-red-400"}`}
|
||||
>
|
||||
{order.isPaid ? "✓" : "✕"}
|
||||
{order.paid ? "✓" : "✕"}
|
||||
</span>
|
||||
</InfoRow>
|
||||
<InfoRow label={t("cardOrder.field.note", "Bellik")} value={order.note ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.createdBy", "Sargyt eden")} value={order.createdBy} isLink />
|
||||
<InfoRow label={t("cardOrder.field.notes", "Bellik")} value={order.notes ?? undefined} />
|
||||
<InfoRow
|
||||
label={t("cardOrder.field.createdAt", "Döredilen wagty")}
|
||||
value={order.createdAt ? new Date(order.createdAt).toLocaleString() : "—"}
|
||||
/>
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardOrder.section.card", "Kart")}>
|
||||
<InfoRow label={t("cardOrder.field.issuanceReason", "Kartyň çykarylmagynyň sebäbi")} value={order.issuanceReasonName} isLink />
|
||||
<InfoRow label={t("cardOrder.field.cardType", "Kart görnüşi")} value={order.cardTypeName} />
|
||||
<InfoRow label={t("cardOrder.field.cardTypeId", "Kart görnüşi ID")} value={order.cardTypeId} />
|
||||
<InfoRow label={t("cardOrder.field.cardStateId", "Kart ýagdaýy ID")} value={order.cardStateId} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardOrder.section.location", "Lokasiýa")}>
|
||||
<InfoRow label={t("cardOrder.field.province", "Welaýat")} value={order.provinceName} />
|
||||
<InfoRow label={t("cardOrder.field.branch", "Şahamça")} value={order.branchName} />
|
||||
<InfoRow label={t("cardOrder.field.region", "Sebit")} value={order.region} />
|
||||
<InfoRow label={t("cardOrder.field.branchId", "Şahamça ID")} value={order.branchId} />
|
||||
<InfoRow label={t("cardOrder.field.userId", "Ulanyjy ID")} value={order.userId} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Şahsy maglumatlar (full width — many fields) ─────────── */}
|
||||
{/* ── Row 2: Şahsy maglumatlar + Kontakt ──────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardOrder.section.personal", "Şahsy maglumatlar")}>
|
||||
<InfoRow
|
||||
label={t("cardOrder.field.fullName", "Doly ady")}
|
||||
value={[order.lastName, order.firstName, order.middleName].filter(Boolean).join(" ")}
|
||||
value={[order.customerSurname, order.customerName, order.customerPatronicName].filter(Boolean).join(" ")}
|
||||
/>
|
||||
<InfoRow label={t("cardOrder.field.birthDate", "Doglan güni")} value={order.birthDate} />
|
||||
<InfoRow label={t("cardOrder.field.bornAt", "Doglan güni")} value={fmtDate(order.bornAt)} />
|
||||
<InfoRow label={t("cardOrder.field.bornPlace", "Doglan ýeri")} value={order.bornPlace ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.oldSurname", "Köne familiýa")} value={order.oldSurname ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.citizenship", "Raýatlyk")} value={order.citizenship} />
|
||||
<InfoRow label={t("cardOrder.field.registeredAddress", "Ýazgy edilen salgy")} value={order.registeredAddress} />
|
||||
<InfoRow label={t("cardOrder.field.currentAddress", "Häzirki ýaşaýyş ýeri")} value={order.currentAddress} />
|
||||
<InfoRow label={t("cardOrder.field.workplace", "Işleýän ýeri we wezipesi")} value={order.workplace} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("cardOrder.section.contacts", "Kontakt")}>
|
||||
<InfoRow label={t("cardOrder.field.phone", "Telefon")} value={order.phone} />
|
||||
<InfoRow label={t("cardOrder.field.phoneExtra", "Telefon goşmaça")} value={order.phoneExtra ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.phoneAdditional", "Telefon goşmaça")} value={order.phoneAdditional ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.realAddress", "Hakyky ýaşaýyş ýeri")} value={order.realAddress ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.jobLocation", "Işleýän ýeri")} value={order.jobLocation ?? undefined} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 3: Passport images ───────────────────────────────────────── */}
|
||||
<BentoGrid cols={4}>
|
||||
<BentoCard title={t("cardOrder.field.passportPage1", "Sahypa 1")}>
|
||||
<PassportImage label={t("cardOrder.field.passportPage1", "Pasport (sahypa 1)")} url={order.passportFiles.page1} />
|
||||
{/* ── Row 3: Pasport maglumatlary ─────────────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("cardOrder.section.passport", "Pasport")}>
|
||||
<InfoRow label={t("cardOrder.field.passportSerie", "Pasport seriýasy")} value={order.passportSerie} />
|
||||
<InfoRow label={t("cardOrder.field.passportId", "Pasport belgisi")} value={order.passportId} />
|
||||
<InfoRow label={t("cardOrder.field.passportGivenAt", "Berlen senesi")} value={fmtDate(order.passportGivenAt)} />
|
||||
<InfoRow label={t("cardOrder.field.passportGivenBy", "Beren edara")} value={order.passportGivenBy ?? undefined} />
|
||||
<InfoRow label={t("cardOrder.field.passportAddress", "Pasport salgysy")} value={order.passportAddress ?? undefined} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardOrder.field.passportPage23", "Sahypa 2-3")}>
|
||||
<PassportImage label={t("cardOrder.field.passportPage23", "Pasport (2-3-nji sahypa)")} url={order.passportFiles.page23} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardOrder.field.passportPage89", "Sahypa 8-9")}>
|
||||
<PassportImage label={t("cardOrder.field.passportPage89", "Pasport (8-9 sahypa)")} url={order.passportFiles.page89} />
|
||||
</BentoCard>
|
||||
<BentoCard title={t("cardOrder.field.passportPage32", "Sahypa 32")}>
|
||||
<PassportImage label={t("cardOrder.field.passportPage32", "Pasport (32-nji sahypa)")} url={order.passportFiles.page32} />
|
||||
|
||||
<BentoCard title={t("cardOrder.section.passportParts", "Pasport bölekleri")}>
|
||||
<InfoRow label={t("cardOrder.field.passportOne", "Pasport 1")} value={order.passportOne || "—"} />
|
||||
<InfoRow label={t("cardOrder.field.passportTwo", "Pasport 2")} value={order.passportTwo || "—"} />
|
||||
<InfoRow label={t("cardOrder.field.passportThree", "Pasport 3")} value={order.passportThree || "—"} />
|
||||
<InfoRow label={t("cardOrder.field.passportFour", "Pasport 4")} value={order.passportFour || "—"} />
|
||||
<InfoRow
|
||||
label={t("cardOrder.field.updatedAt", "Täzelenen wagty")}
|
||||
value={order.updatedAt ? new Date(order.updatedAt).toLocaleString() : "—"}
|
||||
/>
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
|
||||
@@ -9,13 +9,31 @@ import { DataTableToolbar, type ActiveFilter, type FilterField } from "@/compone
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { useLoanPaidOffLetters, useDeleteLoanPaidOffLetter } from "@/features/loanPaidOffLetters/hooks/useLoanPaidOffLetters";
|
||||
import type { LoanPaidOffLetter } from "@/features/loanPaidOffLetters/api/loanPaidOffLettersApi";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { useBranches } from "@/features/branches/hooks/useBranches";
|
||||
import { useDistricts } from "@/features/districts/hooks/useDistricts";
|
||||
|
||||
// ─── Column IDs ────────────────────────────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "passportSeries", "passportNumber", "loanAccount", "issuedAt"] as const;
|
||||
const COLUMN_IDS = ["id", "uniqueId", "customerName", "phone", "status"] as const;
|
||||
|
||||
// ─── Filter field IDs ──────────────────────────────────────────────────────────
|
||||
|
||||
const FILTER_IDS = ["status", "passport_id", "branch_id", "region"] as const;
|
||||
type FilterId = (typeof FILTER_IDS)[number];
|
||||
|
||||
const INITIAL_FILTERS: ActiveFilter[] = FILTER_IDS.map((fieldId) => ({ fieldId, value: "" }));
|
||||
|
||||
// ─── Status badge helpers ──────────────────────────────────────────────────────
|
||||
|
||||
const STATUS_VARIANT: Record<string, StatusBadgeVariant> = {
|
||||
pending: "warning",
|
||||
approved: "success",
|
||||
rejected: "error",
|
||||
};
|
||||
|
||||
// ─── Empty state component ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -24,7 +42,6 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 gap-5">
|
||||
{/* Grid icon matching screenshot */}
|
||||
<div className="text-muted-foreground/40">
|
||||
<TableProperties size={64} strokeWidth={1} />
|
||||
</div>
|
||||
@@ -44,25 +61,82 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
|
||||
// ─── Page Component ────────────────────────────────────────────────────────────
|
||||
|
||||
export default function LoanPaidOffLettersPage() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const deleteMutation = useDeleteLoanPaidOffLetter();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([...COLUMN_IDS]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([]);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>(INITIAL_FILTERS);
|
||||
|
||||
// ── Dropdown data ──────────────────────────────────────────────────────────
|
||||
const { data: branchesData } = useBranches({ page, limit: 25 });
|
||||
const { data: districtsData } = useDistricts({ page, limit: 25 });
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const queryParams = useMemo(() => ({ search: search || undefined, page, perPage }), [search, page, perPage]);
|
||||
const getFilter = useCallback((id: FilterId) => activeFilters.find((f) => f.fieldId === id)?.value ?? "", [activeFilters]);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
search: search || undefined,
|
||||
page,
|
||||
limit: perPage,
|
||||
passport_id: getFilter("passport_id") || undefined,
|
||||
status: getFilter("status") || undefined,
|
||||
branch_id: getFilter("branch_id") || undefined,
|
||||
region: getFilter("region") || undefined,
|
||||
}),
|
||||
[search, page, perPage, getFilter],
|
||||
);
|
||||
|
||||
const { data, isLoading } = useLoanPaidOffLetters(queryParams);
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
const isEmpty = !isLoading && (data?.data?.length ?? 0) === 0;
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
const isEmpty = !isLoading && (data?.loanPaidLetters?.length ?? 0) === 0;
|
||||
|
||||
// ── Filter fields ──────────────────────────────────────────────────────────
|
||||
const filterFields = useMemo<FilterField[]>(
|
||||
() => [
|
||||
{
|
||||
id: "status",
|
||||
label: t("loanPaidOffLetters.filters.status", "Status"),
|
||||
options: [
|
||||
{ value: "pending", label: t("loanPaidOffLetters.status.pending", "Pending") },
|
||||
{ value: "approved", label: t("loanPaidOffLetters.status.approved", "Approved") },
|
||||
{ value: "rejected", label: t("loanPaidOffLetters.status.rejected", "Rejected") },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "passport_id",
|
||||
label: t("loanPaidOffLetters.filters.passportId", "Pasport belgisi"),
|
||||
type: "text",
|
||||
},
|
||||
{
|
||||
id: "branch_id",
|
||||
label: t("loanPaidOffLetters.filters.branchId", "Şahamça"),
|
||||
options: (branchesData?.branches ?? []).map((b) => ({
|
||||
value: String(b.id),
|
||||
label: b.name[lang] || b.name.tm,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "region",
|
||||
label: t("loanPaidOffLetters.filters.region", "Sebit"),
|
||||
options: (districtsData?.provinces ?? []).map((d) => ({
|
||||
value: d.region?.tm || d.name.tm,
|
||||
label: d.name[lang] || d.name.tm,
|
||||
})),
|
||||
},
|
||||
],
|
||||
[t, lang, branchesData, districtsData],
|
||||
);
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
@@ -71,7 +145,7 @@ export default function LoanPaidOffLettersPage() {
|
||||
}, []);
|
||||
|
||||
const handleFilterReset = useCallback(() => {
|
||||
setActiveFilters((prev) => prev.map((f) => ({ ...f, value: "" })));
|
||||
setActiveFilters(INITIAL_FILTERS);
|
||||
setPage(1);
|
||||
}, []);
|
||||
|
||||
@@ -100,31 +174,37 @@ export default function LoanPaidOffLettersPage() {
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
id: "passportSeries",
|
||||
accessorKey: "passportSeries",
|
||||
header: t("loanPaidOffLetters.columns.passportSeries", "PASPORT SERIÝASY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.passportSeries}</span>,
|
||||
size: 160,
|
||||
id: "uniqueId",
|
||||
accessorKey: "uniqueId",
|
||||
header: t("loanPaidOffLetters.columns.uniqueId", "UNIKAL ID"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.uniqueId}</span>,
|
||||
size: 150,
|
||||
},
|
||||
{
|
||||
id: "passportNumber",
|
||||
accessorKey: "passportNumber",
|
||||
header: t("loanPaidOffLetters.columns.passportNumber", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.passportNumber}</span>,
|
||||
size: 140,
|
||||
id: "customerName",
|
||||
header: t("loanPaidOffLetters.columns.customerName", "MÜŞDERI"),
|
||||
accessorFn: (row) => `${row.customerSurname} ${row.customerName}`,
|
||||
cell: ({ row }) => (
|
||||
<span className="text-sm text-foreground">{`${row.original.customerSurname} ${row.original.customerName}`}</span>
|
||||
),
|
||||
size: 200,
|
||||
},
|
||||
{
|
||||
id: "loanAccount",
|
||||
accessorKey: "loanAccount",
|
||||
header: t("loanPaidOffLetters.columns.loanAccount", "KARZ HASABY"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.loanAccount}</span>,
|
||||
id: "phone",
|
||||
accessorKey: "phone",
|
||||
header: t("loanPaidOffLetters.columns.phone", "TELEFON"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.phone}</span>,
|
||||
size: 150,
|
||||
},
|
||||
{
|
||||
id: "issuedAt",
|
||||
accessorKey: "issuedAt",
|
||||
header: t("loanPaidOffLetters.columns.issuedAt", "BERLEN WAGTY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground whitespace-nowrap">{row.original.issuedAt}</span>,
|
||||
size: 160,
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: t("loanPaidOffLetters.columns.status", "STATUS"),
|
||||
cell: ({ row }) => {
|
||||
const status = row.original.status;
|
||||
return <StatusBadge label={t(`loanPaidOffLetters.status.${status}`, status)} variant={STATUS_VARIANT[status] ?? "default"} />;
|
||||
},
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -141,7 +221,7 @@ export default function LoanPaidOffLettersPage() {
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
[t, handleDelete, deleteMutation.isPending],
|
||||
[t, navigate, handleDelete, deleteMutation.isPending],
|
||||
);
|
||||
|
||||
// ── Toggleable columns meta ────────────────────────────────────────────────
|
||||
@@ -154,8 +234,6 @@ export default function LoanPaidOffLettersPage() {
|
||||
[t],
|
||||
);
|
||||
|
||||
const filterFields = useMemo<FilterField[]>(() => [], []);
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -181,8 +259,6 @@ export default function LoanPaidOffLettersPage() {
|
||||
|
||||
{/* Table Card */}
|
||||
<div className="bg-card border border-border rounded-xl p-4">
|
||||
{/* Toolbar: column toggle + filter (right side only, matches screenshot) */}
|
||||
|
||||
<DataTableToolbar
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => {
|
||||
@@ -215,7 +291,7 @@ export default function LoanPaidOffLettersPage() {
|
||||
) : (
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.loanPaidLetters ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -225,7 +301,7 @@ export default function LoanPaidOffLettersPage() {
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={data?.total}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -2,21 +2,36 @@ import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import {
|
||||
useLoanPaidOffLetterById,
|
||||
useDeleteLoanPaidOffLetter,
|
||||
} from "@/features/loanPaidOffLetters/hooks/useLoanPaidOffLetters";
|
||||
import { useLoanPaidOffLetterById, useDeleteLoanPaidOffLetter } from "@/features/loanPaidOffLetters/hooks/useLoanPaidOffLetters";
|
||||
import type { StatusBadgeVariant } from "@/components/ui/statusBadge";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { InfoRow, Section } from "@/components/viewPageComponents";
|
||||
import { BentoGrid, BentoCard, InfoRow } from "@/components/viewPageComponents";
|
||||
import { ConfirmDialog } from "@/components/confirmDialog";
|
||||
|
||||
const STATUS_VARIANT: Record<string, StatusBadgeVariant> = {
|
||||
pending: "warning",
|
||||
approved: "success",
|
||||
rejected: "error",
|
||||
};
|
||||
|
||||
function formatDate(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
return value.slice(0, 10);
|
||||
}
|
||||
|
||||
function LoanPaidOffLetterViewSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Skeleton className="h-7 w-64" />
|
||||
<div className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3">
|
||||
{[...Array(5)].map((_, j) => (
|
||||
<Skeleton key={j} className="h-4 w-full" />
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{[...Array(4)].map((_, i) => (
|
||||
<div key={i} className="bg-card border border-border rounded-xl p-4 flex flex-col gap-3">
|
||||
<Skeleton className="h-3 w-24 mb-1" />
|
||||
{[...Array(4)].map((_, j) => (
|
||||
<Skeleton key={j} className="h-4 w-full" />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -41,19 +56,17 @@ export default function LoanPaidOffLettersViewPage() {
|
||||
if (isLoading) return <LoanPaidOffLetterViewSkeleton />;
|
||||
|
||||
if (!record) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
|
||||
{t("common.notFound", "Tapylmady")}
|
||||
</div>
|
||||
);
|
||||
return <div className="flex items-center justify-center h-64 text-muted-foreground text-sm">{t("common.notFound", "Tapylmady")}</div>;
|
||||
}
|
||||
|
||||
const fullName = [record.customerSurname, record.customerName, record.customerPatronicName].filter(Boolean).join(" ");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* ── Page header ──────────────────────────────────────────────────── */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("loanPaidOffLetters.view.title", "Güwanama maglumaty")}:{" "}
|
||||
{record.id}
|
||||
{t("loanPaidOffLetters.view.title", "Güwanama maglumaty")}: {record.uniqueId}
|
||||
</h1>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
@@ -74,25 +87,62 @@ export default function LoanPaidOffLettersViewPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Section title={t("loanPaidOffLetters.sections.info", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={String(record.id)} />
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.columns.passportSeries", "Pasport seriýasy")}
|
||||
value={record.passportSeries}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.columns.passportNumber", "Pasport belgisi")}
|
||||
value={record.passportNumber}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.columns.loanAccount", "Karz hasaby")}
|
||||
value={record.loanAccount}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.columns.issuedAt", "Berlen wagty")}
|
||||
value={record.issuedAt}
|
||||
/>
|
||||
</Section>
|
||||
{/* ── Row 1: Esasy maglumatlar + Müşderi maglumatlary ───────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("loanPaidOffLetters.sections.info", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={String(record.id)} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.uniqueId", "Unikal ID")} value={record.uniqueId || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.status", "Status")}>
|
||||
<StatusBadge
|
||||
label={t(`loanPaidOffLetters.status.${record.status}`, record.status)}
|
||||
variant={STATUS_VARIANT[record.status] ?? "default"}
|
||||
/>
|
||||
</InfoRow>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.createdAt", "Döredilen wagty")} value={formatDate(record.createdAt)} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("loanPaidOffLetters.sections.customer", "Müşderi maglumatlary")}>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.customerName", "Ady")} value={fullName || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.bornAt", "Doglan senesi")} value={formatDate(record.bornAt)} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.phone", "Telefon")} value={record.phone || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.passportSerie", "Pasport seriýasy")} value={record.passportSerie || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.passportId", "Pasport belgisi")} value={record.passportId || "—"} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
{/* ── Row 2: Karz maglumatlary + Goşmaça ───────────────────────────── */}
|
||||
<BentoGrid cols={2}>
|
||||
<BentoCard title={t("loanPaidOffLetters.sections.loan", "Karz maglumatlary")}>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.loanContractNumber", "Karz şertnamasy belgisi")}
|
||||
value={record.loanContractNumber || "—"}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.loanContractDate", "Karz şertnamasy senesi")}
|
||||
value={formatDate(record.loanContractDate)}
|
||||
/>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanAmount", "Karz möçberi")} value={record.loanAmount || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanReason", "Karz sebäbi")} value={record.loanReason || "—"} />
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.loanFile", "Faýl")} value={record.loanFile || "—"} />
|
||||
</BentoCard>
|
||||
|
||||
<BentoCard title={t("loanPaidOffLetters.sections.additional", "Goşmaça")}>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.region", "Sebit")} value={record.region || "—"} />
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.branchId", "Şahamça ID")}
|
||||
value={record.branchId != null ? String(record.branchId) : "—"}
|
||||
isLink={Boolean(record.branchId)}
|
||||
href={record.branchId ? `/settings/location/branches/${record.branchId}` : undefined}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanPaidOffLetters.fields.userId", "Ulanyjy ID")}
|
||||
value={record.userId != null ? String(record.userId) : "—"}
|
||||
isLink={Boolean(record.userId)}
|
||||
href={record.userId ? `/all-users/${record.userId}` : undefined}
|
||||
/>
|
||||
<InfoRow label={t("loanPaidOffLetters.fields.notes", "Bellikler")} value={record.notes || "—"} />
|
||||
</BentoCard>
|
||||
</BentoGrid>
|
||||
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
|
||||
@@ -15,7 +15,7 @@ import { DeleteDialog } from "@/components/deleteDialog";
|
||||
|
||||
// ─── Column IDs ────────────────────────────────────────────────────────────────
|
||||
|
||||
const COLUMN_IDS = ["id", "passportSeries", "passportNumber", "loanAccount"] as const;
|
||||
const COLUMN_IDS = ["id", "userId", "passportSerie", "passportId", "accountNumber"] as const;
|
||||
|
||||
// ─── Page Component ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -34,10 +34,10 @@ export default function LoanRemainingPage() {
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([]);
|
||||
|
||||
// ── Query ──────────────────────────────────────────────────────────────────
|
||||
const queryParams = useMemo(() => ({ search: search || undefined, page, perPage }), [search, page, perPage]);
|
||||
const queryParams = useMemo(() => ({ passport_id: search || undefined, page, limit: perPage }), [search, page, perPage]);
|
||||
|
||||
const { data, isLoading } = useLoanRemaining(queryParams);
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
const totalPages = data ? Math.ceil(data.count / perPage) : 1;
|
||||
|
||||
// ── Handlers ───────────────────────────────────────────────────────────────
|
||||
const handleFilterChange = useCallback((fieldId: string, value: string) => {
|
||||
@@ -71,24 +71,31 @@ export default function LoanRemainingPage() {
|
||||
size: 80,
|
||||
},
|
||||
{
|
||||
id: "passportSeries",
|
||||
accessorKey: "passportSeries",
|
||||
header: t("loanRemaining.columns.passportSeries", "PASPORT SERIÝASY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.passportSeries}</span>,
|
||||
id: "userId",
|
||||
accessorKey: "userId",
|
||||
header: t("loanRemaining.columns.userId", "ULANYJY ID"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.userId}</span>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
id: "passportSerie",
|
||||
accessorKey: "passportSerie",
|
||||
header: t("loanRemaining.columns.passportSerie", "PASPORT SERIÝASY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.passportSerie}</span>,
|
||||
size: 160,
|
||||
},
|
||||
{
|
||||
id: "passportNumber",
|
||||
accessorKey: "passportNumber",
|
||||
header: t("loanRemaining.columns.passportNumber", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.passportNumber}</span>,
|
||||
id: "passportId",
|
||||
accessorKey: "passportId",
|
||||
header: t("loanRemaining.columns.passportId", "PASPORT BELGISI"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.passportId}</span>,
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: "loanAccount",
|
||||
accessorKey: "loanAccount",
|
||||
header: t("loanRemaining.columns.loanAccount", "KARZ HASABY"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.loanAccount}</span>,
|
||||
id: "accountNumber",
|
||||
accessorKey: "accountNumber",
|
||||
header: t("loanRemaining.columns.accountNumber", "KARZ HASABY"),
|
||||
cell: ({ row }) => <span className="text-sm font-mono text-foreground">{row.original.accountNumber}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -166,7 +173,7 @@ export default function LoanRemainingPage() {
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.loans ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -176,7 +183,7 @@ export default function LoanRemainingPage() {
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={data?.total}
|
||||
totalCount={data?.count}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,10 +2,7 @@ import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Trash2, Pencil } from "lucide-react";
|
||||
import {
|
||||
useLoanRemainingById,
|
||||
useDeleteLoanRemaining,
|
||||
} from "@/features/loanRemaining/hooks/useLoanRemaining";
|
||||
import { useLoanRemainingById, useDeleteLoanRemaining } from "@/features/loanRemaining/hooks/useLoanRemaining";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { InfoRow, Section } from "@/components/viewPageComponents";
|
||||
import { ConfirmDialog } from "@/components/confirmDialog";
|
||||
@@ -49,11 +46,7 @@ export default function LoanRemainingViewPage() {
|
||||
if (isLoading) return <LoanRemainingViewSkeleton />;
|
||||
|
||||
if (!record) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64 text-muted-foreground text-sm">
|
||||
{t("common.notFound", "Tapylmady")}
|
||||
</div>
|
||||
);
|
||||
return <div className="flex items-center justify-center h-64 text-muted-foreground text-sm">{t("common.notFound", "Tapylmady")}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -61,8 +54,7 @@ export default function LoanRemainingViewPage() {
|
||||
{/* Page Header */}
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t("loanRemaining.view.title", "Karz galyndysy maglumaty")}:{" "}
|
||||
{record.id}
|
||||
{t("loanRemaining.view.title", "Karz galyndysy maglumaty")}: {record.id}
|
||||
</h1>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
@@ -86,18 +78,10 @@ export default function LoanRemainingViewPage() {
|
||||
{/* ── Basic Info ─────────────────────────────────────────────────────── */}
|
||||
<Section title={t("loanRemaining.sections.info", "Esasy maglumatlar")}>
|
||||
<InfoRow label={t("common.id", "ID")} value={String(record.id)} />
|
||||
<InfoRow
|
||||
label={t("loanRemaining.columns.passportSeries", "Pasport seriýasy")}
|
||||
value={record.passportSeries}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanRemaining.columns.passportNumber", "Pasport belgisi")}
|
||||
value={record.passportNumber}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t("loanRemaining.columns.loanAccount", "Karz hasaby")}
|
||||
value={record.loanAccount}
|
||||
/>
|
||||
<InfoRow label={t("loanRemaining.columns.userId", "Ulanyjy ID")} value={String(record.userId)} />
|
||||
<InfoRow label={t("loanRemaining.columns.passportSerie", "Pasport seriýasy")} value={record.passportSerie} />
|
||||
<InfoRow label={t("loanRemaining.columns.passportId", "Pasport belgisi")} value={record.passportId} />
|
||||
<InfoRow label={t("loanRemaining.columns.accountNumber", "Karz hasaby")} value={record.accountNumber} />
|
||||
</Section>
|
||||
|
||||
<ConfirmDialog
|
||||
|
||||
@@ -68,17 +68,10 @@ interface FormInputProps extends Omit<React.ComponentProps<typeof Input>, "onCha
|
||||
onChange: (val: string) => void;
|
||||
}
|
||||
|
||||
function FormInput({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
...props
|
||||
}: FormInputProps) {
|
||||
function FormInput({ label, value, onChange, ...props }: FormInputProps) {
|
||||
return (
|
||||
<div className="mb-4">
|
||||
<label className="block text-[13px] font-medium text-foreground mb-1.5">
|
||||
{label}
|
||||
</label>
|
||||
<label className="block text-[13px] font-medium text-foreground mb-1.5">{label}</label>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
@@ -104,7 +97,7 @@ export default function AuthPage() {
|
||||
toast.error(t("Write a correct data please", "Please enter valid data"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
loginMutation.mutate({ email: username, password });
|
||||
};
|
||||
|
||||
@@ -122,34 +115,34 @@ 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]">
|
||||
{view === "login" && (
|
||||
<>
|
||||
<h2 className="text-[22px] font-normal text-foreground text-center mb-2 tracking-wide uppercase">
|
||||
{t("Online panel", "ONLAÝN KABULHANA")}
|
||||
</h2>
|
||||
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||
{view === "login" && (
|
||||
<>
|
||||
<h2 className="text-[22px] font-normal text-foreground text-center mb-2 tracking-wide uppercase">
|
||||
{t("Online panel", "ONLAÝN KABULHANA")}
|
||||
</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"
|
||||
/>
|
||||
<FormInput
|
||||
label={t("Password")}
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={setPassword}
|
||||
/>
|
||||
<FormInput
|
||||
label={t("Phone or username", "Telefon ýada ulanyjy ady")}
|
||||
value={username}
|
||||
onChange={setUsername}
|
||||
placeholder="65999990 ýada ulanyjy_ady"
|
||||
/>
|
||||
<FormInput
|
||||
label={t("Password")}
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={setPassword}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleLogin();
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="text-right mb-6 -mt-2">
|
||||
<span
|
||||
onClick={() => setView("reset-password")}
|
||||
className="text-[13px] text-primary cursor-pointer hover:underline"
|
||||
>
|
||||
{t("Forgot your password?")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-right mb-6 -mt-2">
|
||||
<span onClick={() => setView("reset-password")} className="text-[13px] text-primary cursor-pointer hover:underline">
|
||||
{t("Forgot your password?")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<Button onClick={handleLogin} disabled={loginMutation.isPending} className="h-11">
|
||||
@@ -160,91 +153,67 @@ 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>
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{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" />
|
||||
{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={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} />
|
||||
|
||||
<div className="flex flex-col gap-3 mt-4">
|
||||
<Button onClick={handleOtherSubmit} className="h-11">
|
||||
{t("Register")}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setView("login")} className="h-11">
|
||||
{t("Go to login page")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 mt-4">
|
||||
<Button onClick={handleOtherSubmit} className="h-11">
|
||||
{t("Register")}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setView("login")} 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>
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === "reset-password" && (
|
||||
<>
|
||||
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">
|
||||
{t("Enter your username to continue")}
|
||||
</h2>
|
||||
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||
{view === "reset-password" && (
|
||||
<>
|
||||
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">
|
||||
{t("Enter your username to continue")}
|
||||
</h2>
|
||||
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||
|
||||
<FormInput
|
||||
label={t("Username")}
|
||||
value={username}
|
||||
onChange={setUsername}
|
||||
/>
|
||||
<FormInput label={t("Username")} value={username} onChange={setUsername} />
|
||||
|
||||
<div className="mt-4 flex flex-col gap-3">
|
||||
<Button onClick={handleOtherSubmit} className="h-11">
|
||||
{t("Submit")}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setView("login")} className="h-11">
|
||||
{t("Go to login page")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-4 flex flex-col gap-3">
|
||||
<Button onClick={handleOtherSubmit} className="h-11">
|
||||
{t("Submit")}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setView("login")} 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>
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,35 +2,37 @@ import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ColumnDef, VisibilityState } from "@tanstack/react-table";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
import { DataTable } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
import { TableSearchInput } from "@/components/tableSearch";
|
||||
import { CreateButton } from "@/components/createButton";
|
||||
import { TableActions } from "@/components/tableActions";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import type { FilterField, ActiveFilter } from "@/components/dataTableToolbar";
|
||||
import { useCardTypes, useDeleteCardType } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import { useCardTypes, useDeleteCardType, useUpdateCardTypeActive } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
import type { CardType } from "@/features/cardTypes/api/cardTypesApi";
|
||||
|
||||
export function CardTypesListPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const lang = (i18n.language?.slice(0, 2) ?? "tk") as "tk" | "ru" | "en";
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(25);
|
||||
const [search, setSearch] = useState("");
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([{ fieldId: "isActive", value: "" }]);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>(["id", "name", "value", "description", "isActive", "actions"]);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>(["id", "name", "price", "notes", "isActive", "actions"]);
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const deleteMutation = useDeleteCardType();
|
||||
const activeMutation = useUpdateCardTypeActive();
|
||||
const isActiveFilter = activeFilters.find((f) => f.fieldId === "isActive")?.value ?? "";
|
||||
|
||||
const { data, isLoading } = useCardTypes({ page, perPage, search, isActive: isActiveFilter });
|
||||
const { data, isLoading } = useCardTypes({ page, limit: perPage, search, isActive: isActiveFilter });
|
||||
|
||||
const filterFields: FilterField[] = [
|
||||
{
|
||||
@@ -53,6 +55,10 @@ export function CardTypesListPage() {
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleToggleActive = (cardType: CardType) => {
|
||||
activeMutation.mutate({ id: cardType.id, active: !cardType.active });
|
||||
};
|
||||
|
||||
const columns: ColumnDef<CardType>[] = [
|
||||
{
|
||||
accessorKey: "id",
|
||||
@@ -61,33 +67,41 @@ export function CardTypesListPage() {
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
accessorKey: "title",
|
||||
id: "name",
|
||||
header: t("cardTypes.fields.name", "ADY").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name[lang]}</span>,
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.title[lang]}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "value",
|
||||
header: t("cardTypes.fields.value", "BAHA").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.value}</span>,
|
||||
accessorKey: "price",
|
||||
header: t("cardTypes.fields.price", "BAHA").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.price}</span>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: t("cardTypes.fields.description", "BELLIKLER").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.description ?? "—"}</span>,
|
||||
accessorKey: "notes",
|
||||
header: t("cardTypes.fields.notes", "BELLIKLER").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.notes ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "isActive",
|
||||
accessorKey: "active",
|
||||
id: "isActive",
|
||||
header: t("cardTypes.fields.isActive", "IŞJEŇ").toUpperCase(),
|
||||
cell: ({ row }) =>
|
||||
row.original.isActive ? (
|
||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
||||
) : (
|
||||
<XCircle size={18} className="text-destructive" />
|
||||
),
|
||||
size: 100,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={row.original.active}
|
||||
onCheckedChange={() => handleToggleActive(row.original)}
|
||||
disabled={activeMutation.isPending}
|
||||
/>
|
||||
{row.original.active ? (
|
||||
<StatusBadge label={t("common.active", "Işjeň")} variant="success" />
|
||||
) : (
|
||||
<StatusBadge label={t("common.inactive", "Işjeň däl")} variant="default" />
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
size: 150,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -112,7 +126,8 @@ export function CardTypesListPage() {
|
||||
label: typeof c.header === "string" ? c.header : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ""),
|
||||
}));
|
||||
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -166,7 +181,7 @@ export function CardTypesListPage() {
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.paymentCards ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -176,7 +191,7 @@ export function CardTypesListPage() {
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={data?.total}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -12,33 +12,29 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Section, InfoRow, MultiLangRow } from '@/components/viewPageComponents'
|
||||
import { useCardTypeById, useDeleteCardType } from '@/features/cardTypes/hooks/useCardTypes'
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import { useCardTypeById, useDeleteCardType } from "@/features/cardTypes/hooks/useCardTypes";
|
||||
|
||||
export function CardTypeViewPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const { t, i18n } = useTranslation()
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const numericId = Number(id)
|
||||
const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en'
|
||||
const numericId = Number(id);
|
||||
|
||||
const { data, isLoading } = useCardTypeById(numericId)
|
||||
const deleteMutation = useDeleteCardType()
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
const { data, isLoading } = useCardTypeById(numericId);
|
||||
const deleteMutation = useDeleteCardType();
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
||||
<div className="flex items-start justify-between mb-6">
|
||||
<div>
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{isLoading
|
||||
? '...'
|
||||
: `${t('cardTypes.view.title', 'Kart görnüşi giňişleýin')}: ${data?.name[lang] ?? ''}`}
|
||||
{isLoading ? "..." : `${t("cardTypes.view.title", "Kart görnüşi giňişleýin")}: ${data?.title.tm ?? ""}`}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
@@ -46,8 +42,8 @@ export function CardTypeViewPage() {
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => navigate(`/resources/card-types/${numericId}/edit`)}
|
||||
title={t('common.edit', 'Üýtgetmek')}
|
||||
onClick={() => navigate(`/settings/card/card-types/${numericId}/edit`)}
|
||||
title={t("common.edit", "Üýtgetmek")}
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</Button>
|
||||
@@ -56,7 +52,7 @@ export function CardTypeViewPage() {
|
||||
size="icon"
|
||||
className="text-destructive border-destructive/30 hover:bg-destructive/10"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
title={t('common.delete', 'Öçürmek')}
|
||||
title={t("common.delete", "Öçürmek")}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
@@ -79,57 +75,48 @@ export function CardTypeViewPage() {
|
||||
<Section>
|
||||
<InfoRow label="ID" value={data.id} />
|
||||
|
||||
<MultiLangRow label={t('cardTypes.fields.name', 'Ady')} value={data.name} />
|
||||
<MultiLangRow label={t("cardTypes.fields.name", "Ady")} value={data.title} />
|
||||
|
||||
<InfoRow label={t('cardTypes.fields.value', 'Baha')} value={data.value} />
|
||||
<InfoRow
|
||||
label={t('cardTypes.fields.description', 'Bellikler')}
|
||||
value={data.description ?? undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardTypes.fields.price", "Baha")} value={data.price} />
|
||||
<InfoRow label={t("cardTypes.fields.notes", "Bellikler")} value={data.notes ?? undefined} />
|
||||
|
||||
<div className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-2.5 px-4 gap-1 sm:gap-0">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">
|
||||
{t('cardTypes.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
{data.isActive ? (
|
||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">{t("cardTypes.fields.isActive", "Işjeň")}</span>
|
||||
{data.active ? (
|
||||
<StatusBadge label={t("common.active", "Işjeň")} variant="success" />
|
||||
) : (
|
||||
<XCircle size={18} className="text-destructive" />
|
||||
<StatusBadge label={t("common.inactive", "Işjeň däl")} variant="default" />
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">{t('common.noData', 'Maglumat ýok')}</p>
|
||||
<p className="text-muted-foreground text-sm">{t("common.noData", "Maglumat ýok")}</p>
|
||||
)}
|
||||
|
||||
{/* Delete dialog */}
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t('cardTypes.deleteConfirm', 'Bu kart görnüşini öçürmek isleýärsiňizmi?')}
|
||||
</AlertDialogDescription>
|
||||
<AlertDialogTitle>{t("common.confirmDelete", "Öçürmegi tassyklaň")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t("cardTypes.deleteConfirm", "Bu kart görnüşini öçürmek isleýärsiňizmi?")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
|
||||
<AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() =>
|
||||
deleteMutation.mutate(numericId, {
|
||||
onSuccess: () => navigate('/resources/card-types'),
|
||||
onSuccess: () => navigate("/settings/card/card-types"),
|
||||
})
|
||||
}
|
||||
>
|
||||
{deleteMutation.isPending
|
||||
? t('common.deleting', 'Öçürilýär...')
|
||||
: t('common.delete', 'Öçürmek')}
|
||||
{deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default CardTypeViewPage
|
||||
export default CardTypeViewPage;
|
||||
|
||||
@@ -19,7 +19,7 @@ export function CardReasonsListPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const lang = (i18n.language?.slice(0, 2) ?? "tk") as "tk" | "ru" | "en";
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
// ── Table state ─────────────────────────────────────────────────────────────
|
||||
const [page, setPage] = useState(1);
|
||||
@@ -33,14 +33,7 @@ export function CardReasonsListPage() {
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const deleteMutation = useDeleteCardReason();
|
||||
|
||||
const isActiveFilter = activeFilters.find((f) => f.fieldId === "isActive")?.value ?? "";
|
||||
|
||||
const { data, isLoading } = useCardReasons({
|
||||
page,
|
||||
perPage,
|
||||
search,
|
||||
isActive: isActiveFilter,
|
||||
});
|
||||
const { data, isLoading } = useCardReasons({ page, limit: perPage, search });
|
||||
|
||||
const filterFields: FilterField[] = [
|
||||
{
|
||||
@@ -72,32 +65,28 @@ export function CardReasonsListPage() {
|
||||
size: 70,
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
accessorKey: "title",
|
||||
id: "name",
|
||||
header: t("cardReasons.fields.name", "ADY").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name[lang]}</span>,
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.title[lang]}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "value",
|
||||
header: t("cardReasons.fields.value", "BAHA").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.value}</span>,
|
||||
accessorKey: "price",
|
||||
header: t("cardReasons.fields.price", "BAHA").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.price}</span>,
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: t("cardReasons.fields.description", "BELLIKLER").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.description ?? "—"}</span>,
|
||||
accessorKey: "notes",
|
||||
header: t("cardReasons.fields.notes", "BELLIKLER").toUpperCase(),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.notes ?? "—"}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "isActive",
|
||||
accessorKey: "active",
|
||||
id: "isActive",
|
||||
header: t("cardReasons.fields.isActive", "IŞJEŇ").toUpperCase(),
|
||||
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: 100,
|
||||
},
|
||||
{
|
||||
@@ -123,7 +112,8 @@ export function CardReasonsListPage() {
|
||||
label: typeof c.header === "string" ? c.header : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ""),
|
||||
}));
|
||||
|
||||
const totalPages = data ? Math.ceil(data.total / perPage) : 1;
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -177,7 +167,7 @@ export function CardReasonsListPage() {
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.reasonCards ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -187,7 +177,7 @@ export function CardReasonsListPage() {
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={data?.total}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Pencil, Trash2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CheckCircle2, XCircle } from 'lucide-react'
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CheckCircle2, XCircle } from "lucide-react";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -13,35 +13,31 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Section, InfoRow, MultiLangRow } from '@/components/viewPageComponents'
|
||||
import { useCardReasonById, useDeleteCardReason } from '@/features/cardReasons/hooks/useCardReasons'
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents";
|
||||
import { useCardReasonById, useDeleteCardReason } from "@/features/cardReasons/hooks/useCardReasons";
|
||||
|
||||
// ─── CardReasonViewPage ────────────────────────────────────────────────────────
|
||||
|
||||
export function CardReasonViewPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const { t, i18n } = useTranslation()
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const numericId = Number(id)
|
||||
const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en'
|
||||
const numericId = Number(id);
|
||||
const lang = (i18n.language?.slice(0, 2) ?? "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const { data, isLoading } = useCardReasonById(numericId)
|
||||
const deleteMutation = useDeleteCardReason()
|
||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
||||
const { data, isLoading } = useCardReasonById(numericId);
|
||||
const deleteMutation = useDeleteCardReason();
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div >
|
||||
|
||||
<div>
|
||||
<div className="flex items-start justify-between mb-6">
|
||||
<div>
|
||||
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
{isLoading
|
||||
? '...'
|
||||
: `${t('cardReasons.viewTitle', 'Kartyň çykarylmagynyň sebäbi giňişleýin')}: ${data?.name[lang] ?? ''}`}
|
||||
{isLoading ? "..." : `${t("cardReasons.viewTitle", "Kartyň çykarylmagynyň sebäbi giňişleýin")}: ${data?.title[lang] ?? ""}`}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
@@ -49,8 +45,8 @@ export function CardReasonViewPage() {
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => navigate(`/resources/card-states/${numericId}/edit`)}
|
||||
title={t('common.edit', 'Üýtgetmek')}
|
||||
onClick={() => navigate(`/settings/card/card-reasons/${numericId}/edit`)}
|
||||
title={t("common.edit", "Üýtgetmek")}
|
||||
>
|
||||
<Pencil size={15} />
|
||||
</Button>
|
||||
@@ -59,7 +55,7 @@ export function CardReasonViewPage() {
|
||||
size="icon"
|
||||
className="text-destructive border-destructive/30 hover:bg-destructive/10"
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
title={t('common.delete', 'Öçürmek')}
|
||||
title={t("common.delete", "Öçürmek")}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
@@ -80,63 +76,49 @@ export function CardReasonViewPage() {
|
||||
</div>
|
||||
) : data ? (
|
||||
<Section>
|
||||
<InfoRow label={t('common.id', 'ID')} value={data.id} />
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
|
||||
<MultiLangRow label={t('cardReasons.fields.name', 'Ady')} value={data.name} />
|
||||
<MultiLangRow label={t("cardReasons.fields.name", "Ady")} value={data.title} />
|
||||
|
||||
<InfoRow
|
||||
label={t('cardReasons.fields.value', 'Baha')}
|
||||
value={data.value}
|
||||
/>
|
||||
<InfoRow
|
||||
label={t('cardReasons.fields.description', 'Bellikler')}
|
||||
value={data.description ?? undefined}
|
||||
/>
|
||||
<InfoRow label={t("cardReasons.fields.price", "Baha")} value={data.price} />
|
||||
<InfoRow label={t("cardReasons.fields.notes", "Bellikler")} value={data.notes ?? undefined} />
|
||||
|
||||
{/* isActive custom row */}
|
||||
<div className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-2.5 px-4 gap-1 sm:gap-0">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">
|
||||
{t('cardReasons.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
{data.isActive ? (
|
||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
||||
) : (
|
||||
<XCircle size={18} className="text-destructive" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">{t("cardReasons.fields.isActive", "Işjeň")}</span>
|
||||
{data.active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />}
|
||||
</div>
|
||||
</Section>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">{t('common.noData', 'Maglumat ýok')}</p>
|
||||
<p className="text-muted-foreground text-sm">{t("common.noData", "Maglumat ýok")}</p>
|
||||
)}
|
||||
|
||||
{/* Delete dialog */}
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("common.confirmDelete", "Öçürmegi tassyklaň")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t('cardReasons.deleteConfirm', 'Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?')}
|
||||
{t("cardReasons.deleteConfirm", "Bu kartyň çykarylmagynyň sebäbini öçürmek isleýärsiňizmi?")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
|
||||
<AlertDialogCancel>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() =>
|
||||
deleteMutation.mutate(numericId, {
|
||||
onSuccess: () => navigate('/resources/card-states'),
|
||||
onSuccess: () => navigate("/settings/card/card-reasons"),
|
||||
})
|
||||
}
|
||||
>
|
||||
{deleteMutation.isPending
|
||||
? t('common.deleting', 'Öçürilýär...')
|
||||
: t('common.delete', 'Öçürmek')}
|
||||
{deleteMutation.isPending ? t("common.deleting", "Öçürilýär...") : t("common.delete", "Öçürmek")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default CardReasonViewPage
|
||||
export default CardReasonViewPage;
|
||||
|
||||
@@ -21,7 +21,7 @@ function useLoanTypeColumns(
|
||||
onDelete: (id: number) => void,
|
||||
): ColumnDef<LoanType>[] {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = (i18n.language ?? "tk") as "tk" | "ru" | "en";
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -31,9 +31,9 @@ function useLoanTypeColumns(
|
||||
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
accessorKey: "title",
|
||||
header: t("loanTypes.columns.name", "ADY"),
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name[lang]}</span>,
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.title[lang]}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "tax",
|
||||
@@ -48,19 +48,19 @@ function useLoanTypeColumns(
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.loanTerm}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "notes",
|
||||
accessorKey: "content",
|
||||
header: t("loanTypes.columns.notes", "BELLIKLER"),
|
||||
cell: ({ row }) => {
|
||||
const notes = row.original.notes;
|
||||
return <span className="text-sm text-foreground">{notes ? notes[lang] || "—" : "—"}</span>;
|
||||
const content = row.original.content;
|
||||
return <span className="text-sm text-foreground">{content ? content[lang] || "—" : "—"}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "isActive",
|
||||
accessorKey: "active",
|
||||
header: t("loanTypes.columns.isActive", "IŞJEŇ"),
|
||||
size: 80,
|
||||
cell: ({ row }) =>
|
||||
row.original.isActive ? (
|
||||
row.original.active ? (
|
||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
||||
) : (
|
||||
<XCircle size={18} className="text-muted-foreground" />
|
||||
@@ -96,7 +96,7 @@ export default function LoanTypesListPage() {
|
||||
const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>({});
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>([]);
|
||||
|
||||
const { data, isLoading } = useGetLoanTypes({ page, perPage, search });
|
||||
const { data, isLoading } = useGetLoanTypes({ page, limit: perPage, search });
|
||||
const deleteMutation = useDeleteLoanType();
|
||||
|
||||
const handleView = (id: number) => navigate(`/settings/loan/loan-types/${id}`);
|
||||
@@ -118,6 +118,9 @@ export default function LoanTypesListPage() {
|
||||
label: typeof c.header === "string" ? c.header : String(c.id ?? ""),
|
||||
}));
|
||||
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-semibold text-foreground mb-5">{t("loanTypes.title", "Karz görnüşleri")}</h1>
|
||||
@@ -154,7 +157,7 @@ export default function LoanTypesListPage() {
|
||||
|
||||
<DataTable<LoanType>
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.loanTypes ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -163,8 +166,8 @@ export default function LoanTypesListPage() {
|
||||
enableRowSelection
|
||||
getRowId={(row) => String(row.id)}
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.total}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// pages/LoanTypeViewPage.tsx
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pencil, Trash2, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -15,29 +15,29 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { Section, InfoRow, MultiLangRow } from '@/components/viewPageComponents'
|
||||
import { useGetLoanTypeById, useDeleteLoanType } from '@/features/loanTypes/hooks/useLoanTypes'
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Section, InfoRow, MultiLangRow } from "@/components/viewPageComponents";
|
||||
import { useGetLoanTypeById, useDeleteLoanType } from "@/features/loanTypes/hooks/useLoanTypes";
|
||||
|
||||
// ─── LoanTypeViewPage ─────────────────────────────────────────────────────────
|
||||
|
||||
export default function LoanTypeViewPage() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const loanTypeId = Number(id)
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const loanTypeId = Number(id);
|
||||
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
const { data, isLoading, isError } = useGetLoanTypeById(loanTypeId)
|
||||
const deleteMutation = useDeleteLoanType()
|
||||
const { data, isLoading, isError } = useGetLoanTypeById(loanTypeId);
|
||||
const deleteMutation = useDeleteLoanType();
|
||||
|
||||
const lang = (i18n.language ?? 'tk') as 'tk' | 'ru' | 'en'
|
||||
const lang = (i18n.language === "ru" ? "ru" : i18n.language === "en" ? "en" : "tm") as "tm" | "ru" | "en";
|
||||
|
||||
const handleDelete = async () => {
|
||||
await deleteMutation.mutateAsync(loanTypeId)
|
||||
navigate('/resources/loan-types')
|
||||
}
|
||||
await deleteMutation.mutateAsync(loanTypeId);
|
||||
navigate("/settings/loan/loan-types");
|
||||
};
|
||||
|
||||
// ── Skeleton ───────────────────────────────────────────────────────────────
|
||||
if (isLoading) {
|
||||
@@ -47,34 +47,33 @@ export default function LoanTypeViewPage() {
|
||||
<Skeleton className="h-7 w-80 mb-6" />
|
||||
<div className="bg-card border border-border rounded-xl overflow-hidden divide-y divide-border">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<div key={i} className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center px-4 py-3 gap-2 sm:gap-0">
|
||||
<div
|
||||
key={i}
|
||||
className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center px-4 py-3 gap-2 sm:gap-0"
|
||||
>
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ── Error ──────────────────────────────────────────────────────────────────
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<div className=" flex items-center justify-center py-20 text-destructive text-sm">
|
||||
{t('common.error', 'Ýalňyşlyk ýüze çykdy')}
|
||||
</div>
|
||||
)
|
||||
<div className=" flex items-center justify-center py-20 text-destructive text-sm">{t("common.error", "Ýalňyşlyk ýüze çykdy")}</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── View ───────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div >
|
||||
|
||||
|
||||
<div>
|
||||
{/* Page header */}
|
||||
<div className="flex items-start justify-between mb-5">
|
||||
<h1 className="text-xl font-semibold text-foreground">
|
||||
{t('loanTypes.viewTitle', 'Karz görnüşi giňişleýin')}: {data.name[lang]}
|
||||
{t("loanTypes.viewTitle", "Karz görnüşi giňişleýin")}: {data.title[lang]}
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
@@ -82,16 +81,16 @@ export default function LoanTypeViewPage() {
|
||||
size="icon"
|
||||
onClick={() => setShowDeleteDialog(true)}
|
||||
className="text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
|
||||
title={t('common.delete', 'Pozmak')}
|
||||
title={t("common.delete", "Pozmak")}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => navigate(`/resources/loan-types/${loanTypeId}/edit`)}
|
||||
onClick={() => navigate(`/settings/loan/loan-types/${loanTypeId}/edit`)}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors"
|
||||
title={t('common.edit', 'Redaktirlemek')}
|
||||
title={t("common.edit", "Redaktirlemek")}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</Button>
|
||||
@@ -100,38 +99,22 @@ export default function LoanTypeViewPage() {
|
||||
|
||||
{/* Detail section */}
|
||||
<Section>
|
||||
<InfoRow label={t('common.id', 'ID')} value={data.id} />
|
||||
<InfoRow label={t("common.id", "ID")} value={data.id} />
|
||||
|
||||
<MultiLangRow label={t('loanTypes.fields.name', 'Ady')} value={data.name} />
|
||||
<MultiLangRow label={t("loanTypes.fields.name", "Ady")} value={data.title} />
|
||||
|
||||
<InfoRow
|
||||
label={t('loanTypes.fields.tax', 'Salgyt')}
|
||||
value={data.tax}
|
||||
/>
|
||||
<InfoRow label={t("loanTypes.fields.tax", "Salgyt")} value={data.tax} />
|
||||
|
||||
<InfoRow
|
||||
label={t('loanTypes.fields.loanTerm', 'Karz möhleti')}
|
||||
value={data.loanTerm}
|
||||
/>
|
||||
<InfoRow label={t("loanTypes.fields.loanTerm", "Karz möhleti")} value={data.loanTerm} />
|
||||
|
||||
<div className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-2.5 px-4 border-b border-border gap-0.5 sm:gap-0">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">
|
||||
{t('loanTypes.fields.notes', 'Bellikler')}
|
||||
</span>
|
||||
<span className="text-sm text-foreground break-words min-w-0">
|
||||
{data.notes ? data.notes[lang] || '—' : '—'}
|
||||
</span>
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">{t("loanTypes.fields.notes", "Bellikler")}</span>
|
||||
<span className="text-sm text-foreground break-words min-w-0">{data.content ? data.content[lang] || "—" : "—"}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:grid sm:grid-cols-[minmax(0,42%)_minmax(0,58%)] items-start sm:items-center py-2.5 px-4 border-b border-border last:border-0 gap-1 sm:gap-0">
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">
|
||||
{t('loanTypes.fields.isActive', 'Işjeň')}
|
||||
</span>
|
||||
{data.isActive ? (
|
||||
<CheckCircle2 size={20} className="text-emerald-500" />
|
||||
) : (
|
||||
<XCircle size={20} className="text-muted-foreground" />
|
||||
)}
|
||||
<span className="text-xs sm:text-sm text-muted-foreground leading-snug">{t("loanTypes.fields.isActive", "Işjeň")}</span>
|
||||
{data.active ? <CheckCircle2 size={20} className="text-emerald-500" /> : <XCircle size={20} className="text-muted-foreground" />}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
@@ -139,30 +122,23 @@ export default function LoanTypeViewPage() {
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('loanTypes.deleteDialog.title', 'Pozmak')}</AlertDialogTitle>
|
||||
<AlertDialogTitle>{t("loanTypes.deleteDialog.title", "Pozmak")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t(
|
||||
'loanTypes.deleteDialog.description',
|
||||
'Bu karz görnüşini pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylyp bilinmez.'
|
||||
)}
|
||||
{t("loanTypes.deleteDialog.description", "Bu karz görnüşini pozmak isleýärsiňizmi? Bu amal yzyna gaýtarylyp bilinmez.")}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>
|
||||
{t('common.cancel', 'Ýatyr')}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>{t("common.cancel", "Ýatyr")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={deleteMutation.isPending}
|
||||
className="bg-destructive hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMutation.isPending
|
||||
? t('common.deleting', 'Pozulýar...')
|
||||
: t('common.delete', 'Pozmak')}
|
||||
{deleteMutation.isPending ? t("common.deleting", "Pozulýar...") : t("common.delete", "Pozmak")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,17 @@ import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||
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 { useGetRequiredDocuments, useDeleteRequiredDocument } from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { StatusBadge } from "@/components/ui/statusBadge";
|
||||
import {
|
||||
useGetRequiredDocuments,
|
||||
useDeleteRequiredDocument,
|
||||
useUpdateRequiredDocumentActive,
|
||||
} from "@/features/requiredDocuments/hooks/useRequiredDocuments";
|
||||
import type { LoanDocument } from "@/features/requiredDocuments/api/requiredDocumentsApi";
|
||||
import type { VisibilityState } from "@tanstack/react-table";
|
||||
import { DeleteDialog } from "@/components/deleteDialog";
|
||||
@@ -14,34 +20,32 @@ import { DeleteDialog } from "@/components/deleteDialog";
|
||||
// ─── Column visibility defaults ───────────────────────────────────────────────
|
||||
|
||||
const DEFAULT_VISIBILITY: VisibilityState = {};
|
||||
const DEFAULT_ORDER = ["id", "name", "actions"];
|
||||
const DEFAULT_ORDER = ["id", "name", "value", "active", "actions"];
|
||||
|
||||
export default function RequiredDocumentsListPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const lang = (i18n.language?.slice(0, 2) ?? "tk") as "tk" | "ru" | "en";
|
||||
|
||||
// ── Table state ─────────────────────────────────────────────────────────────
|
||||
const [search, setSearch] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [perPage] = useState(10);
|
||||
const [perPage] = useState(25);
|
||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(DEFAULT_VISIBILITY);
|
||||
const [columnOrder, setColumnOrder] = useState<string[]>(DEFAULT_ORDER);
|
||||
const [activeFilters, setActiveFilters] = useState<ActiveFilter[]>([{ fieldId: "isActive", value: "" }]);
|
||||
|
||||
// ── Data ────────────────────────────────────────────────────────────────────
|
||||
const { data, isLoading } = useGetRequiredDocuments({ page, perPage, search });
|
||||
const isActiveFilter = activeFilters.find((f) => f.fieldId === "isActive")?.value ?? "";
|
||||
const { data, isLoading } = useGetRequiredDocuments({ page, limit: perPage, search, active: isActiveFilter });
|
||||
const deleteMutation = useDeleteRequiredDocument();
|
||||
const activeMutation = useUpdateRequiredDocumentActive();
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
const total = data?.count ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / perPage));
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (deleteId === null) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
const handleToggleActive = (doc: LoanDocument) => {
|
||||
activeMutation.mutate({ id: doc.id, active: !doc.active });
|
||||
};
|
||||
|
||||
// ── Columns ─────────────────────────────────────────────────────────────────
|
||||
@@ -62,9 +66,36 @@ export default function RequiredDocumentsListPage() {
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
accessorKey: "name",
|
||||
header: t("loanDocuments.columns.name", "ADY"),
|
||||
accessorFn: (row) => row.name[lang],
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name[lang]}</span>,
|
||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.name}</span>,
|
||||
},
|
||||
{
|
||||
id: "value",
|
||||
accessorKey: "value",
|
||||
header: t("loanDocuments.columns.value", "BAHA"),
|
||||
cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.value}</span>,
|
||||
},
|
||||
{
|
||||
id: "active",
|
||||
accessorKey: "active",
|
||||
header: t("loanDocuments.columns.isActive", "IŞJEŇ"),
|
||||
size: 100,
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={row.original.active}
|
||||
onCheckedChange={() => handleToggleActive(row.original)}
|
||||
disabled={activeMutation.isPending}
|
||||
/>
|
||||
{row.original.active ? (
|
||||
<StatusBadge label={t("common.active", "Işjeň")} variant="success" />
|
||||
) : (
|
||||
<StatusBadge label={t("common.inactive", "Işjeň däl")} variant="default" />
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -82,10 +113,42 @@ export default function RequiredDocumentsListPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (deleteId === null) return;
|
||||
deleteMutation.mutate(deleteId);
|
||||
setDeleteId(null);
|
||||
};
|
||||
|
||||
const columnMetas = columns
|
||||
.filter((c) => c.id !== "actions" && c.id !== "select")
|
||||
.map((c) => ({ id: c.id as string, label: typeof c.header === "string" ? c.header : (c.id as string) }));
|
||||
|
||||
// ── Filter fields ───────────────────────────────────────────────────────────
|
||||
const filterFields: FilterField[] = [
|
||||
{
|
||||
id: "isActive",
|
||||
label: t("loanDocuments.fields.isActive", "Işjeň"),
|
||||
options: [
|
||||
{ value: "true", label: t("common.active", "Işjeň") },
|
||||
{ value: "false", label: t("common.inactive", "Işjeň däl") },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const handleFilterChange = (fieldId: string, value: string) => {
|
||||
setActiveFilters((prev) => prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)));
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleFilterReset = () => {
|
||||
setActiveFilters([{ fieldId: "isActive", value: "" }]);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Page heading */}
|
||||
@@ -120,12 +183,16 @@ export default function RequiredDocumentsListPage() {
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
hideSearch
|
||||
hideAction
|
||||
filterFields={filterFields}
|
||||
activeFilters={activeFilters}
|
||||
onFilterChange={handleFilterChange}
|
||||
onFilterReset={handleFilterReset}
|
||||
/>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
data={data?.loansDocuments ?? []}
|
||||
isLoading={isLoading}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
@@ -134,8 +201,8 @@ export default function RequiredDocumentsListPage() {
|
||||
getRowId={(row) => String(row.id)}
|
||||
enableRowSelection
|
||||
currentPage={page}
|
||||
totalPages={data?.totalPages ?? 1}
|
||||
totalCount={data?.total}
|
||||
totalPages={totalPages}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user