updated login, added client, staff api, forget and register api
This commit is contained in:
1 parent
5073166931
commit
0e75c85fe1
16 files changed
+1501
-980
No files matched your search
@@ -1,8 +1,22 @@
|
|||||||
import apiClient from "@/lib/api/client";
|
import apiClient from "@/lib/api/client";
|
||||||
import type { AuthUser } from "@/app/store/authStore";
|
import type { AuthUser } from "@/app/store/authStore";
|
||||||
|
|
||||||
|
export interface RegisterRequest {
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
passwordConfirm: string;
|
||||||
|
phone: string;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterVerifyRequest {
|
||||||
|
code: string;
|
||||||
|
phone: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface LoginRequest {
|
export interface LoginRequest {
|
||||||
email: string;
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,3 +57,30 @@ export async function updateProfileApi(data: UpdateProfileRequest): Promise<Auth
|
|||||||
export async function logoutApi(): Promise<void> {
|
export async function logoutApi(): Promise<void> {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function registerApi(data: RegisterRequest): Promise<void> {
|
||||||
|
await apiClient.post("/register", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registerVerifyApi(data: RegisterVerifyRequest): Promise<void> {
|
||||||
|
await apiClient.post("/register/verify", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForgotPasswordRequest {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ForgotPasswordVerifyRequest {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
passwordConfirm: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forgotPasswordApi(data: ForgotPasswordRequest): Promise<void> {
|
||||||
|
await apiClient.post("/forgot-password", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forgotPasswordVerifyApi(data: ForgotPasswordVerifyRequest): Promise<void> {
|
||||||
|
await apiClient.post("/forgot-password/verify", data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { forgotPasswordApi, forgotPasswordVerifyApi, type ForgotPasswordRequest, type ForgotPasswordVerifyRequest } from "../api/authApi";
|
||||||
|
|
||||||
|
export function useForgotPassword() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: ForgotPasswordRequest) => forgotPasswordApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useForgotPasswordVerify() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: ForgotPasswordVerifyRequest) => forgotPasswordVerifyApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { registerApi, registerVerifyApi, type RegisterRequest, type RegisterVerifyRequest } from "../api/authApi";
|
||||||
|
|
||||||
|
export function useRegister() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: RegisterRequest) => registerApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRegisterVerify() {
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: RegisterVerifyRequest) => registerVerifyApi(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,267 +1,163 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface SocialMedia {
|
||||||
|
facebook: string;
|
||||||
|
instagram: string;
|
||||||
|
telegram: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Client {
|
export interface Client {
|
||||||
id: number
|
id: number;
|
||||||
username: string
|
email: string;
|
||||||
name: string
|
name: string;
|
||||||
phone: string | null
|
firstName: string;
|
||||||
email: string | null
|
lastName: string;
|
||||||
isActive: boolean
|
username: string;
|
||||||
|
phone: string;
|
||||||
|
avatar: string;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
lightMode: number;
|
||||||
|
role: string;
|
||||||
|
active: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientDetail extends Client {
|
export interface ClientDetail extends Client {
|
||||||
roles: ClientRole[]
|
roles: ClientRole[];
|
||||||
permissions: ClientPermission[]
|
permissions: ClientPermission[];
|
||||||
branches: ClientBranch[]
|
branches: ClientBranch[];
|
||||||
loanOrders: ClientLoanOrder[]
|
loanOrders: ClientLoanOrder[];
|
||||||
cardOrders: ClientCardOrder[]
|
cardOrders: ClientCardOrder[];
|
||||||
auditLogs: ClientAuditLog[]
|
auditLogs: ClientAuditLog[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientRole {
|
export interface ClientRole {
|
||||||
id: number
|
id: number;
|
||||||
code: string
|
code: string;
|
||||||
name: string
|
name: string;
|
||||||
guardName: string
|
guardName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientPermission {
|
export interface ClientPermission {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
guardName: string
|
guardName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientBranch {
|
export interface ClientBranch {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
region: string
|
region: string;
|
||||||
district: string
|
district: string;
|
||||||
uniqueCode: string
|
uniqueCode: string;
|
||||||
isActive: boolean
|
isActive: boolean;
|
||||||
billingUsernameIbr: string
|
billingUsernameIbr: string;
|
||||||
billingUsernameSber: string
|
billingUsernameSber: string;
|
||||||
billingUsernameVisa: string
|
billingUsernameVisa: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientLoanOrder {
|
export interface ClientLoanOrder {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
amount: number
|
amount: number;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientCardOrder {
|
export interface ClientCardOrder {
|
||||||
id: number
|
id: number;
|
||||||
name: string
|
name: string;
|
||||||
amount: number
|
amount: number;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientAuditLog {
|
export interface ClientAuditLog {
|
||||||
id: number
|
id: number;
|
||||||
actionName: string
|
actionName: string;
|
||||||
performedBy: string
|
performedBy: string;
|
||||||
target: string
|
target: string;
|
||||||
status: string
|
status: string;
|
||||||
createdAt: string
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientsListResponse {
|
export interface ClientsListResponse {
|
||||||
data: Client[]
|
count: number;
|
||||||
meta: {
|
users: Client[];
|
||||||
currentPage: number
|
|
||||||
totalPages: number
|
|
||||||
totalCount: number
|
|
||||||
perPage: number
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateClientPayload {
|
|
||||||
username: string
|
|
||||||
name: string
|
|
||||||
phone: string
|
|
||||||
email?: string
|
|
||||||
password: string
|
|
||||||
isActive: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UpdateClientPayload {
|
|
||||||
username?: string
|
|
||||||
name?: string
|
|
||||||
phone?: string
|
|
||||||
email?: string
|
|
||||||
password?: string
|
|
||||||
isActive?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientsListParams {
|
export interface ClientsListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
perPage?: number
|
limit?: number;
|
||||||
search?: string
|
search?: string;
|
||||||
isActive?: string
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock Data & API ────────────────────────────────────────────────────────────
|
export interface CreateClientPayload {
|
||||||
|
active: boolean;
|
||||||
|
avatar: string;
|
||||||
|
email: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
lightMode: number;
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
phone: string;
|
||||||
|
role: string;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
export interface UpdateClientPayload {
|
||||||
|
active?: boolean;
|
||||||
|
avatar?: string;
|
||||||
|
email?: string;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
lightMode?: number;
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
role?: string;
|
||||||
|
socialMedia?: SocialMedia;
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
|
||||||
let mockClients: ClientDetail[] = [
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
username: 'client_01',
|
|
||||||
name: 'Merdan Merdanow',
|
|
||||||
phone: '+99361234567',
|
|
||||||
email: 'merdan@example.com',
|
|
||||||
isActive: true,
|
|
||||||
roles: [{ id: 1, code: 'CLIENT_STANDARD', name: 'Standard Client', guardName: 'web' }],
|
|
||||||
permissions: [],
|
|
||||||
branches: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
name: 'Aşgabat Baş Şahamça',
|
|
||||||
region: 'Aşgabat',
|
|
||||||
district: 'Kopetdag',
|
|
||||||
uniqueCode: '01',
|
|
||||||
isActive: true,
|
|
||||||
billingUsernameIbr: 'ibr_c1',
|
|
||||||
billingUsernameSber: 'sber_c1',
|
|
||||||
billingUsernameVisa: 'visa_c1',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
loanOrders: [
|
|
||||||
{ id: 101, name: 'Sarp ediş karzy', amount: 20000, status: 'Active', createdAt: '2023-11-01T10:00:00Z' }
|
|
||||||
],
|
|
||||||
cardOrders: [
|
|
||||||
{ id: 201, name: 'Visa Gold', amount: 500, status: 'Pending', createdAt: '2023-11-05T14:30:00Z' }
|
|
||||||
],
|
|
||||||
auditLogs: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
actionName: 'Profile Update',
|
|
||||||
performedBy: 'System',
|
|
||||||
target: 'client_01',
|
|
||||||
status: 'Success',
|
|
||||||
createdAt: '2023-10-27T10:00:00Z',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
username: 'client_02',
|
|
||||||
name: 'Aýnabat Aýmyradowa',
|
|
||||||
phone: '+99365765432',
|
|
||||||
email: 'aynabat@example.com',
|
|
||||||
isActive: false,
|
|
||||||
roles: [{ id: 2, code: 'CLIENT_PREMIUM', name: 'Premium Client', guardName: 'web' }],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanOrders: [],
|
|
||||||
cardOrders: [],
|
|
||||||
auditLogs: [],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export const clientsApi = {
|
export const clientsApi = {
|
||||||
getAll: async (params: ClientsListParams): Promise<ClientsListResponse> => {
|
/** GET /users/clients — backend filters by `username` */
|
||||||
await delay(500)
|
getClients: async (params: ClientsListParams = {}, signal?: AbortSignal): Promise<ClientsListResponse> => {
|
||||||
let filtered = [...mockClients]
|
const { page, limit, search, isActive } = params;
|
||||||
if (params.search) {
|
const { data } = await apiClient.get<ClientsListResponse>("/users/clients", {
|
||||||
const q = params.search.toLowerCase()
|
params: { page, limit, username: search, isActive },
|
||||||
filtered = filtered.filter(
|
signal,
|
||||||
(c) =>
|
});
|
||||||
c.name.toLowerCase().includes(q) ||
|
return data;
|
||||||
c.username.toLowerCase().includes(q) ||
|
|
||||||
(c.phone && c.phone.includes(q))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (params.isActive !== undefined && params.isActive !== '') {
|
|
||||||
const isActive = params.isActive === 'true'
|
|
||||||
filtered = filtered.filter((c) => c.isActive === isActive)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: filtered,
|
|
||||||
meta: {
|
|
||||||
currentPage: params.page || 1,
|
|
||||||
totalPages: Math.ceil(filtered.length / (params.perPage || 25)) || 1,
|
|
||||||
totalCount: filtered.length,
|
|
||||||
perPage: params.perPage || 25,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: number): Promise<ClientDetail> => {
|
/** GET /users/:id */
|
||||||
await delay(500)
|
getClientById: async (id: number): Promise<ClientDetail> => {
|
||||||
const client = mockClients.find((c) => c.id === Number(id))
|
const { data } = await apiClient.get<ClientDetail>(`/users/${id}`);
|
||||||
if (!client) throw new Error('Not found')
|
return data;
|
||||||
return client
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateClientPayload): Promise<Client> => {
|
/** POST /users — same entity & payload as all users */
|
||||||
await delay(500)
|
createClient: async (payload: CreateClientPayload): Promise<Client> => {
|
||||||
const newClient: ClientDetail = {
|
const { data } = await apiClient.post<Client>("/users", payload);
|
||||||
id: mockClients.length > 0 ? Math.max(...mockClients.map((c) => c.id)) + 1 : 1,
|
return data;
|
||||||
username: payload.username,
|
|
||||||
name: payload.name,
|
|
||||||
phone: payload.phone,
|
|
||||||
email: payload.email || null,
|
|
||||||
isActive: payload.isActive,
|
|
||||||
roles: [],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanOrders: [],
|
|
||||||
cardOrders: [],
|
|
||||||
auditLogs: [],
|
|
||||||
}
|
|
||||||
mockClients.unshift(newClient)
|
|
||||||
return newClient
|
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: number, payload: UpdateClientPayload): Promise<Client> => {
|
/** PUT /users/:id */
|
||||||
await delay(500)
|
updateClient: async (id: number, payload: UpdateClientPayload): Promise<Client> => {
|
||||||
const index = mockClients.findIndex((c) => c.id === Number(id))
|
const { data } = await apiClient.put<Client>(`/users/${id}`, payload);
|
||||||
if (index === -1) throw new Error('Not found')
|
return data;
|
||||||
|
|
||||||
mockClients[index] = {
|
|
||||||
...mockClients[index],
|
|
||||||
...payload,
|
|
||||||
username: payload.username ?? mockClients[index].username,
|
|
||||||
name: payload.name ?? mockClients[index].name,
|
|
||||||
phone: payload.phone ?? mockClients[index].phone,
|
|
||||||
email: payload.email !== undefined ? payload.email : mockClients[index].email,
|
|
||||||
isActive: payload.isActive ?? mockClients[index].isActive,
|
|
||||||
}
|
|
||||||
return mockClients[index]
|
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: number): Promise<void> => {
|
/** DELETE /users/:id */
|
||||||
await delay(500)
|
deleteClient: async (id: number): Promise<void> => {
|
||||||
mockClients = mockClients.filter((c) => c.id !== Number(id))
|
await apiClient.delete(`/users/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
assignRole: async (_clientId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removeRole: async (_clientId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
assignPermission: async (_clientId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removePermission: async (_clientId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
assignBranch: async (_clientId: number, _branchId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removeBranch: async (_clientId: number, _branchId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,19 @@
|
|||||||
import { useMemo, useEffect, useCallback } from "react";
|
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
|
||||||
import { FormActions } from "@/components/formActions";
|
|
||||||
import { FormInput } from "@/components/formInput";
|
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 { BentoGrid, BentoCard } from "@/components/bento";
|
||||||
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
|
import { useCreateClient, useUpdateClient } from "../hooks/useClients";
|
||||||
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/client.schema";
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import type { ClientFormData } from "../schemas/client.schema";
|
|
||||||
import type { Client } from "../api/clientsApi";
|
import type { Client } from "../api/clientsApi";
|
||||||
|
import { clientFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/client.schema";
|
||||||
|
import type { ClientFormData } from "../schemas/client.schema";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -42,13 +45,40 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
);
|
);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateClient();
|
const createClient = useCreateClient();
|
||||||
const updateMutation = useUpdateClient(initialData?.id ?? 0);
|
const updateClient = useUpdateClient(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createClient.isPending || updateClient.isPending;
|
||||||
|
|
||||||
const schema = useMemo(() => clientFormSchema(mode, t), [mode, t, i18n.language]);
|
const schema = useMemo(() => clientFormSchema(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 }));
|
||||||
|
|
||||||
|
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 {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -64,10 +94,18 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
...DEFAULT_FORM_VALUES,
|
...DEFAULT_FORM_VALUES,
|
||||||
username: initialData.username,
|
username: initialData.username,
|
||||||
name: initialData.name,
|
name: initialData.name,
|
||||||
phone: initialData.phone ?? "",
|
firstName: initialData.firstName ?? "",
|
||||||
|
lastName: initialData.lastName ?? "",
|
||||||
|
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||||
email: initialData.email ?? "",
|
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: "",
|
password: "",
|
||||||
isActive: initialData.isActive,
|
active: !!initialData.active,
|
||||||
}
|
}
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
});
|
});
|
||||||
@@ -88,7 +126,6 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [i18n.language]);
|
||||||
|
|
||||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
const isValid = await trigger();
|
||||||
if (!isValid) return;
|
if (!isValid) return;
|
||||||
@@ -97,27 +134,15 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
const payload = buildPayload(data);
|
const payload = buildPayload(data);
|
||||||
createMutation.mutate(payload, {
|
await createClient.mutateAsync(payload);
|
||||||
onSuccess: () => navigate("/clients"),
|
navigate("/clients");
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
updateMutation.mutate(
|
const payload = buildUpdatePayload(data);
|
||||||
{
|
await updateClient.mutateAsync(payload);
|
||||||
username: data.username.trim(),
|
navigate(`/clients/${initialData!.id}`);
|
||||||
name: data.name.trim(),
|
|
||||||
phone: data.phone.trim(),
|
|
||||||
email: data.email.trim() || undefined,
|
|
||||||
isActive: data.isActive,
|
|
||||||
...(data.password.trim() ? { password: data.password } : {}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: () => navigate(`/clients/${initialData!.id}`),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Render ──────────────────────────────────────────────────────────────────
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
@@ -127,88 +152,178 @@ export function ClientForm({ mode, initialData }: ClientFormProps) {
|
|||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("clients.fields.username", "Ulanyjy ady")}
|
label={t("users.fields.username", "Ulanyjy ady")}
|
||||||
value={form.username}
|
value={form.username}
|
||||||
onChange={(v) => setField("username", v)}
|
onChange={(v) => setField("username", v)}
|
||||||
placeholder={t("clients.fields.username", "Ulanyjy ady")}
|
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
||||||
error={errors.username}
|
error={errors.username}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
|
||||||
|
</BentoCard>
|
||||||
|
<BentoCard>
|
||||||
|
<FormInput
|
||||||
|
type="text"
|
||||||
|
label={t("users.fields.name", "Ady")}
|
||||||
|
value={form.name}
|
||||||
|
onChange={(v) => setField("name", v)}
|
||||||
|
placeholder={t("users.fields.name", "Ady")}
|
||||||
|
error={errors.name}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<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>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
label={t("clients.fields.name", "Ady")}
|
label={t("users.fields.lastName", "Familiýasy")}
|
||||||
value={form.name}
|
value={form.lastName}
|
||||||
onChange={(v) => setField("name", v)}
|
onChange={(v) => setField("lastName", v)}
|
||||||
placeholder={t("clients.fields.name", "Ady")}
|
placeholder={t("users.fields.lastName", "Familiýasy")}
|
||||||
error={errors.name}
|
error={errors.lastName}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
|
||||||
/>
|
/>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="phone"
|
type="phone"
|
||||||
label={t("clients.fields.phone", "Telefon")}
|
label={t("users.fields.phone", "Telefon")}
|
||||||
value={form.phone}
|
value={form.phone}
|
||||||
onChange={(v) => setField("phone", v)}
|
onChange={(v) => setField("phone", v)}
|
||||||
|
placeholder="62-38-49-56"
|
||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="email"
|
type="email"
|
||||||
label={t("clients.fields.email", "E-poçta")}
|
label={t("users.fields.email", "E-poçta")}
|
||||||
value={form.email}
|
value={form.email}
|
||||||
onChange={(v) => setField("email", v)}
|
onChange={(v) => setField("email", v)}
|
||||||
placeholder={t("clients.fields.email", "E-poçta")}
|
placeholder={t("users.fields.email", "E-poçta")}
|
||||||
|
error={errors.email}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
|
<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>
|
||||||
</BentoGrid>
|
|
||||||
<BentoGrid cols={1}>
|
|
||||||
<BentoCard>
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="password"
|
type="text"
|
||||||
label={t("clients.fields.password", "Açar sözi") + (mode === "create" ? " *" : "")}
|
label={t("users.fields.avatar", "Awatar URL")}
|
||||||
value={form.password}
|
value={form.avatar}
|
||||||
onChange={(v) => setField("password", v)}
|
onChange={(v) => setField("avatar", v)}
|
||||||
placeholder={
|
placeholder="https://..."
|
||||||
mode === "edit"
|
error={errors.avatar}
|
||||||
? t("clients.fields.passwordEditHint", "Üýtgetmek üçin täze açar söz giriziň")
|
|
||||||
: t("clients.fields.password", "Açar sözi")
|
|
||||||
}
|
|
||||||
error={errors.password}
|
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
/>
|
/>
|
||||||
{mode === "edit" && (
|
|
||||||
<p className="text-xs text-muted-foreground -mt-3">
|
|
||||||
{t("clients.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
<BentoCard>
|
{mode === "create" && (
|
||||||
<div className="flex items-center gap-3">
|
<BentoCard>
|
||||||
<span className="text-sm text-muted-foreground">{t("clients.fields.isActive", "Işjeň")}</span>
|
<FormInput
|
||||||
<Checkbox
|
type="password"
|
||||||
checked={form.isActive}
|
label={t("users.fields.password", "Açar sözi")}
|
||||||
onCheckedChange={(v) => setField("isActive", !!v)}
|
value={form.password}
|
||||||
|
onChange={(v) => setField("password", v)}
|
||||||
|
placeholder={t("users.fields.password", "Açar sözi")}
|
||||||
|
error={errors.password}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
|
||||||
|
</BentoCard>
|
||||||
|
)}
|
||||||
|
<BentoCard>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
|
||||||
|
</div>
|
||||||
|
<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}
|
||||||
|
/>
|
||||||
|
<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}
|
disabled={isPending}
|
||||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<FormActions
|
</BentoCard>
|
||||||
isPending={isPending}
|
<BentoCard>
|
||||||
onSubmit={handleSubmit}
|
<div className="space-y-1">
|
||||||
onCancel={() => navigate(-1)}
|
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
|
||||||
submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")}
|
</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>
|
||||||
|
<BentoCard>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
|
||||||
|
<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="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>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
<FormActions
|
||||||
|
isPending={isPending}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onCancel={() => navigate(-1)}
|
||||||
|
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,31 +1,30 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
clientsApi,
|
import { clientsApi, type ClientsListParams, type CreateClientPayload, type UpdateClientPayload } from "../api/clientsApi";
|
||||||
type ClientsListParams,
|
|
||||||
type CreateClientPayload,
|
|
||||||
type UpdateClientPayload,
|
|
||||||
} from '../api/clientsApi'
|
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const clientKeys = {
|
export const clientKeys = {
|
||||||
all: ['clients'] as const,
|
all: ["clients"] as const,
|
||||||
lists: () => [...clientKeys.all, 'list'] as const,
|
lists: () => [...clientKeys.all, "list"] as const,
|
||||||
list: (params: ClientsListParams) => [...clientKeys.lists(), params] as const,
|
list: (params: ClientsListParams) => [...clientKeys.lists(), params] as const,
|
||||||
details: () => [...clientKeys.all, 'detail'] as const,
|
details: () => [...clientKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...clientKeys.details(), id] as const,
|
detail: (id: number) => [...clientKeys.details(), id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── useClients ───────────────────────────────────────────────────────────────
|
// ─── useClients ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useClients(params: ClientsListParams) {
|
export function useClients(params: ClientsListParams = {}) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const queryParams: ClientsListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: clientKeys.list(params),
|
queryKey: clientKeys.list(queryParams),
|
||||||
queryFn: () => clientsApi.getAll(params),
|
queryFn: ({ signal }) => clientsApi.getClients(queryParams, signal),
|
||||||
placeholderData: (prev) => prev,
|
placeholderData: (prev) => prev,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useClient ────────────────────────────────────────────────────────────────
|
// ─── useClient ────────────────────────────────────────────────────────────────
|
||||||
@@ -33,96 +32,53 @@ export function useClients(params: ClientsListParams) {
|
|||||||
export function useClient(id: number) {
|
export function useClient(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: clientKeys.detail(id),
|
queryKey: clientKeys.detail(id),
|
||||||
queryFn: () => clientsApi.getById(id),
|
queryFn: () => clientsApi.getClientById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateClient ──────────────────────────────────────────────────────────
|
// ─── useCreateClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateClient() {
|
export function useCreateClient() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateClientPayload) => clientsApi.create(payload),
|
mutationFn: (payload: CreateClientPayload) => clientsApi.createClient(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
toast.success(t('clients.createSuccess', 'Müşderi üstünlikli döredildi'))
|
toast.success(t("clients.createSuccess", "Müşderi üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateClient ──────────────────────────────────────────────────────────
|
// ─── useUpdateClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateClient(id: number) {
|
export function useUpdateClient(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateClientPayload) => clientsApi.update(id, payload),
|
mutationFn: (payload: UpdateClientPayload) => clientsApi.updateClient(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updatedClient) => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(id) })
|
queryClient.setQueryData(clientKeys.detail(id), updatedClient);
|
||||||
toast.success(t('clients.updateSuccess', 'Müşderi üstünlikli täzelendi'))
|
toast.success(t("clients.updateSuccess", "Müşderi üstünlikli täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── useDeleteClient ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteClient() {
|
export function useDeleteClient() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => clientsApi.delete(id),
|
mutationFn: (id: number) => clientsApi.deleteClient(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: clientKeys.lists() });
|
||||||
toast.success(t('clients.deleteSuccess', 'Müşderi üstünlikli pozuldy'))
|
toast.success(t("clients.deleteSuccess", "Müşderi üstünlikli pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useAssignClientRole ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useAssignClientRole(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => clientsApi.assignRole(clientId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.roleAssigned', 'Rol birikdirildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useRemoveClientRole ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useRemoveClientRole(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => clientsApi.removeRole(clientId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.roleRemoved', 'Rol aýryldy'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useAssignClientBranch ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useAssignClientBranch(clientId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (branchId: number) => clientsApi.assignBranch(clientId, branchId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: clientKeys.detail(clientId) })
|
|
||||||
toast.success(t('clients.branchAssigned', 'Şahamça birikdirildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,20 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { CreateClientPayload } from "../api/clientsApi";
|
import type { CreateClientPayload, UpdateClientPayload } from "../api/clientsApi";
|
||||||
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
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 clientFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||||
const baseSchema = z.object({
|
const baseSchema = z.object({
|
||||||
username: z.string().min(1, t("validation.required", "validation.required")),
|
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")),
|
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
firstName: z.string().default(""),
|
||||||
|
lastName: z.string().default(""),
|
||||||
phone: z
|
phone: z
|
||||||
.string()
|
.string()
|
||||||
.min(1, t("validation.required", "validation.required"))
|
.min(1, t("validation.required", "validation.required"))
|
||||||
@@ -25,14 +33,26 @@ export function clientFormSchema(mode: "create" | "edit", t: (key: string, fallb
|
|||||||
},
|
},
|
||||||
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
||||||
),
|
),
|
||||||
email: z.string().default(""),
|
email: z
|
||||||
|
.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(),
|
password: z.string(),
|
||||||
isActive: z.boolean(),
|
active: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
return mode === "create"
|
return mode === "create"
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string().min(1, t("validation.required", "validation.required")),
|
password: z
|
||||||
|
.string()
|
||||||
|
.min(1, t("validation.required", "validation.required"))
|
||||||
|
.min(6, t("validation.minLength", "validation.minLength")),
|
||||||
})
|
})
|
||||||
: baseSchema;
|
: baseSchema;
|
||||||
}
|
}
|
||||||
@@ -42,19 +62,57 @@ export type ClientFormData = z.infer<ReturnType<typeof clientFormSchema>>;
|
|||||||
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
export const DEFAULT_FORM_VALUES: ClientFormData = {
|
||||||
username: "",
|
username: "",
|
||||||
name: "",
|
name: "",
|
||||||
|
firstName: "",
|
||||||
|
lastName: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
email: "",
|
email: "",
|
||||||
|
avatar: "",
|
||||||
|
role: "",
|
||||||
|
socialFacebook: "",
|
||||||
|
socialInstagram: "",
|
||||||
|
socialTelegram: "",
|
||||||
|
lightMode: false,
|
||||||
password: "",
|
password: "",
|
||||||
isActive: true,
|
active: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: ClientFormData): CreateClientPayload {
|
export function buildPayload(data: ClientFormData): CreateClientPayload {
|
||||||
return {
|
return {
|
||||||
username: data.username.trim(),
|
username: data.username.trim(),
|
||||||
name: data.name.trim(),
|
name: data.name.trim(),
|
||||||
phone: data.phone.trim(),
|
firstName: data.firstName.trim(),
|
||||||
email: data.email.trim() || undefined,
|
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,
|
password: data.password,
|
||||||
isActive: data.isActive,
|
active: data.active,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUpdatePayload(data: ClientFormData): UpdateClientPayload {
|
||||||
|
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,234 +1,159 @@
|
|||||||
|
import apiClient from "@/lib/api/client";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface SocialMedia {
|
||||||
|
facebook: string;
|
||||||
|
instagram: string;
|
||||||
|
telegram: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Operator {
|
export interface Operator {
|
||||||
id: number
|
id: number;
|
||||||
username: string
|
email: string;
|
||||||
name: string
|
name: string;
|
||||||
phone: string | null
|
firstName: string;
|
||||||
email: string | null
|
lastName: string;
|
||||||
isActive: boolean
|
username: string;
|
||||||
}
|
phone: string;
|
||||||
|
avatar: string;
|
||||||
export interface OperatorDetail extends Operator {
|
socialMedia: SocialMedia;
|
||||||
roles: OperatorRole[]
|
lightMode: number;
|
||||||
permissions: OperatorPermission[]
|
role: string;
|
||||||
branches: OperatorBranch[]
|
active: boolean;
|
||||||
loanLimits: OperatorLoanLimit[]
|
createdAt: string;
|
||||||
cardLimits: OperatorCardLimit[]
|
updatedAt: string;
|
||||||
auditLogs: OperatorAuditLog[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorRole {
|
|
||||||
id: number
|
|
||||||
code: string
|
|
||||||
name: string
|
|
||||||
guardName: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorPermission {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
guardName: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorBranch {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
region: string
|
|
||||||
district: string
|
|
||||||
uniqueCode: string
|
|
||||||
isActive: boolean
|
|
||||||
billingUsernameIbr: string
|
|
||||||
billingUsernameSber: string
|
|
||||||
billingUsernameVisa: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorLoanLimit {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
amount: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorCardLimit {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
amount: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OperatorAuditLog {
|
|
||||||
id: number
|
|
||||||
actionName: string
|
|
||||||
performedBy: string
|
|
||||||
target: string
|
|
||||||
status: string
|
|
||||||
createdAt: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorsListResponse {
|
export interface OperatorsListResponse {
|
||||||
data: Operator[]
|
count: number;
|
||||||
meta: {
|
users: Operator[];
|
||||||
currentPage: number
|
|
||||||
totalPages: number
|
|
||||||
totalCount: number
|
|
||||||
perPage: number
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateOperatorPayload {
|
export interface OperatorDetail extends Operator {
|
||||||
username: string
|
roles: OperatorRole[];
|
||||||
name: string
|
permissions: OperatorPermission[];
|
||||||
phone?: string
|
branches: OperatorBranch[];
|
||||||
email?: string
|
loanLimits: OperatorLoanLimit[];
|
||||||
password: string
|
cardLimits: OperatorCardLimit[];
|
||||||
isActive: boolean
|
auditLogs: OperatorAuditLog[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateOperatorPayload {
|
export interface OperatorRole {
|
||||||
username?: string
|
id: number;
|
||||||
name?: string
|
code: string;
|
||||||
phone?: string
|
name: string;
|
||||||
email?: string
|
guardName: string;
|
||||||
password?: string
|
}
|
||||||
isActive?: boolean
|
|
||||||
|
export interface OperatorPermission {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
guardName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorBranch {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
region: string;
|
||||||
|
district: string;
|
||||||
|
uniqueCode: string;
|
||||||
|
isActive: boolean;
|
||||||
|
billingUsernameIbr: string;
|
||||||
|
billingUsernameSber: string;
|
||||||
|
billingUsernameVisa: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorLoanLimit {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorCardLimit {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorAuditLog {
|
||||||
|
id: number;
|
||||||
|
actionName: string;
|
||||||
|
performedBy: string;
|
||||||
|
target: string;
|
||||||
|
status: string;
|
||||||
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OperatorsListParams {
|
export interface OperatorsListParams {
|
||||||
page?: number
|
page?: number;
|
||||||
perPage?: number
|
limit?: number;
|
||||||
search?: string
|
search?: string;
|
||||||
isActive?: string
|
isActive?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Mock Data & API ────────────────────────────────────────────────────────────
|
export interface CreateOperatorPayload {
|
||||||
|
active: boolean;
|
||||||
|
avatar: string;
|
||||||
|
email: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
lightMode: number;
|
||||||
|
name: string;
|
||||||
|
password: string;
|
||||||
|
phone: string;
|
||||||
|
role: string;
|
||||||
|
socialMedia: SocialMedia;
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
export interface UpdateOperatorPayload {
|
||||||
|
active?: boolean;
|
||||||
|
avatar?: string;
|
||||||
|
email?: string;
|
||||||
|
firstName?: string;
|
||||||
|
lastName?: string;
|
||||||
|
lightMode?: number;
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
role?: string;
|
||||||
|
socialMedia?: SocialMedia;
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
|
||||||
let mockOperators: OperatorDetail[] = [
|
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
username: 'johndoe',
|
|
||||||
name: 'John Doe',
|
|
||||||
phone: '+99365123456',
|
|
||||||
email: 'johndoe@example.com',
|
|
||||||
isActive: true,
|
|
||||||
roles: [{ id: 1, code: 'ADMIN', name: 'Administrator', guardName: 'web' }],
|
|
||||||
permissions: [{ id: 1, name: 'create_user', guardName: 'web' }],
|
|
||||||
branches: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
name: 'Main Branch',
|
|
||||||
region: 'Aşgabat',
|
|
||||||
district: 'Kopetdag',
|
|
||||||
uniqueCode: '01',
|
|
||||||
isActive: true,
|
|
||||||
billingUsernameIbr: 'ibr_1',
|
|
||||||
billingUsernameSber: 'sber_1',
|
|
||||||
billingUsernameVisa: 'visa_1',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
loanLimits: [{ id: 1, name: 'Consumer Loan', amount: 50000 }],
|
|
||||||
cardLimits: [{ id: 1, name: 'Credit Card', amount: 10000 }],
|
|
||||||
auditLogs: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
actionName: 'Login',
|
|
||||||
performedBy: 'System',
|
|
||||||
target: 'johndoe',
|
|
||||||
status: 'Success',
|
|
||||||
createdAt: '2023-10-27T10:00:00Z',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
username: 'janedoe',
|
|
||||||
name: 'Jane Doe',
|
|
||||||
phone: '+99365654321',
|
|
||||||
email: 'janedoe@example.com',
|
|
||||||
isActive: false,
|
|
||||||
roles: [{ id: 2, code: 'OPERATOR', name: 'Operator', guardName: 'web' }],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanLimits: [],
|
|
||||||
cardLimits: [],
|
|
||||||
auditLogs: [],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export const operatorsApi = {
|
export const operatorsApi = {
|
||||||
getAll: async (params: OperatorsListParams): Promise<OperatorsListResponse> => {
|
/** GET /users/staff — backend filters by `username` */
|
||||||
await delay(500)
|
getOperators: async (params: OperatorsListParams = {}, signal?: AbortSignal): Promise<OperatorsListResponse> => {
|
||||||
let filtered = [...mockOperators]
|
const { page, limit, search, isActive } = params;
|
||||||
if (params.search) {
|
const { data } = await apiClient.get<OperatorsListResponse>("/users/staff", {
|
||||||
const q = params.search.toLowerCase()
|
params: { page, limit, username: search, isActive },
|
||||||
filtered = filtered.filter(
|
signal,
|
||||||
(o) =>
|
});
|
||||||
o.name.toLowerCase().includes(q) ||
|
return data;
|
||||||
o.username.toLowerCase().includes(q)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
data: filtered,
|
|
||||||
meta: {
|
|
||||||
currentPage: params.page || 1,
|
|
||||||
totalPages: 1,
|
|
||||||
totalCount: filtered.length,
|
|
||||||
perPage: params.perPage || 10,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getById: async (id: number): Promise<OperatorDetail> => {
|
/** GET /users/:id */
|
||||||
await delay(500)
|
getOperatorById: async (id: number): Promise<OperatorDetail> => {
|
||||||
const op = mockOperators.find((o) => o.id === Number(id))
|
const { data } = await apiClient.get<OperatorDetail>(`/users/${id}`);
|
||||||
if (!op) throw new Error('Not found')
|
return data;
|
||||||
return op
|
|
||||||
},
|
},
|
||||||
|
|
||||||
create: async (payload: CreateOperatorPayload): Promise<Operator> => {
|
/** POST /users — same entity & payload as all users */
|
||||||
await delay(500)
|
createOperator: async (payload: CreateOperatorPayload): Promise<Operator> => {
|
||||||
const newOp: OperatorDetail = {
|
const { data } = await apiClient.post<Operator>("/users", payload);
|
||||||
id: mockOperators.length > 0 ? Math.max(...mockOperators.map((o) => o.id)) + 1 : 1,
|
return data;
|
||||||
...payload,
|
|
||||||
phone: payload.phone || null,
|
|
||||||
email: payload.email || null,
|
|
||||||
roles: [],
|
|
||||||
permissions: [],
|
|
||||||
branches: [],
|
|
||||||
loanLimits: [],
|
|
||||||
cardLimits: [],
|
|
||||||
auditLogs: [],
|
|
||||||
}
|
|
||||||
mockOperators.push(newOp)
|
|
||||||
return newOp
|
|
||||||
},
|
},
|
||||||
|
|
||||||
update: async (id: number, payload: UpdateOperatorPayload): Promise<Operator> => {
|
/** PUT /users/:id */
|
||||||
await delay(500)
|
updateOperator: async (id: number, payload: UpdateOperatorPayload): Promise<Operator> => {
|
||||||
const index = mockOperators.findIndex((o) => o.id === Number(id))
|
const { data } = await apiClient.put<Operator>(`/users/${id}`, payload);
|
||||||
if (index === -1) throw new Error('Not found')
|
return data;
|
||||||
mockOperators[index] = { ...mockOperators[index], ...payload }
|
|
||||||
return mockOperators[index]
|
|
||||||
},
|
},
|
||||||
|
|
||||||
delete: async (id: number): Promise<void> => {
|
/** DELETE /users/:id */
|
||||||
await delay(500)
|
deleteOperator: async (id: number): Promise<void> => {
|
||||||
mockOperators = mockOperators.filter((o) => o.id !== Number(id))
|
await apiClient.delete(`/users/${id}`);
|
||||||
},
|
},
|
||||||
|
};
|
||||||
assignRole: async (_operatorId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removeRole: async (_operatorId: number, _roleId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
assignPermission: async (_operatorId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
|
|
||||||
removePermission: async (_operatorId: number, _permissionId: number): Promise<void> => {
|
|
||||||
await delay(500)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
import { useMemo, useEffect, useCallback } from "react";
|
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
|
||||||
import { FormActions } from "@/components/formActions";
|
|
||||||
import { FormInput } from "@/components/formInput";
|
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 { useCreateOperator, useUpdateOperator } from "../hooks/useOperators";
|
import { useCreateOperator, useUpdateOperator } from "../hooks/useOperators";
|
||||||
import { operatorFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/operator.schema";
|
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||||
import type { OperatorFormData } from "../schemas/operator.schema";
|
|
||||||
import type { Operator } from "../api/operatorsApi";
|
import type { Operator } from "../api/operatorsApi";
|
||||||
|
import { operatorFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/operator.schema";
|
||||||
|
import type { OperatorFormData } from "../schemas/operator.schema";
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -41,13 +45,40 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
);
|
);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const createMutation = useCreateOperator();
|
const createOperator = useCreateOperator();
|
||||||
const updateMutation = useUpdateOperator(initialData?.id ?? 0);
|
const updateOperator = useUpdateOperator(initialData?.id ?? 0);
|
||||||
|
|
||||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
const isPending = createOperator.isPending || updateOperator.isPending;
|
||||||
|
|
||||||
const schema = useMemo(() => operatorFormSchema(mode, t), [mode, t, i18n.language]);
|
const schema = useMemo(() => operatorFormSchema(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 }));
|
||||||
|
|
||||||
|
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 {
|
const {
|
||||||
watch,
|
watch,
|
||||||
setValue,
|
setValue,
|
||||||
@@ -63,10 +94,18 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
...DEFAULT_FORM_VALUES,
|
...DEFAULT_FORM_VALUES,
|
||||||
username: initialData.username,
|
username: initialData.username,
|
||||||
name: initialData.name,
|
name: initialData.name,
|
||||||
phone: initialData.phone ?? "",
|
firstName: initialData.firstName ?? "",
|
||||||
|
lastName: initialData.lastName ?? "",
|
||||||
|
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||||
email: initialData.email ?? "",
|
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: "",
|
password: "",
|
||||||
isActive: initialData.isActive,
|
active: !!initialData.active,
|
||||||
}
|
}
|
||||||
: DEFAULT_FORM_VALUES,
|
: DEFAULT_FORM_VALUES,
|
||||||
});
|
});
|
||||||
@@ -87,7 +126,6 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [i18n.language]);
|
}, [i18n.language]);
|
||||||
|
|
||||||
// ── Submit ──────────────────────────────────────────────────────────────────
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
const isValid = await trigger();
|
const isValid = await trigger();
|
||||||
if (!isValid) return;
|
if (!isValid) return;
|
||||||
@@ -96,130 +134,196 @@ export function OperatorForm({ mode, initialData }: OperatorFormProps) {
|
|||||||
|
|
||||||
if (mode === "create") {
|
if (mode === "create") {
|
||||||
const payload = buildPayload(data);
|
const payload = buildPayload(data);
|
||||||
createMutation.mutate(payload, {
|
await createOperator.mutateAsync(payload);
|
||||||
onSuccess: () => navigate("/operators"),
|
navigate("/operators");
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
updateMutation.mutate(
|
const payload = buildUpdatePayload(data);
|
||||||
{
|
await updateOperator.mutateAsync(payload);
|
||||||
username: data.username.trim(),
|
navigate(`/operators/${initialData!.id}`);
|
||||||
name: data.name.trim(),
|
|
||||||
phone: data.phone.trim() || undefined,
|
|
||||||
email: data.email.trim() || undefined,
|
|
||||||
isActive: data.isActive,
|
|
||||||
...(data.password.trim() ? { password: data.password } : {}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: () => navigate(`/operators/${initialData!.id}`),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Render ──────────────────────────────────────────────────────────────────
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<h1 className="text-xl font-semibold text-foreground">
|
<h1 className="text-xl font-semibold text-foreground">
|
||||||
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
|
{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="bg-card border border-border rounded-xl overflow-hidden">
|
<BentoGrid cols={2}>
|
||||||
{/* Username */}
|
<BentoCard>
|
||||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
|
||||||
<span className="text-xs font-bold text-muted-foreground pt-2">
|
|
||||||
{t("operators.fields.username", "Ulanyjy ady")}
|
|
||||||
<span className="text-destructive ml-0.5">*</span>
|
|
||||||
</span>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
|
label={t("users.fields.username", "Ulanyjy ady")}
|
||||||
value={form.username}
|
value={form.username}
|
||||||
onChange={(v) => setField("username", v)}
|
onChange={(v) => setField("username", v)}
|
||||||
placeholder={t("operators.fields.username", "Ulanyjy ady")}
|
placeholder={t("users.fields.username", "Ulanyjy ady")}
|
||||||
error={errors.username}
|
error={errors.username}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
className="max-w-lg"
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.usernameHint", "Unikal login ady")}</p>
|
||||||
|
</BentoCard>
|
||||||
{/* Name */}
|
<BentoCard>
|
||||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
|
||||||
<span className="text-sm text-muted-foreground pt-2">
|
|
||||||
{t("operators.fields.name", "Ady")}
|
|
||||||
<span className="text-destructive ml-0.5">*</span>
|
|
||||||
</span>
|
|
||||||
<FormInput
|
<FormInput
|
||||||
type="text"
|
type="text"
|
||||||
|
label={t("users.fields.name", "Ady")}
|
||||||
value={form.name}
|
value={form.name}
|
||||||
onChange={(v) => setField("name", v)}
|
onChange={(v) => setField("name", v)}
|
||||||
placeholder={t("operators.fields.name", "Ady")}
|
placeholder={t("users.fields.name", "Ady")}
|
||||||
error={errors.name}
|
error={errors.name}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
className="max-w-lg"
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
|
||||||
|
</BentoCard>
|
||||||
{/* Phone */}
|
<BentoCard>
|
||||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
<FormInput
|
||||||
<span className="text-sm text-muted-foreground pt-2">{t("operators.fields.phone", "Telefon")}</span>
|
type="text"
|
||||||
<FormInput type="phone" value={form.phone} onChange={(v) => setField("phone", v)} disabled={isPending} className="max-w-lg" />
|
label={t("users.fields.firstName", "Ady (at)")}
|
||||||
</div>
|
value={form.firstName}
|
||||||
|
onChange={(v) => setField("firstName", v)}
|
||||||
{/* Email */}
|
placeholder={t("users.fields.firstName", "Ady (at)")}
|
||||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
error={errors.firstName}
|
||||||
<span className="text-sm text-muted-foreground pt-2">{t("operators.fields.email", "E-poçta")}</span>
|
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"
|
||||||
|
label={t("users.fields.phone", "Telefon")}
|
||||||
|
value={form.phone}
|
||||||
|
onChange={(v) => setField("phone", v)}
|
||||||
|
placeholder="62-38-49-56"
|
||||||
|
error={errors.phone}
|
||||||
|
disabled={isPending}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.phoneHint", "+993 bilen başlanýar")}</p>
|
||||||
|
</BentoCard>
|
||||||
|
<BentoCard>
|
||||||
<FormInput
|
<FormInput
|
||||||
type="email"
|
type="email"
|
||||||
|
label={t("users.fields.email", "E-poçta")}
|
||||||
value={form.email}
|
value={form.email}
|
||||||
onChange={(v) => setField("email", v)}
|
onChange={(v) => setField("email", v)}
|
||||||
placeholder={t("operators.fields.email", "E-poçta")}
|
placeholder={t("users.fields.email", "E-poçta")}
|
||||||
|
error={errors.email}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
className="max-w-lg"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
|
||||||
|
</BentoCard>
|
||||||
{/* Password */}
|
<BentoCard>
|
||||||
<div className="grid grid-cols-[220px_1fr] items-start py-4 px-6 border-b border-border">
|
<InfiniteSelect
|
||||||
<span className="text-sm text-muted-foreground pt-2">
|
label={t("users.fields.role", "Roly")}
|
||||||
{t("operators.fields.password", "Açar sözi")}
|
value={form.role}
|
||||||
{mode === "create" && <span className="text-destructive ml-0.5">*</span>}
|
onChange={(v) => setField("role", v)}
|
||||||
</span>
|
placeholder={t("users.fields.role", "Roly")}
|
||||||
<div className="max-w-lg space-y-1">
|
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
|
<FormInput
|
||||||
type="password"
|
type="password"
|
||||||
|
label={t("users.fields.password", "Açar sözi")}
|
||||||
value={form.password}
|
value={form.password}
|
||||||
onChange={(v) => setField("password", v)}
|
onChange={(v) => setField("password", v)}
|
||||||
placeholder={
|
placeholder={t("users.fields.password", "Açar sözi")}
|
||||||
mode === "edit"
|
|
||||||
? t("operators.fields.passwordEditHint", "Üýtgetmek üçin täze açar söz giriziň")
|
|
||||||
: t("operators.fields.password", "Açar sözi")
|
|
||||||
}
|
|
||||||
error={errors.password}
|
error={errors.password}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
|
required
|
||||||
/>
|
/>
|
||||||
{mode === "edit" && (
|
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.passwordHint", "Iň az 6 harp")}</p>
|
||||||
<p className="text-xs text-muted-foreground">{t("operators.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}</p>
|
</BentoCard>
|
||||||
)}
|
)}
|
||||||
|
<BentoCard>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div className="flex flex-col gap-3">
|
||||||
|
<FormInput
|
||||||
{/* isActive */}
|
type="text"
|
||||||
<div className="grid grid-cols-[220px_1fr] items-center py-4 px-6">
|
label={t("users.fields.facebook", "Facebook")}
|
||||||
<span className="text-sm text-muted-foreground">{t("operators.fields.isActive", "Işjeň")}</span>
|
value={form.socialFacebook}
|
||||||
<Checkbox
|
onChange={(v) => setField("socialFacebook", v)}
|
||||||
checked={form.isActive}
|
placeholder="facebook.com/..."
|
||||||
onCheckedChange={(v) => setField("isActive", !!v)}
|
error={errors.socialFacebook}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
/>
|
||||||
/>
|
<FormInput
|
||||||
</div>
|
type="text"
|
||||||
|
label={t("users.fields.instagram", "Instagram")}
|
||||||
<FormActions
|
value={form.socialInstagram}
|
||||||
isPending={isPending}
|
onChange={(v) => setField("socialInstagram", v)}
|
||||||
onSubmit={handleSubmit}
|
placeholder="instagram.com/..."
|
||||||
onCancel={() => navigate(-1)}
|
error={errors.socialInstagram}
|
||||||
submitLabel={mode === "create" ? t("operators.createBtn", "Operator döredin") : t("operators.updateBtn", "Üýtgetmeleri sakla")}
|
disabled={isPending}
|
||||||
className="px-6 py-4 border-t border-border bg-muted/20"
|
/>
|
||||||
/>
|
<FormInput
|
||||||
</div>
|
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>
|
||||||
|
<BentoCard>
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.isActive", "Işjeň")}</p>
|
||||||
|
<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="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>
|
||||||
|
</BentoGrid>
|
||||||
|
<FormActions
|
||||||
|
isPending={isPending}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
onCancel={() => navigate(-1)}
|
||||||
|
submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,31 +1,30 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner'
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||||
operatorsApi,
|
import { operatorsApi, type OperatorsListParams, type CreateOperatorPayload, type UpdateOperatorPayload } from "../api/operatorsApi";
|
||||||
type OperatorsListParams,
|
|
||||||
type CreateOperatorPayload,
|
|
||||||
type UpdateOperatorPayload,
|
|
||||||
} from '../api/operatorsApi'
|
|
||||||
|
|
||||||
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
// ─── Query Keys ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const operatorKeys = {
|
export const operatorKeys = {
|
||||||
all: ['operators'] as const,
|
all: ["operators"] as const,
|
||||||
lists: () => [...operatorKeys.all, 'list'] as const,
|
lists: () => [...operatorKeys.all, "list"] as const,
|
||||||
list: (params: OperatorsListParams) => [...operatorKeys.lists(), params] as const,
|
list: (params: OperatorsListParams) => [...operatorKeys.lists(), params] as const,
|
||||||
details: () => [...operatorKeys.all, 'detail'] as const,
|
details: () => [...operatorKeys.all, "detail"] as const,
|
||||||
detail: (id: number) => [...operatorKeys.details(), id] as const,
|
detail: (id: number) => [...operatorKeys.details(), id] as const,
|
||||||
}
|
};
|
||||||
|
|
||||||
// ─── useOperators ─────────────────────────────────────────────────────────────
|
// ─── useOperators ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useOperators(params: OperatorsListParams) {
|
export function useOperators(params: OperatorsListParams = {}) {
|
||||||
|
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||||
|
const queryParams: OperatorsListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: operatorKeys.list(params),
|
queryKey: operatorKeys.list(queryParams),
|
||||||
queryFn: () => operatorsApi.getAll(params),
|
queryFn: ({ signal }) => operatorsApi.getOperators(queryParams, signal),
|
||||||
placeholderData: (prev) => prev,
|
placeholderData: (prev) => prev,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useOperator ──────────────────────────────────────────────────────────────
|
// ─── useOperator ──────────────────────────────────────────────────────────────
|
||||||
@@ -33,81 +32,53 @@ export function useOperators(params: OperatorsListParams) {
|
|||||||
export function useOperator(id: number) {
|
export function useOperator(id: number) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: operatorKeys.detail(id),
|
queryKey: operatorKeys.detail(id),
|
||||||
queryFn: () => operatorsApi.getById(id),
|
queryFn: () => operatorsApi.getOperatorById(id),
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useCreateOperator ────────────────────────────────────────────────────────
|
// ─── useCreateOperator ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useCreateOperator() {
|
export function useCreateOperator() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: CreateOperatorPayload) => operatorsApi.create(payload),
|
mutationFn: (payload: CreateOperatorPayload) => operatorsApi.createOperator(payload),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() });
|
||||||
toast.success(t('operators.createSuccess', 'Operator üstünlikli döredildi'))
|
toast.success(t("operators.createSuccess", "Operator üstünlikli döredildi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useUpdateOperator ────────────────────────────────────────────────────────
|
// ─── useUpdateOperator ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useUpdateOperator(id: number) {
|
export function useUpdateOperator(id: number) {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (payload: UpdateOperatorPayload) => operatorsApi.update(id, payload),
|
mutationFn: (payload: UpdateOperatorPayload) => operatorsApi.updateOperator(id, payload),
|
||||||
onSuccess: () => {
|
onSuccess: (updatedOperator) => {
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() });
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(id) })
|
queryClient.setQueryData(operatorKeys.detail(id), updatedOperator);
|
||||||
toast.success(t('operators.updateSuccess', 'Operator üstünlikli täzelendi'))
|
toast.success(t("operators.updateSuccess", "Operator üstünlikli täzelendi"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── useDeleteOperator ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function useDeleteOperator() {
|
export function useDeleteOperator() {
|
||||||
const queryClient = useQueryClient()
|
const { t } = useTranslation();
|
||||||
const { t } = useTranslation()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (id: number) => operatorsApi.delete(id),
|
mutationFn: (id: number) => operatorsApi.deleteOperator(id),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() })
|
queryClient.invalidateQueries({ queryKey: operatorKeys.lists() });
|
||||||
toast.success(t('operators.deleteSuccess', 'Operator üstünlikli pozuldy'))
|
toast.success(t("operators.deleteSuccess", "Operator üstünlikli pozuldy"));
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── useAssignRole ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useAssignRole(operatorId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => operatorsApi.assignRole(operatorId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(operatorId) })
|
|
||||||
toast.success(t('operators.roleAssigned', 'Rol birikdirildi'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── useRemoveRole ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function useRemoveRole(operatorId: number) {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const { t } = useTranslation()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (roleId: number) => operatorsApi.removeRole(operatorId, roleId),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: operatorKeys.detail(operatorId) })
|
|
||||||
toast.success(t('operators.roleRemoved', 'Rol aýryldy'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,39 +1,50 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { CreateOperatorPayload } from "../api/operatorsApi";
|
import type { CreateOperatorPayload, UpdateOperatorPayload } from "../api/operatorsApi";
|
||||||
|
|
||||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
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 operatorFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
export function operatorFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||||
const baseSchema = z.object({
|
const baseSchema = z.object({
|
||||||
username: z.string().min(1, t("validation.required", "validation.required")),
|
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")),
|
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||||
|
firstName: z.string().default(""),
|
||||||
|
lastName: z.string().default(""),
|
||||||
phone: z
|
phone: z
|
||||||
.string()
|
.string()
|
||||||
|
.min(1, t("validation.required", "validation.required"))
|
||||||
.refine(
|
.refine(
|
||||||
(val) => {
|
(val) => {
|
||||||
if (!val) return true;
|
|
||||||
const digits = val.replace(/\D/g, "");
|
|
||||||
return digits.length === 8;
|
|
||||||
},
|
|
||||||
{ message: "validation.invalidPhone" },
|
|
||||||
)
|
|
||||||
.refine(
|
|
||||||
(val) => {
|
|
||||||
if (!val) return true;
|
|
||||||
const digits = val.replace(/\D/g, "");
|
const digits = val.replace(/\D/g, "");
|
||||||
return VALID_PHONE_PREFIXES.includes(digits.slice(0, 2));
|
return VALID_PHONE_PREFIXES.includes(digits.slice(0, 2));
|
||||||
},
|
},
|
||||||
{ message: "validation.invalidPhonePrefix" },
|
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
||||||
)
|
),
|
||||||
|
email: z
|
||||||
|
.string()
|
||||||
|
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
||||||
.default(""),
|
.default(""),
|
||||||
email: z.string().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(),
|
password: z.string(),
|
||||||
isActive: z.boolean(),
|
active: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
return mode === "create"
|
return mode === "create"
|
||||||
? baseSchema.extend({
|
? baseSchema.extend({
|
||||||
password: z.string().min(1, t("validation.required", "validation.required")),
|
password: z
|
||||||
|
.string()
|
||||||
|
.min(1, t("validation.required", "validation.required"))
|
||||||
|
.min(6, t("validation.minLength", "validation.minLength")),
|
||||||
})
|
})
|
||||||
: baseSchema;
|
: baseSchema;
|
||||||
}
|
}
|
||||||
@@ -43,19 +54,57 @@ export type OperatorFormData = z.infer<ReturnType<typeof operatorFormSchema>>;
|
|||||||
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
export const DEFAULT_FORM_VALUES: OperatorFormData = {
|
||||||
username: "",
|
username: "",
|
||||||
name: "",
|
name: "",
|
||||||
|
firstName: "",
|
||||||
|
lastName: "",
|
||||||
phone: "",
|
phone: "",
|
||||||
email: "",
|
email: "",
|
||||||
|
avatar: "",
|
||||||
|
role: "",
|
||||||
|
socialFacebook: "",
|
||||||
|
socialInstagram: "",
|
||||||
|
socialTelegram: "",
|
||||||
|
lightMode: false,
|
||||||
password: "",
|
password: "",
|
||||||
isActive: true,
|
active: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function buildPayload(data: OperatorFormData): CreateOperatorPayload {
|
export function buildPayload(data: OperatorFormData): CreateOperatorPayload {
|
||||||
return {
|
return {
|
||||||
username: data.username.trim(),
|
username: data.username.trim(),
|
||||||
name: data.name.trim(),
|
name: data.name.trim(),
|
||||||
phone: data.phone.trim() || undefined,
|
firstName: data.firstName.trim(),
|
||||||
email: data.email.trim() || undefined,
|
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,
|
password: data.password,
|
||||||
isActive: data.isActive,
|
active: data.active,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUpdatePayload(data: OperatorFormData): UpdateOperatorPayload {
|
||||||
|
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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+442
-50
@@ -3,12 +3,20 @@ import BankImage from "@/assets/bank-img.png";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { useLogin } from "@/features/auth/hooks/useLogin";
|
import { useLogin } from "@/features/auth/hooks/useLogin";
|
||||||
|
import { useRegister, useRegisterVerify } from "@/features/auth/hooks/useRegister";
|
||||||
|
import { useForgotPassword, useForgotPasswordVerify } from "@/features/auth/hooks/useForgotPassword";
|
||||||
import { useThemeStore } from "@/app/store/themeStore";
|
import { useThemeStore } from "@/app/store/themeStore";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Sun, Moon, Globe } from "lucide-react";
|
import { Sun, Moon, Globe, MessageSquare } from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { cleanPhoneNumber } from "@/lib/utils";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
type AuthView = "login" | "register" | "reset-password";
|
// ─── Auth view type ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type AuthView = "login" | "register" | "register-verify" | "forgot-password" | "forgot-password-verify";
|
||||||
|
|
||||||
|
// ─── LeftPanel ─────────────────────f───────────────────────────────────────────
|
||||||
|
|
||||||
function LeftPanel() {
|
function LeftPanel() {
|
||||||
return (
|
return (
|
||||||
@@ -18,6 +26,8 @@ function LeftPanel() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Header ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function Header() {
|
function Header() {
|
||||||
const { theme, toggleTheme } = useThemeStore();
|
const { theme, toggleTheme } = useThemeStore();
|
||||||
const { i18n } = useTranslation();
|
const { i18n } = useTranslation();
|
||||||
@@ -62,13 +72,15 @@ function Header() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FormInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange" | "value"> {
|
// ─── Simple FormInput (used in login / reset-password) ────────────────────────
|
||||||
|
|
||||||
|
interface SimpleFormInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange" | "value"> {
|
||||||
label: string;
|
label: string;
|
||||||
value: string;
|
value: string;
|
||||||
onChange: (val: string) => void;
|
onChange: (val: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function FormInput({ label, value, onChange, ...props }: FormInputProps) {
|
function FormInput({ label, value, onChange, ...props }: SimpleFormInputProps) {
|
||||||
return (
|
return (
|
||||||
<div className="mb-4">
|
<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>
|
||||||
@@ -82,30 +94,256 @@ function FormInput({ label, value, onChange, ...props }: FormInputProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── PhoneInput (matches the existing formInput.tsx component pattern) ────────
|
||||||
|
|
||||||
|
interface PhoneInputFieldProps {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (val: string) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function PhoneInputField({ label, value, onChange, disabled }: PhoneInputFieldProps) {
|
||||||
|
const cleanedDigits = cleanPhoneNumber(value);
|
||||||
|
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const digits = e.target.value.replace(/\D/g, "").slice(0, 8);
|
||||||
|
if (digits.length <= 2) {
|
||||||
|
onChange(digits);
|
||||||
|
} else {
|
||||||
|
onChange(`${digits.slice(0, 2)} ${digits.slice(2)}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formattedDisplayValue = cleanedDigits.length <= 2 ? cleanedDigits : `${cleanedDigits.slice(0, 2)} ${cleanedDigits.slice(2)}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-4">
|
||||||
|
<label className="block text-[13px] font-medium text-foreground mb-1.5">{label}</label>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex h-11 w-full rounded-md border bg-background overflow-hidden",
|
||||||
|
"ring-offset-background transition-colors duration-150",
|
||||||
|
"focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-0",
|
||||||
|
"border-input",
|
||||||
|
disabled && "opacity-50 cursor-not-allowed",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center px-3 bg-muted/50 border-r border-input text-sm font-medium text-muted-foreground shrink-0 select-none">
|
||||||
|
+993
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={formattedDisplayValue}
|
||||||
|
onChange={handleChange}
|
||||||
|
placeholder="61 097651"
|
||||||
|
disabled={disabled}
|
||||||
|
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none disabled:cursor-not-allowed"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── AuthPage ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function AuthPage() {
|
export default function AuthPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
// Mutations
|
||||||
const loginMutation = useLogin();
|
const loginMutation = useLogin();
|
||||||
|
const registerMutation = useRegister();
|
||||||
|
const registerVerifyMutation = useRegisterVerify();
|
||||||
|
const forgotPasswordMutation = useForgotPassword();
|
||||||
|
const forgotPasswordVerifyMutation = useForgotPasswordVerify();
|
||||||
|
|
||||||
|
// View
|
||||||
const [view, setView] = useState<AuthView>("login");
|
const [view, setView] = useState<AuthView>("login");
|
||||||
const [username, setUsername] = useState("");
|
|
||||||
|
// Login fields
|
||||||
|
const [identifier, setIdentifier] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
|
||||||
const [phone, setPhone] = useState("");
|
// Register fields
|
||||||
const [fullName, setFullName] = useState("");
|
const [regName, setRegName] = useState("");
|
||||||
|
const [regPhone, setRegPhone] = useState("");
|
||||||
|
const [regUsername, setRegUsername] = useState("");
|
||||||
|
const [regPassword, setRegPassword] = useState("");
|
||||||
|
const [regPasswordConfirm, setRegPasswordConfirm] = useState("");
|
||||||
|
|
||||||
|
// SMS verification
|
||||||
|
const [smsCode, setSmsCode] = useState("");
|
||||||
|
|
||||||
|
// Forgot password fields
|
||||||
|
const [forgotName, setForgotName] = useState("");
|
||||||
|
const [forgotCode, setForgotCode] = useState("");
|
||||||
|
const [forgotPassword, setForgotPassword] = useState("");
|
||||||
|
const [forgotPasswordConfirm, setForgotPasswordConfirm] = useState("");
|
||||||
|
|
||||||
|
// ── Login ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Returns true if the identifier looks like a phone number (only digits / spaces)
|
||||||
|
const identifierIsPhone = (val: string) => /^[\d\s]*$/.test(val) && val.replace(/\D/g, "").length > 0;
|
||||||
|
|
||||||
|
const handleIdentifierChange = (raw: string) => {
|
||||||
|
// If the new value is all digits/spaces → apply phone formatting (XX XXXXXX, max 8 digits)
|
||||||
|
if (/^[\d\s]*$/.test(raw)) {
|
||||||
|
const digits = raw.replace(/\D/g, "").slice(0, 8);
|
||||||
|
if (digits.length <= 2) {
|
||||||
|
setIdentifier(digits);
|
||||||
|
} else {
|
||||||
|
setIdentifier(`${digits.slice(0, 2)} ${digits.slice(2)}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Username mode — allow any chars but strip leading/trailing spaces
|
||||||
|
setIdentifier(raw);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleLogin = () => {
|
const handleLogin = () => {
|
||||||
if (!username || !password) {
|
if (!identifier || !password) {
|
||||||
toast.error(t("Write a correct data please", "Please enter valid data"));
|
toast.error(t("Write a correct data please", "Please enter valid data"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
loginMutation.mutate({ email: username, password });
|
const digits = identifier.replace(/\D/g, "");
|
||||||
|
const isPhone = identifierIsPhone(identifier);
|
||||||
|
|
||||||
|
loginMutation.mutate(isPhone ? { phone: `+993${digits}`, password } : { name: identifier.trim(), password });
|
||||||
};
|
};
|
||||||
|
|
||||||
// Mock submit for other views
|
// ── Register step 1 ────────────────────────────────────────────────────────
|
||||||
const handleOtherSubmit = async () => {
|
|
||||||
toast.info(t("featureNotImplemented", "This feature is not implemented yet"));
|
const handleRegister = () => {
|
||||||
|
const digits = cleanPhoneNumber(regPhone);
|
||||||
|
if (!regName || !regPhone || !regUsername || !regPassword || !regPasswordConfirm) {
|
||||||
|
toast.error(t("Please fill in all fields", "Ähli meýdançalary dolduryň"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (digits.length !== 8) {
|
||||||
|
toast.error(t("Phone number must be 8 digits", "Telefon belgisi 8 san bolmaly"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (regPassword !== regPasswordConfirm) {
|
||||||
|
toast.error(t("Passwords do not match", "Açar sözler gabat gelmeýär"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerMutation.mutate(
|
||||||
|
{
|
||||||
|
name: regName,
|
||||||
|
username: regUsername,
|
||||||
|
phone: `+993${digits}`,
|
||||||
|
password: regPassword,
|
||||||
|
passwordConfirm: regPasswordConfirm,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success(t("SMS code sent", "SMS kody iberildi"));
|
||||||
|
setView("register-verify");
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(t("Registration failed", "Hasaba alyş başa barmady"));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ── Register step 2: SMS verify ────────────────────────────────────────────
|
||||||
|
|
||||||
|
const handleVerify = () => {
|
||||||
|
const digits = cleanPhoneNumber(regPhone);
|
||||||
|
if (!smsCode) {
|
||||||
|
toast.error(t("Please enter the SMS code", "SMS kodyny giriziň"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerVerifyMutation.mutate(
|
||||||
|
{ code: smsCode, phone: `+993${digits}` },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success(t("Registration successful!", "Hasaba alyş üstünlikli!"));
|
||||||
|
// Reset register state and go to login
|
||||||
|
setRegName("");
|
||||||
|
setRegPhone("");
|
||||||
|
setRegUsername("");
|
||||||
|
setRegPassword("");
|
||||||
|
setRegPasswordConfirm("");
|
||||||
|
setSmsCode("");
|
||||||
|
setView("login");
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(t("Invalid SMS code", "SMS kody ýalňyş"));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Forgot password step 1 ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const handleForgotPassword = () => {
|
||||||
|
if (!forgotName) {
|
||||||
|
toast.error(t("Please enter your username", "Ulanyjy adyňyzy giriziň"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
forgotPasswordMutation.mutate(
|
||||||
|
{ name: forgotName },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success(t("SMS code sent", "SMS kody iberildi"));
|
||||||
|
setView("forgot-password-verify");
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(t("User not found", "Ulanyjy tapylmady"));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Forgot password step 2: new password ──────────────────────────────────
|
||||||
|
|
||||||
|
const handleForgotPasswordVerify = () => {
|
||||||
|
if (!forgotCode || !forgotPassword || !forgotPasswordConfirm) {
|
||||||
|
toast.error(t("Please fill in all fields", "Ähli meýdançalary dolduryň"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (forgotPassword !== forgotPasswordConfirm) {
|
||||||
|
toast.error(t("Passwords do not match", "Açar sözler gabat gelmeýär"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
forgotPasswordVerifyMutation.mutate(
|
||||||
|
{
|
||||||
|
code: forgotCode,
|
||||||
|
name: forgotName,
|
||||||
|
password: forgotPassword,
|
||||||
|
passwordConfirm: forgotPasswordConfirm,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success(t("Password reset successful!", "Açar söz üstünlikli üýtgedildi!"));
|
||||||
|
setForgotName("");
|
||||||
|
setForgotCode("");
|
||||||
|
setForgotPassword("");
|
||||||
|
setForgotPasswordConfirm("");
|
||||||
|
setView("login");
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error(t("Invalid code or data", "Ýalňyş kod ýa-da maglumat"));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Privacy policy link ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const PrivacyLink = () => (
|
||||||
|
<div className="text-center mt-8">
|
||||||
|
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
|
||||||
|
{t("Privacy Policy")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-screen bg-background text-foreground font-sans">
|
<div className="flex flex-col h-screen bg-background text-foreground font-sans">
|
||||||
<Header />
|
<Header />
|
||||||
@@ -115,6 +353,7 @@ export default function AuthPage() {
|
|||||||
<div className="w-full md:w-[45%] flex flex-col bg-background">
|
<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="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]">
|
<div className="w-full max-w-[400px]">
|
||||||
|
{/* ── LOGIN ── */}
|
||||||
{view === "login" && (
|
{view === "login" && (
|
||||||
<>
|
<>
|
||||||
<h2 className="text-[22px] font-normal text-foreground text-center mb-2 tracking-wide uppercase">
|
<h2 className="text-[22px] font-normal text-foreground text-center mb-2 tracking-wide uppercase">
|
||||||
@@ -122,12 +361,38 @@ export default function AuthPage() {
|
|||||||
</h2>
|
</h2>
|
||||||
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||||
|
|
||||||
<FormInput
|
{/* Smart phone / username input */}
|
||||||
label={t("Phone or username", "Telefon ýada ulanyjy ady")}
|
<div className="mb-4">
|
||||||
value={username}
|
<label className="block text-[13px] font-medium text-foreground mb-1.5">
|
||||||
onChange={setUsername}
|
{t("Phone or name", "Telefon ýa-da ulanyjy ady")}
|
||||||
placeholder="65999990 ýada ulanyjy_ady"
|
</label>
|
||||||
/>
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex h-11 w-full rounded-md border bg-background overflow-hidden",
|
||||||
|
"ring-offset-background transition-colors duration-150",
|
||||||
|
"focus-within:outline-none focus-within:ring-2 focus-within:ring-primary focus-within:ring-offset-0 border-input",
|
||||||
|
loginMutation.isPending && "opacity-50 cursor-not-allowed",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{identifierIsPhone(identifier) && (
|
||||||
|
<div className="flex items-center px-3 bg-muted/50 border-r border-input text-sm font-medium text-muted-foreground shrink-0 select-none transition-all">
|
||||||
|
+993
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode={identifierIsPhone(identifier) ? "numeric" : "text"}
|
||||||
|
value={identifier}
|
||||||
|
onChange={(e) => handleIdentifierChange(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleLogin();
|
||||||
|
}}
|
||||||
|
placeholder={t("61 097651 or name", "61 097651 ýa-da ulanyjy_ady")}
|
||||||
|
disabled={loginMutation.isPending}
|
||||||
|
className="flex-1 h-full px-3 bg-transparent text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none disabled:cursor-not-allowed"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<FormInput
|
<FormInput
|
||||||
label={t("Password")}
|
label={t("Password")}
|
||||||
type="password"
|
type="password"
|
||||||
@@ -136,10 +401,11 @@ export default function AuthPage() {
|
|||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter") handleLogin();
|
if (e.key === "Enter") handleLogin();
|
||||||
}}
|
}}
|
||||||
|
disabled={loginMutation.isPending}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="text-right mb-6 -mt-2">
|
<div className="text-right mb-6 -mt-2">
|
||||||
<span onClick={() => setView("reset-password")} className="text-[13px] text-primary cursor-pointer hover:underline">
|
<span onClick={() => setView("forgot-password")} className="text-[13px] text-primary cursor-pointer hover:underline">
|
||||||
{t("Forgot your password?")}
|
{t("Forgot your password?")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -153,65 +419,191 @@ export default function AuthPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-center mt-8">
|
<PrivacyLink />
|
||||||
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
|
|
||||||
{t("Privacy Policy")}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* ── REGISTER (step 1) ── */}
|
||||||
{view === "register" && (
|
{view === "register" && (
|
||||||
<>
|
<>
|
||||||
<h2 className="text-xl font-normal text-foreground text-center mb-2">{t("Online panel", "Onlaýn kabulhana")}</h2>
|
<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" />
|
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||||
|
|
||||||
<FormInput label={t("Full Name")} value={fullName} onChange={setFullName} />
|
<FormInput
|
||||||
<FormInput label={t("Phone")} value={phone} onChange={setPhone} />
|
label={t("Full Name")}
|
||||||
<FormInput label={t("Username")} value={username} onChange={setUsername} />
|
value={regName}
|
||||||
<FormInput label={t("Password")} type="password" value={password} onChange={setPassword} />
|
onChange={setRegName}
|
||||||
<FormInput label={t("Confirm Password")} type="password" value={confirmPassword} onChange={setConfirmPassword} />
|
placeholder={t("Full Name", "Doly adyňyz")}
|
||||||
|
disabled={registerMutation.isPending}
|
||||||
|
/>
|
||||||
|
<PhoneInputField label={t("Phone")} value={regPhone} onChange={setRegPhone} disabled={registerMutation.isPending} />
|
||||||
|
<FormInput
|
||||||
|
label={t("Username")}
|
||||||
|
value={regUsername}
|
||||||
|
onChange={setRegUsername}
|
||||||
|
placeholder={t("Username", "Ulanyjy ady")}
|
||||||
|
disabled={registerMutation.isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
label={t("Password")}
|
||||||
|
type="password"
|
||||||
|
value={regPassword}
|
||||||
|
onChange={setRegPassword}
|
||||||
|
disabled={registerMutation.isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
label={t("Confirm Password")}
|
||||||
|
type="password"
|
||||||
|
value={regPasswordConfirm}
|
||||||
|
onChange={setRegPasswordConfirm}
|
||||||
|
disabled={registerMutation.isPending}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="flex flex-col gap-3 mt-4">
|
<div className="flex flex-col gap-3 mt-4">
|
||||||
<Button onClick={handleOtherSubmit} className="h-11">
|
<Button onClick={handleRegister} disabled={registerMutation.isPending} className="h-11">
|
||||||
{t("Register")}
|
{registerMutation.isPending ? t("Loading") + "..." : t("Register")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={() => setView("login")} className="h-11">
|
<Button variant="outline" onClick={() => setView("login")} disabled={registerMutation.isPending} className="h-11">
|
||||||
{t("Go to login page")}
|
{t("Go to login page")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-center mt-8">
|
<PrivacyLink />
|
||||||
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
|
|
||||||
{t("Privacy Policy")}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{view === "reset-password" && (
|
{/* ── REGISTER VERIFY (step 2 – SMS OTP) ── */}
|
||||||
|
{view === "register-verify" && (
|
||||||
<>
|
<>
|
||||||
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">
|
<div className="flex flex-col items-center mb-6">
|
||||||
{t("Enter your username to continue")}
|
<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-3">
|
||||||
</h2>
|
<MessageSquare size={22} className="text-primary" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl font-normal text-foreground text-center mb-1">{t("SMS Verification", "SMS Tassyklamasy")}</h2>
|
||||||
|
<p className="text-[13px] text-muted-foreground text-center">
|
||||||
|
{t("Enter the code sent to", "Iberilen kody giriziň")}{" "}
|
||||||
|
<span className="font-semibold text-foreground">+993 {regPhone}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||||
|
|
||||||
<FormInput label={t("Username")} value={username} onChange={setUsername} />
|
<FormInput
|
||||||
|
label={t("SMS Code", "SMS Kody")}
|
||||||
|
value={smsCode}
|
||||||
|
onChange={setSmsCode}
|
||||||
|
placeholder="______"
|
||||||
|
maxLength={6}
|
||||||
|
disabled={registerVerifyMutation.isPending}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleVerify();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-3 mt-4">
|
||||||
|
<Button onClick={handleVerify} disabled={registerVerifyMutation.isPending} className="h-11">
|
||||||
|
{registerVerifyMutation.isPending ? t("Loading") + "..." : t("Verify", "Tassykla")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setView("register")}
|
||||||
|
disabled={registerVerifyMutation.isPending}
|
||||||
|
className="h-11"
|
||||||
|
>
|
||||||
|
{t("Back", "Yza")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<PrivacyLink />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* ── FORGOT PASSWORD (step 1) ── */}
|
||||||
|
{view === "forgot-password" && (
|
||||||
|
<>
|
||||||
|
<h2 className="text-lg font-normal text-foreground text-center mb-2 leading-relaxed">{t("Forgot your password?")}</h2>
|
||||||
|
<p className="text-[13px] text-muted-foreground text-center mb-5">
|
||||||
|
{t("Enter your username to receive a reset code", "Täzeden açar söz üçin ulanyjy adyňyzy giriziň")}
|
||||||
|
</p>
|
||||||
|
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||||
|
|
||||||
|
<FormInput
|
||||||
|
label={t("Username")}
|
||||||
|
value={forgotName}
|
||||||
|
onChange={setForgotName}
|
||||||
|
disabled={forgotPasswordMutation.isPending}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleForgotPassword();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="mt-4 flex flex-col gap-3">
|
<div className="mt-4 flex flex-col gap-3">
|
||||||
<Button onClick={handleOtherSubmit} className="h-11">
|
<Button onClick={handleForgotPassword} disabled={forgotPasswordMutation.isPending} className="h-11">
|
||||||
{t("Submit")}
|
{forgotPasswordMutation.isPending ? t("Loading") + "..." : t("Submit")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={() => setView("login")} className="h-11">
|
<Button variant="outline" onClick={() => setView("login")} disabled={forgotPasswordMutation.isPending} className="h-11">
|
||||||
{t("Go to login page")}
|
{t("Go to login page")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-center mt-8">
|
<PrivacyLink />
|
||||||
<span className="text-[13px] text-muted-foreground underline cursor-pointer hover:text-foreground transition-colors">
|
</>
|
||||||
{t("Privacy Policy")}
|
)}
|
||||||
</span>
|
|
||||||
|
{/* ── FORGOT PASSWORD VERIFY (step 2) ── */}
|
||||||
|
{view === "forgot-password-verify" && (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col items-center mb-6">
|
||||||
|
<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-3">
|
||||||
|
<MessageSquare size={22} className="text-primary" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl font-normal text-foreground text-center mb-1">{t("Reset Password", "Açar sözi täzele")}</h2>
|
||||||
|
<p className="text-[13px] text-muted-foreground text-center">
|
||||||
|
{t("Enter the SMS code and your new password", "SMS kodyny we täze açar söziňizi giriziň")}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="w-14 h-0.5 bg-primary mx-auto mb-7" />
|
||||||
|
|
||||||
|
<FormInput
|
||||||
|
label={t("SMS Code", "SMS Kody")}
|
||||||
|
value={forgotCode}
|
||||||
|
onChange={setForgotCode}
|
||||||
|
placeholder="______"
|
||||||
|
maxLength={6}
|
||||||
|
disabled={forgotPasswordVerifyMutation.isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
label={t("New Password", "Täze açar söz")}
|
||||||
|
type="password"
|
||||||
|
value={forgotPassword}
|
||||||
|
onChange={setForgotPassword}
|
||||||
|
disabled={forgotPasswordVerifyMutation.isPending}
|
||||||
|
/>
|
||||||
|
<FormInput
|
||||||
|
label={t("Confirm New Password", "Täze açar sözi tassykla")}
|
||||||
|
type="password"
|
||||||
|
value={forgotPasswordConfirm}
|
||||||
|
onChange={setForgotPasswordConfirm}
|
||||||
|
disabled={forgotPasswordVerifyMutation.isPending}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleForgotPasswordVerify();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="mt-4 flex flex-col gap-3">
|
||||||
|
<Button onClick={handleForgotPasswordVerify} disabled={forgotPasswordVerifyMutation.isPending} className="h-11">
|
||||||
|
{forgotPasswordVerifyMutation.isPending ? t("Loading") + "..." : t("Reset Password", "Açar sözi täzele")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setView("forgot-password")}
|
||||||
|
disabled={forgotPasswordVerifyMutation.isPending}
|
||||||
|
className="h-11"
|
||||||
|
>
|
||||||
|
{t("Back", "Yza")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<PrivacyLink />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -27,14 +27,14 @@ export default function ClientsPage() {
|
|||||||
|
|
||||||
const { data, isLoading } = useClients({
|
const { data, isLoading } = useClients({
|
||||||
page,
|
page,
|
||||||
perPage,
|
limit: perPage,
|
||||||
search: search || undefined,
|
search: search || undefined,
|
||||||
isActive: isActiveFilter || undefined,
|
isActive: isActiveFilter || undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
const clients = data?.data ?? [];
|
const clients = data?.users ?? [];
|
||||||
const totalPages = data?.meta.totalPages ?? 1;
|
const totalCount = data?.count ?? 0;
|
||||||
const totalCount = data?.meta.totalCount ?? 0;
|
const totalPages = Math.max(1, Math.ceil(totalCount / perPage));
|
||||||
|
|
||||||
const columns: ColumnDef<Client>[] = [
|
const columns: ColumnDef<Client>[] = [
|
||||||
{
|
{
|
||||||
@@ -71,14 +71,10 @@ export default function ClientsPage() {
|
|||||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
|
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "isActive",
|
accessorKey: "active",
|
||||||
header: t("clients.fields.isActive", "IŞJEŇ"),
|
header: t("clients.fields.isActive", "IŞJEŇ"),
|
||||||
cell: ({ row }) =>
|
cell: ({ row }) =>
|
||||||
row.original.isActive ? (
|
row.original.active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />,
|
||||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle size={18} className="text-destructive" />
|
|
||||||
),
|
|
||||||
size: 80,
|
size: 80,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,71 +1,67 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from "react";
|
||||||
import { useParams, useNavigate } from 'react-router-dom'
|
import { useParams, useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from "react-i18next";
|
||||||
import { Pencil, Trash2, XCircle, CheckCircle2 } from 'lucide-react'
|
import { Pencil, Trash2, XCircle, CheckCircle2 } from "lucide-react";
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from "@/components/ui/button";
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { ConfirmDialog } from '@/components/confirmDialog'
|
import { ConfirmDialog } from "@/components/confirmDialog";
|
||||||
import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from '@/components/viewPageComponents'
|
import { BentoGrid, BentoCard, InfoRow, AuditLog, CollapsibleSection, EmptyState } from "@/components/viewPageComponents";
|
||||||
import { DataTable, type ColumnDef } from '@/components/dataTable'
|
import { DataTable, type ColumnDef } from "@/components/dataTable";
|
||||||
import { DataTableToolbar } from '@/components/dataTableToolbar'
|
import { DataTableToolbar } from "@/components/dataTableToolbar";
|
||||||
import { useClient, useDeleteClient } from '@/features/clients/hooks/useClients'
|
import { useClient, useDeleteClient } from "@/features/clients/hooks/useClients";
|
||||||
import type { ClientRole, ClientBranch, ClientAuditLog } from '@/features/clients/api/clientsApi'
|
import type { ClientRole, ClientBranch, ClientAuditLog } from "@/features/clients/api/clientsApi";
|
||||||
|
|
||||||
// ─── ActiveIndicator ──────────────────────────────────────────────────────────
|
// ─── ActiveIndicator ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function ActiveIndicator({ active }: { active: boolean }) {
|
function ActiveIndicator({ active }: { active: boolean }) {
|
||||||
return active ? (
|
return active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />;
|
||||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle size={18} className="text-destructive" />
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export default function ClientDetailPage() {
|
export default function ClientDetailPage() {
|
||||||
const { id } = useParams<{ id: string }>()
|
const { id } = useParams<{ id: string }>();
|
||||||
const clientId = Number(id)
|
const clientId = Number(id);
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate();
|
||||||
const deleteMutation = useDeleteClient()
|
const deleteMutation = useDeleteClient();
|
||||||
|
|
||||||
const { data: client, isLoading } = useClient(clientId)
|
const { data: client, isLoading } = useClient(clientId);
|
||||||
|
|
||||||
const [deleteOpen, setDeleteOpen] = useState(false)
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
const [roleSearch, setRoleSearch] = useState('')
|
const [roleSearch, setRoleSearch] = useState("");
|
||||||
const [permSearch, setPermSearch] = useState('')
|
const [permSearch, setPermSearch] = useState("");
|
||||||
const [branchSearch, setBranchSearch] = useState('')
|
const [branchSearch, setBranchSearch] = useState("");
|
||||||
const [loanSearch, setLoanSearch] = useState('')
|
const [loanSearch, setLoanSearch] = useState("");
|
||||||
const [cardSearch, setCardSearch] = useState('')
|
const [cardSearch, setCardSearch] = useState("");
|
||||||
|
|
||||||
// ── Role columns ──────────────────────────────────────────────────────────
|
// ── Role columns ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const roleColumns: ColumnDef<ClientRole>[] = [
|
const roleColumns: ColumnDef<ClientRole>[] = [
|
||||||
{
|
{
|
||||||
accessorKey: 'id',
|
accessorKey: "id",
|
||||||
header: t('common.id', 'ID'),
|
header: t("common.id", "ID"),
|
||||||
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
|
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
|
||||||
size: 80,
|
size: 80,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'code',
|
accessorKey: "code",
|
||||||
header: t('roles.fields.code', 'KOD'),
|
header: t("roles.fields.code", "KOD"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.code}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'name',
|
accessorKey: "name",
|
||||||
header: t('roles.fields.name', 'ADY'),
|
header: t("roles.fields.name", "ADY"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'guardName',
|
accessorKey: "guardName",
|
||||||
header: t('roles.fields.guardName', 'GUARD NAME'),
|
header: t("roles.fields.guardName", "GUARD NAME"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.guardName}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actions',
|
id: "actions",
|
||||||
header: '',
|
header: "",
|
||||||
cell: () => (
|
cell: () => (
|
||||||
<div className="flex items-center gap-1 justify-end">
|
<div className="flex items-center gap-1 justify-end">
|
||||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
|
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
|
||||||
@@ -75,40 +71,40 @@ export default function ClientDetailPage() {
|
|||||||
),
|
),
|
||||||
size: 60,
|
size: 60,
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
|
||||||
// ── Branch columns ────────────────────────────────────────────────────────
|
// ── Branch columns ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const branchColumns: ColumnDef<ClientBranch>[] = [
|
const branchColumns: ColumnDef<ClientBranch>[] = [
|
||||||
{
|
{
|
||||||
accessorKey: 'id',
|
accessorKey: "id",
|
||||||
header: t('common.id', 'ID'),
|
header: t("common.id", "ID"),
|
||||||
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
|
cell: ({ row }) => <span className="text-primary font-semibold text-sm">{row.original.id}</span>,
|
||||||
size: 60,
|
size: 60,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'name',
|
accessorKey: "name",
|
||||||
header: t('branches.fields.name', 'ADY'),
|
header: t("branches.fields.name", "ADY"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.name}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'region',
|
accessorKey: "region",
|
||||||
header: t('branches.fields.region', 'WELAÝAT'),
|
header: t("branches.fields.region", "WELAÝAT"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.region}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'district',
|
accessorKey: "district",
|
||||||
header: t('branches.fields.district', 'ETRAP'),
|
header: t("branches.fields.district", "ETRAP"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.district}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'uniqueCode',
|
accessorKey: "uniqueCode",
|
||||||
header: t('branches.fields.uniqueCode', 'UNIKAL BELGI'),
|
header: t("branches.fields.uniqueCode", "UNIKAL BELGI"),
|
||||||
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
|
cell: ({ row }) => <span className="text-sm">{row.original.uniqueCode}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'actions',
|
id: "actions",
|
||||||
header: '',
|
header: "",
|
||||||
cell: () => (
|
cell: () => (
|
||||||
<div className="flex items-center gap-1 justify-end">
|
<div className="flex items-center gap-1 justify-end">
|
||||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
|
<Button size="icon" variant="ghost" className="h-7 w-7 text-muted-foreground hover:text-destructive">
|
||||||
@@ -118,7 +114,7 @@ export default function ClientDetailPage() {
|
|||||||
),
|
),
|
||||||
size: 60,
|
size: 60,
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
|
|
||||||
// ── Loading ───────────────────────────────────────────────────────────────
|
// ── Loading ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -137,46 +133,44 @@ export default function ClientDetailPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!client) return null
|
if (!client) return null;
|
||||||
|
|
||||||
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
|
const auditLogs = (client.auditLogs ?? []).map((log: ClientAuditLog) => ({
|
||||||
id: String(log.id),
|
id: String(log.id),
|
||||||
action: log.actionName,
|
action: log.actionName,
|
||||||
by: log.performedBy,
|
by: log.performedBy,
|
||||||
target: log.target,
|
target: log.target,
|
||||||
status: log.status,
|
status: log.status,
|
||||||
date: log.createdAt,
|
date: log.createdAt,
|
||||||
}))
|
}));
|
||||||
|
|
||||||
const filteredRoles = (client.roles ?? []).filter((r) =>
|
const filteredRoles = (client.roles ?? []).filter(
|
||||||
r.name.toLowerCase().includes(roleSearch.toLowerCase()) ||
|
(r) => r.name.toLowerCase().includes(roleSearch.toLowerCase()) || r.code.toLowerCase().includes(roleSearch.toLowerCase()),
|
||||||
r.code.toLowerCase().includes(roleSearch.toLowerCase()),
|
);
|
||||||
)
|
const filteredBranches = (client.branches ?? []).filter((b) => b.name.toLowerCase().includes(branchSearch.toLowerCase()));
|
||||||
const filteredBranches = (client.branches ?? []).filter((b) =>
|
|
||||||
b.name.toLowerCase().includes(branchSearch.toLowerCase()),
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className=" flex flex-col gap-6">
|
<div className=" flex flex-col gap-6">
|
||||||
|
|
||||||
{/* ── Page header ──────────────────────────────────────────────────── */}
|
{/* ── Page header ──────────────────────────────────────────────────── */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-semibold text-foreground">
|
<h1 className="text-2xl font-semibold text-foreground">
|
||||||
{t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name}
|
{t("clients.detailTitle", "Müşderi giňişleýin")}: {client.name}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
<Button
|
||||||
size="icon" variant="ghost"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||||
onClick={() => setDeleteOpen(true)}
|
onClick={() => setDeleteOpen(true)}
|
||||||
>
|
>
|
||||||
<Trash2 size={15} />
|
<Trash2 size={15} />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
size="icon" variant="ghost"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||||
onClick={() => navigate(`/clients/${clientId}/edit`)}
|
onClick={() => navigate(`/clients/${clientId}/edit`)}
|
||||||
>
|
>
|
||||||
@@ -187,114 +181,117 @@ export default function ClientDetailPage() {
|
|||||||
|
|
||||||
{/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
|
{/* ── Row 1: Esasy maglumatlar + Kontakt ──────────────────────────── */}
|
||||||
<BentoGrid cols={2}>
|
<BentoGrid cols={2}>
|
||||||
<BentoCard title={t('clients.sections.basic', 'Esasy maglumatlar')}>
|
<BentoCard title={t("clients.sections.basic", "Esasy maglumatlar")}>
|
||||||
<InfoRow label={t('common.id', 'ID')} value={client.id} />
|
<InfoRow label={t("common.id", "ID")} value={client.id} />
|
||||||
<InfoRow
|
<InfoRow label={t("clients.fields.username", "Ulanyjy ady")} value={client.username} />
|
||||||
label={t('clients.fields.username', 'Ulanyjy ady')}
|
<InfoRow label={t("clients.fields.name", "Ady")} value={client.name} />
|
||||||
value={client.username}
|
<InfoRow label={t("clients.fields.isActive", "Işjeň")}>
|
||||||
/>
|
<ActiveIndicator active={client.active} />
|
||||||
<InfoRow
|
|
||||||
label={t('clients.fields.name', 'Ady')}
|
|
||||||
value={client.name}
|
|
||||||
/>
|
|
||||||
<InfoRow label={t('clients.fields.isActive', 'Işjeň')}>
|
|
||||||
<ActiveIndicator active={client.isActive} />
|
|
||||||
</InfoRow>
|
</InfoRow>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
<BentoCard title={t('clients.sections.contact', 'Kontakt')}>
|
<BentoCard title={t("clients.sections.contact", "Kontakt")}>
|
||||||
<InfoRow
|
<InfoRow label={t("clients.fields.phone", "Telefon")} value={client.phone ?? "—"} />
|
||||||
label={t('clients.fields.phone', 'Telefon')}
|
<InfoRow label={t("clients.fields.email", "E-poçta")} value={client.email ?? "—"} />
|
||||||
value={client.phone ?? '—'}
|
|
||||||
/>
|
|
||||||
<InfoRow
|
|
||||||
label={t('clients.fields.email', 'E-poçta')}
|
|
||||||
value={client.email ?? '—'}
|
|
||||||
/>
|
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
</BentoGrid>
|
</BentoGrid>
|
||||||
|
|
||||||
{/* ── Rollar ───────────────────────────────────────────────────────── */}
|
{/* ── Rollar ───────────────────────────────────────────────────────── */}
|
||||||
<CollapsibleSection title={t('clients.sections.roles', 'Rollar')}>
|
<CollapsibleSection title={t("clients.sections.roles", "Rollar")}>
|
||||||
<DataTableToolbar
|
<DataTableToolbar
|
||||||
searchValue={roleSearch}
|
searchValue={roleSearch}
|
||||||
onSearchChange={setRoleSearch}
|
onSearchChange={setRoleSearch}
|
||||||
searchPlaceholder={t('common.search', 'Gözlemek')}
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||||
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
|
columns={[]}
|
||||||
columnOrder={[]} onColumnOrderChange={() => {}}
|
columnVisibility={{}}
|
||||||
actionLabel={t('clients.addRole', 'Rol birikdiriň')}
|
onColumnVisibilityChange={() => {}}
|
||||||
|
columnOrder={[]}
|
||||||
|
onColumnOrderChange={() => {}}
|
||||||
|
actionLabel={t("clients.addRole", "Rol birikdiriň")}
|
||||||
onAction={() => {}}
|
onAction={() => {}}
|
||||||
/>
|
/>
|
||||||
{filteredRoles.length > 0 ? (
|
{filteredRoles.length > 0 ? (
|
||||||
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
|
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
|
||||||
) : (
|
) : (
|
||||||
<EmptyState label={t('clients.noRoles', 'Berlen kriterýalara Rol gabat gelmedi.')} />
|
<EmptyState label={t("clients.noRoles", "Berlen kriterýalara Rol gabat gelmedi.")} />
|
||||||
)}
|
)}
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
|
{/* ── Rugsatlar ────────────────────────────────────────────────────── */}
|
||||||
<CollapsibleSection title={t('clients.sections.permissions', 'Rugsatlar')}>
|
<CollapsibleSection title={t("clients.sections.permissions", "Rugsatlar")}>
|
||||||
<DataTableToolbar
|
<DataTableToolbar
|
||||||
searchValue={permSearch}
|
searchValue={permSearch}
|
||||||
onSearchChange={setPermSearch}
|
onSearchChange={setPermSearch}
|
||||||
searchPlaceholder={t('common.search', 'Gözlemek')}
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||||
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
|
columns={[]}
|
||||||
columnOrder={[]} onColumnOrderChange={() => {}}
|
columnVisibility={{}}
|
||||||
actionLabel={t('clients.addPermission', 'Rugsat birikdiriň')}
|
onColumnVisibilityChange={() => {}}
|
||||||
|
columnOrder={[]}
|
||||||
|
onColumnOrderChange={() => {}}
|
||||||
|
actionLabel={t("clients.addPermission", "Rugsat birikdiriň")}
|
||||||
onAction={() => {}}
|
onAction={() => {}}
|
||||||
/>
|
/>
|
||||||
{(client.permissions ?? []).length === 0 && (
|
{(client.permissions ?? []).length === 0 && (
|
||||||
<EmptyState label={t('clients.noPermissions', 'Berlen kriterýalara Rugsat gabat gelmedi.')} />
|
<EmptyState label={t("clients.noPermissions", "Berlen kriterýalara Rugsat gabat gelmedi.")} />
|
||||||
)}
|
)}
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
|
{/* ── Şahamçalar ───────────────────────────────────────────────────── */}
|
||||||
<CollapsibleSection title={t('clients.sections.branches', 'Şahamçalar')}>
|
<CollapsibleSection title={t("clients.sections.branches", "Şahamçalar")}>
|
||||||
<DataTableToolbar
|
<DataTableToolbar
|
||||||
searchValue={branchSearch}
|
searchValue={branchSearch}
|
||||||
onSearchChange={setBranchSearch}
|
onSearchChange={setBranchSearch}
|
||||||
searchPlaceholder={t('common.search', 'Gözlemek')}
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||||
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
|
columns={[]}
|
||||||
columnOrder={[]} onColumnOrderChange={() => {}}
|
columnVisibility={{}}
|
||||||
actionLabel={t('clients.addBranch', 'Şahamça birikdiriň')}
|
onColumnVisibilityChange={() => {}}
|
||||||
|
columnOrder={[]}
|
||||||
|
onColumnOrderChange={() => {}}
|
||||||
|
actionLabel={t("clients.addBranch", "Şahamça birikdiriň")}
|
||||||
onAction={() => {}}
|
onAction={() => {}}
|
||||||
/>
|
/>
|
||||||
{filteredBranches.length > 0 ? (
|
{filteredBranches.length > 0 ? (
|
||||||
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
|
<DataTable columns={branchColumns} data={filteredBranches} getRowId={(r) => String(r.id)} enableRowSelection />
|
||||||
) : (
|
) : (
|
||||||
<EmptyState label={t('clients.noBranches', 'Berlen kriterýalara Şahamça gabat gelmedi.')} />
|
<EmptyState label={t("clients.noBranches", "Berlen kriterýalara Şahamça gabat gelmedi.")} />
|
||||||
)}
|
)}
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
{/* ── Karz sargyt ──────────────────────────────────────────────────── */}
|
{/* ── Karz sargyt ──────────────────────────────────────────────────── */}
|
||||||
<CollapsibleSection title={t('clients.sections.loanOrders', 'Karz sargyt')}>
|
<CollapsibleSection title={t("clients.sections.loanOrders", "Karz sargyt")}>
|
||||||
<DataTableToolbar
|
<DataTableToolbar
|
||||||
searchValue={loanSearch}
|
searchValue={loanSearch}
|
||||||
onSearchChange={setLoanSearch}
|
onSearchChange={setLoanSearch}
|
||||||
searchPlaceholder={t('common.search', 'Gözlemek')}
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||||
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
|
columns={[]}
|
||||||
columnOrder={[]} onColumnOrderChange={() => {}}
|
columnVisibility={{}}
|
||||||
actionLabel={t('clients.addLoanOrder', 'Karz sargyt dörediň')}
|
onColumnVisibilityChange={() => {}}
|
||||||
|
columnOrder={[]}
|
||||||
|
onColumnOrderChange={() => {}}
|
||||||
|
actionLabel={t("clients.addLoanOrder", "Karz sargyt dörediň")}
|
||||||
onAction={() => {}}
|
onAction={() => {}}
|
||||||
/>
|
/>
|
||||||
{(client.loanOrders ?? []).length === 0 && (
|
{(client.loanOrders ?? []).length === 0 && (
|
||||||
<EmptyState label={t('clients.noLoanOrders', 'Berlen kriterýalara Karz sargyt gabat gelmedi.')} />
|
<EmptyState label={t("clients.noLoanOrders", "Berlen kriterýalara Karz sargyt gabat gelmedi.")} />
|
||||||
)}
|
)}
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
{/* ── Kart sargyt ──────────────────────────────────────────────────── */}
|
{/* ── Kart sargyt ──────────────────────────────────────────────────── */}
|
||||||
<CollapsibleSection title={t('clients.sections.cardOrders', 'Kart sargyt')}>
|
<CollapsibleSection title={t("clients.sections.cardOrders", "Kart sargyt")}>
|
||||||
<DataTableToolbar
|
<DataTableToolbar
|
||||||
searchValue={cardSearch}
|
searchValue={cardSearch}
|
||||||
onSearchChange={setCardSearch}
|
onSearchChange={setCardSearch}
|
||||||
searchPlaceholder={t('common.search', 'Gözlemek')}
|
searchPlaceholder={t("common.search", "Gözlemek")}
|
||||||
columns={[]} columnVisibility={{}} onColumnVisibilityChange={() => {}}
|
columns={[]}
|
||||||
columnOrder={[]} onColumnOrderChange={() => {}}
|
columnVisibility={{}}
|
||||||
actionLabel={t('clients.addCardOrder', 'Kart sargyt dörediň')}
|
onColumnVisibilityChange={() => {}}
|
||||||
|
columnOrder={[]}
|
||||||
|
onColumnOrderChange={() => {}}
|
||||||
|
actionLabel={t("clients.addCardOrder", "Kart sargyt dörediň")}
|
||||||
onAction={() => {}}
|
onAction={() => {}}
|
||||||
/>
|
/>
|
||||||
{(client.cardOrders ?? []).length === 0 && (
|
{(client.cardOrders ?? []).length === 0 && (
|
||||||
<EmptyState label={t('clients.noCardOrders', 'Berlen kriterýalara Kart sargyt gabat gelmedi.')} />
|
<EmptyState label={t("clients.noCardOrders", "Berlen kriterýalara Kart sargyt gabat gelmedi.")} />
|
||||||
)}
|
)}
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
@@ -304,13 +301,12 @@ export default function ClientDetailPage() {
|
|||||||
<ConfirmDialog
|
<ConfirmDialog
|
||||||
open={deleteOpen}
|
open={deleteOpen}
|
||||||
onOpenChange={setDeleteOpen}
|
onOpenChange={setDeleteOpen}
|
||||||
title={t('clients.deleteTitle', 'Müşderini pozmak')}
|
title={t("clients.deleteTitle", "Müşderini pozmak")}
|
||||||
description={t('clients.deleteConfirm', '{{name}} müşderisini pozmak isleýärsiňizmi?', { name: client.name })}
|
description={t("clients.deleteConfirm", "{{name}} müşderisini pozmak isleýärsiňizmi?", { name: client.name })}
|
||||||
confirmLabel={t('common.delete', 'Poz')}
|
confirmLabel={t("common.delete", "Poz")}
|
||||||
onConfirm={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate('/clients') })}
|
onConfirm={() => deleteMutation.mutate(clientId, { onSuccess: () => navigate("/clients") })}
|
||||||
isLoading={deleteMutation.isPending}
|
isLoading={deleteMutation.isPending}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
@@ -32,14 +32,14 @@ export default function OperatorsPage() {
|
|||||||
// ── Query ────────────────────────────────────────────────────────────────────
|
// ── Query ────────────────────────────────────────────────────────────────────
|
||||||
const { data, isLoading } = useOperators({
|
const { data, isLoading } = useOperators({
|
||||||
page,
|
page,
|
||||||
perPage,
|
limit: perPage,
|
||||||
search: search || undefined,
|
search: search || undefined,
|
||||||
isActive: isActiveFilter || undefined,
|
isActive: isActiveFilter || undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
const operators = data?.data ?? [];
|
const operators = data?.users ?? [];
|
||||||
const totalPages = data?.meta.totalPages ?? 1;
|
const totalCount = data?.count ?? 0;
|
||||||
const totalCount = data?.meta.totalCount ?? 0;
|
const totalPages = Math.max(1, Math.ceil(totalCount / perPage));
|
||||||
|
|
||||||
// ── Columns ──────────────────────────────────────────────────────────────────
|
// ── Columns ──────────────────────────────────────────────────────────────────
|
||||||
const columns: ColumnDef<Operator>[] = [
|
const columns: ColumnDef<Operator>[] = [
|
||||||
@@ -77,14 +77,10 @@ export default function OperatorsPage() {
|
|||||||
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
|
cell: ({ row }) => <span className="text-sm text-foreground">{row.original.email ?? "—"}</span>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "isActive",
|
accessorKey: "active",
|
||||||
header: t("operators.fields.isActive", "IŞJEŇ"),
|
header: t("operators.fields.isActive", "IŞJEŇ"),
|
||||||
cell: ({ row }) =>
|
cell: ({ row }) =>
|
||||||
row.original.isActive ? (
|
row.original.active ? <CheckCircle2 size={18} className="text-emerald-500" /> : <XCircle size={18} className="text-destructive" />,
|
||||||
<CheckCircle2 size={18} className="text-emerald-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle size={18} className="text-destructive" />
|
|
||||||
),
|
|
||||||
size: 80,
|
size: 80,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ export default function OperatorDetailPage() {
|
|||||||
<InfoRow label={t("operators.fields.username", "Ulanyjy ady")} value={operator.username} />
|
<InfoRow label={t("operators.fields.username", "Ulanyjy ady")} value={operator.username} />
|
||||||
<InfoRow label={t("operators.fields.name", "Ady")} value={operator.name} />
|
<InfoRow label={t("operators.fields.name", "Ady")} value={operator.name} />
|
||||||
<InfoRow label={t("operators.fields.isActive", "Işjeň")}>
|
<InfoRow label={t("operators.fields.isActive", "Işjeň")}>
|
||||||
<ActiveIndicator active={operator.isActive} />
|
<ActiveIndicator active={operator.active} />
|
||||||
</InfoRow>
|
</InfoRow>
|
||||||
</BentoCard>
|
</BentoCard>
|
||||||
|
|
||||||
@@ -258,9 +258,7 @@ export default function OperatorDetailPage() {
|
|||||||
columnOrder={[]}
|
columnOrder={[]}
|
||||||
onColumnOrderChange={() => {}}
|
onColumnOrderChange={() => {}}
|
||||||
actionLabel={t("operators.addRole", "Rol birikdiriň")}
|
actionLabel={t("operators.addRole", "Rol birikdiriň")}
|
||||||
onAction={() => {
|
onAction={() => {}}
|
||||||
/* modal aç ya da navigate */
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
|
<DataTable columns={roleColumns} data={filteredRoles} getRowId={(r) => String(r.id)} enableRowSelection />
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|||||||
Reference in new issue
Block a user