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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user