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