diff --git a/src/features/auth/api/authApi.ts b/src/features/auth/api/authApi.ts index 33ee158..6abd7b4 100644 --- a/src/features/auth/api/authApi.ts +++ b/src/features/auth/api/authApi.ts @@ -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 { return Promise.resolve(); } + +export async function registerApi(data: RegisterRequest): Promise { + await apiClient.post("/register", data); +} + +export async function registerVerifyApi(data: RegisterVerifyRequest): Promise { + 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 { + await apiClient.post("/forgot-password", data); +} + +export async function forgotPasswordVerifyApi(data: ForgotPasswordVerifyRequest): Promise { + await apiClient.post("/forgot-password/verify", data); +} diff --git a/src/features/auth/hooks/useForgotPassword.ts b/src/features/auth/hooks/useForgotPassword.ts new file mode 100644 index 0000000..e12ec9b --- /dev/null +++ b/src/features/auth/hooks/useForgotPassword.ts @@ -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), + }); +} diff --git a/src/features/auth/hooks/useRegister.ts b/src/features/auth/hooks/useRegister.ts new file mode 100644 index 0000000..b8631ef --- /dev/null +++ b/src/features/auth/hooks/useRegister.ts @@ -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), + }); +} diff --git a/src/features/clients/api/clientsApi.ts b/src/features/clients/api/clientsApi.ts index 334ea53..a7b8fae 100644 --- a/src/features/clients/api/clientsApi.ts +++ b/src/features/clients/api/clientsApi.ts @@ -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 => { - 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 => { + const { page, limit, search, isActive } = params; + const { data } = await apiClient.get("/users/clients", { + params: { page, limit, username: search, isActive }, + signal, + }); + return data; }, - getById: async (id: number): Promise => { - 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 => { + const { data } = await apiClient.get(`/users/${id}`); + return data; }, - create: async (payload: CreateClientPayload): Promise => { - 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 => { + const { data } = await apiClient.post("/users", payload); + return data; }, - update: async (id: number, payload: UpdateClientPayload): Promise => { - 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 => { + const { data } = await apiClient.put(`/users/${id}`, payload); + return data; }, - delete: async (id: number): Promise => { - await delay(500) - mockClients = mockClients.filter((c) => c.id !== Number(id)) + /** DELETE /users/:id */ + deleteClient: async (id: number): Promise => { + await apiClient.delete(`/users/${id}`); }, - - assignRole: async (_clientId: number, _roleId: number): Promise => { - await delay(500) - }, - - removeRole: async (_clientId: number, _roleId: number): Promise => { - await delay(500) - }, - - assignPermission: async (_clientId: number, _permissionId: number): Promise => { - await delay(500) - }, - - removePermission: async (_clientId: number, _permissionId: number): Promise => { - await delay(500) - }, - - assignBranch: async (_clientId: number, _branchId: number): Promise => { - await delay(500) - }, - - removeBranch: async (_clientId: number, _branchId: number): Promise => { - await delay(500) - }, -} \ No newline at end of file +}; diff --git a/src/features/clients/components/clientForm.tsx b/src/features/clients/components/clientForm.tsx index bd4fc6c..4b82d92 100644 --- a/src/features/clients/components/clientForm.tsx +++ b/src/features/clients/components/clientForm.tsx @@ -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 = 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 (

@@ -127,88 +152,178 @@ export function ClientForm({ mode, initialData }: ClientFormProps) { setField("username", v)} - placeholder={t("clients.fields.username", "Ulanyjy ady")} + placeholder={t("users.fields.username", "Ulanyjy ady")} error={errors.username} disabled={isPending} required /> +

{t("users.fields.usernameHint", "Unikal login ady")}

+
+ + setField("name", v)} + placeholder={t("users.fields.name", "Ady")} + error={errors.name} + disabled={isPending} + required + /> +

{t("users.fields.nameHint", "Doly ady we familiýasy")}

+
+ + setField("firstName", v)} + placeholder={t("users.fields.firstName", "Ady (at)")} + error={errors.firstName} + disabled={isPending} + /> 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 /> setField("phone", v)} + placeholder="62-38-49-56" error={errors.phone} disabled={isPending} required /> +

{t("users.fields.phoneHint", "+993 bilen başlanýar")}

setField("email", v)} - placeholder={t("clients.fields.email", "E-poçta")} + placeholder={t("users.fields.email", "E-poçta")} + error={errors.email} disabled={isPending} /> +

{t("users.fields.emailHint", "Islege görä")}

+
+ + setField("role", v)} + placeholder={t("users.fields.role", "Roly")} + error={errors.role} + disabled={isPending} + required + {...roleSelect} + /> - - 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" && ( -

- {t("clients.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")} -

- )}
- -
- {t("clients.fields.isActive", "Işjeň")} - setField("isActive", !!v)} + {mode === "create" && ( + + setField("password", v)} + placeholder={t("users.fields.password", "Açar sözi")} + error={errors.password} + disabled={isPending} + required + /> +

{t("users.fields.passwordHint", "Iň az 6 harp")}

+
+ )} + +
+

{t("users.fields.socialMedia", "Sosial media")}

+
+
+ setField("socialFacebook", v)} + placeholder="facebook.com/..." + error={errors.socialFacebook} + disabled={isPending} + /> + setField("socialInstagram", v)} + placeholder="instagram.com/..." + error={errors.socialInstagram} + disabled={isPending} + /> + setField("socialTelegram", v)} + placeholder="t.me/..." + error={errors.socialTelegram} disabled={isPending} - className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" />
- navigate(-1)} - submitLabel={mode === "create" ? t("clients.createBtn", "Müşderi döredin") : t("clients.updateBtn", "Üýtgetmeleri sakla")} - /> +
+ +
+

{t("users.fields.lightMode", "Light režimi")}

+
+
+ setField("lightMode", !!v)} disabled={isPending} /> + +
+
+ +
+

{t("users.fields.isActive", "Işjeň")}

+

{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}

+
+
+ setField("active", !!v)} disabled={isPending} /> + +
+ navigate(-1)} + submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")} + />
); } diff --git a/src/features/clients/hooks/useClients.ts b/src/features/clients/hooks/useClients.ts index f4b2363..f6fa26f 100644 --- a/src/features/clients/hooks/useClients.ts +++ b/src/features/clients/hooks/useClients.ts @@ -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')) - }, - }) -} \ No newline at end of file diff --git a/src/features/clients/schemas/client.schema.ts b/src/features/clients/schemas/client.schema.ts index d48a7b4..513d130 100644 --- a/src/features/clients/schemas/client.schema.ts +++ b/src/features/clients/schemas/client.schema.ts @@ -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>; 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, }; } diff --git a/src/features/operators/api/operatorsApi.ts b/src/features/operators/api/operatorsApi.ts index bdd7d4f..d3dc62d 100644 --- a/src/features/operators/api/operatorsApi.ts +++ b/src/features/operators/api/operatorsApi.ts @@ -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 => { - 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 => { + const { page, limit, search, isActive } = params; + const { data } = await apiClient.get("/users/staff", { + params: { page, limit, username: search, isActive }, + signal, + }); + return data; }, - getById: async (id: number): Promise => { - 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 => { + const { data } = await apiClient.get(`/users/${id}`); + return data; }, - create: async (payload: CreateOperatorPayload): Promise => { - 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 => { + const { data } = await apiClient.post("/users", payload); + return data; }, - update: async (id: number, payload: UpdateOperatorPayload): Promise => { - 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 => { + const { data } = await apiClient.put(`/users/${id}`, payload); + return data; }, - delete: async (id: number): Promise => { - await delay(500) - mockOperators = mockOperators.filter((o) => o.id !== Number(id)) + /** DELETE /users/:id */ + deleteOperator: async (id: number): Promise => { + await apiClient.delete(`/users/${id}`); }, - - assignRole: async (_operatorId: number, _roleId: number): Promise => { - await delay(500) - }, - - removeRole: async (_operatorId: number, _roleId: number): Promise => { - await delay(500) - }, - - assignPermission: async (_operatorId: number, _permissionId: number): Promise => { - await delay(500) - }, - - removePermission: async (_operatorId: number, _permissionId: number): Promise => { - await delay(500) - }, -} \ No newline at end of file +}; diff --git a/src/features/operators/components/operatorForms.tsx b/src/features/operators/components/operatorForms.tsx index 7e6672b..16fcea6 100644 --- a/src/features/operators/components/operatorForms.tsx +++ b/src/features/operators/components/operatorForms.tsx @@ -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 = 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 (

{mode === "create" ? t("operators.createTitle", "Operator dörediň") : t("operators.editTitle", "Operator üýtgetmek")}

-
- {/* Username */} -
- - {t("operators.fields.username", "Ulanyjy ady")} - * - + + 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 /> -
- - {/* Name */} -
- - {t("operators.fields.name", "Ady")} - * - +

{t("users.fields.usernameHint", "Unikal login ady")}

+ + 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 /> -
- - {/* Phone */} -
- {t("operators.fields.phone", "Telefon")} - setField("phone", v)} disabled={isPending} className="max-w-lg" /> -
- - {/* Email */} -
- {t("operators.fields.email", "E-poçta")} +

{t("users.fields.nameHint", "Doly ady we familiýasy")}

+ + + setField("firstName", v)} + placeholder={t("users.fields.firstName", "Ady (at)")} + error={errors.firstName} + disabled={isPending} + /> + + + setField("lastName", v)} + placeholder={t("users.fields.lastName", "Familiýasy")} + error={errors.lastName} + disabled={isPending} + /> + + + setField("phone", v)} + placeholder="62-38-49-56" + error={errors.phone} + disabled={isPending} + required + /> +

{t("users.fields.phoneHint", "+993 bilen başlanýar")}

+
+ 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" /> -
- - {/* Password */} -
- - {t("operators.fields.password", "Açar sözi")} - {mode === "create" && *} - -
+

{t("users.fields.emailHint", "Islege görä")}

+ + + setField("role", v)} + placeholder={t("users.fields.role", "Roly")} + error={errors.role} + disabled={isPending} + required + {...roleSelect} + /> + + + setField("avatar", v)} + placeholder="https://..." + error={errors.avatar} + disabled={isPending} + /> + + {mode === "create" && ( + 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" && ( -

{t("operators.fields.passwordEditNote", "Boş goýsaňyz, açar sözi üýtgemez")}

- )} +

{t("users.fields.passwordHint", "Iň az 6 harp")}

+
+ )} + +
+

{t("users.fields.socialMedia", "Sosial media")}

-
- - {/* isActive */} -
- {t("operators.fields.isActive", "Işjeň")} - setField("isActive", !!v)} - disabled={isPending} - className="data-[state=checked]:bg-primary data-[state=checked]:border-primary" - /> -
- - 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" - /> -
+
+ setField("socialFacebook", v)} + placeholder="facebook.com/..." + error={errors.socialFacebook} + disabled={isPending} + /> + setField("socialInstagram", v)} + placeholder="instagram.com/..." + error={errors.socialInstagram} + disabled={isPending} + /> + setField("socialTelegram", v)} + placeholder="t.me/..." + error={errors.socialTelegram} + disabled={isPending} + /> +
+ + +
+

{t("users.fields.lightMode", "Light režimi")}

+
+
+ setField("lightMode", !!v)} disabled={isPending} /> + +
+
+ +
+

{t("users.fields.isActive", "Işjeň")}

+

{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}

+
+
+ setField("active", !!v)} disabled={isPending} /> + +
+
+ + navigate(-1)} + submitLabel={mode === "create" ? t("users.actions.create", "Ulanyjy dörediň") : t("users.actions.save", "Ýatda sakla")} + />
); } diff --git a/src/features/operators/hooks/useOperators.ts b/src/features/operators/hooks/useOperators.ts index 74f31df..5eb68da 100644 --- a/src/features/operators/hooks/useOperators.ts +++ b/src/features/operators/hooks/useOperators.ts @@ -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')) - }, - }) -} \ No newline at end of file diff --git a/src/features/operators/schemas/operator.schema.ts b/src/features/operators/schemas/operator.schema.ts index eac41b8..bb9f7a7 100644 --- a/src/features/operators/schemas/operator.schema.ts +++ b/src/features/operators/schemas/operator.schema.ts @@ -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>; 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, }; } diff --git a/src/pages/login/index.tsx b/src/pages/login/index.tsx index f918775..b5578e3 100644 --- a/src/pages/login/index.tsx +++ b/src/pages/login/index.tsx @@ -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, "onChange" | "value"> { +// ─── Simple FormInput (used in login / reset-password) ──────────────────────── + +interface SimpleFormInputProps extends Omit, "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 (
@@ -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) => { + 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 ( +
+ +
+
+ +993 +
+ +
+
+ ); +} + +// ─── 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("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 = () => ( +
+ + {t("Privacy Policy")} + +
+ ); + return (
@@ -115,6 +353,7 @@ export default function AuthPage() {
+ {/* ── LOGIN ── */} {view === "login" && ( <>

@@ -122,12 +361,38 @@ export default function AuthPage() {

- + {/* Smart phone / username input */} +
+ +
+ {identifierIsPhone(identifier) && ( +
+ +993 +
+ )} + 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" + /> +
+
{ if (e.key === "Enter") handleLogin(); }} + disabled={loginMutation.isPending} />
- setView("reset-password")} className="text-[13px] text-primary cursor-pointer hover:underline"> + setView("forgot-password")} className="text-[13px] text-primary cursor-pointer hover:underline"> {t("Forgot your password?")}
@@ -153,65 +419,191 @@ export default function AuthPage() {
-
- - {t("Privacy Policy")} - -
+ )} + {/* ── REGISTER (step 1) ── */} {view === "register" && ( <>

{t("Online panel", "Onlaýn kabulhana")}

- - - - - + + + + +
- -
-
- - {t("Privacy Policy")} - -
+ )} - {view === "reset-password" && ( + {/* ── REGISTER VERIFY (step 2 – SMS OTP) ── */} + {view === "register-verify" && ( <> -

- {t("Enter your username to continue")} -

+
+
+ +
+

{t("SMS Verification", "SMS Tassyklamasy")}

+

+ {t("Enter the code sent to", "Iberilen kody giriziň")}{" "} + +993 {regPhone} +

+
- + { + if (e.key === "Enter") handleVerify(); + }} + /> + +
+ + +
+ + + + )} + + {/* ── FORGOT PASSWORD (step 1) ── */} + {view === "forgot-password" && ( + <> +

{t("Forgot your password?")}

+

+ {t("Enter your username to receive a reset code", "Täzeden açar söz üçin ulanyjy adyňyzy giriziň")} +

+
+ + { + if (e.key === "Enter") handleForgotPassword(); + }} + />
- -
-
- - {t("Privacy Policy")} - + + + )} + + {/* ── FORGOT PASSWORD VERIFY (step 2) ── */} + {view === "forgot-password-verify" && ( + <> +
+
+ +
+

{t("Reset Password", "Açar sözi täzele")}

+

+ {t("Enter the SMS code and your new password", "SMS kodyny we täze açar söziňizi giriziň")} +

+
+ + + + { + if (e.key === "Enter") handleForgotPasswordVerify(); + }} + /> + +
+ + +
+ + )}
diff --git a/src/pages/users/clients/index.tsx b/src/pages/users/clients/index.tsx index be9e8e1..273acf8 100644 --- a/src/pages/users/clients/index.tsx +++ b/src/pages/users/clients/index.tsx @@ -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[] = [ { @@ -71,14 +71,10 @@ export default function ClientsPage() { cell: ({ row }) => {row.original.email ?? "—"}, }, { - accessorKey: "isActive", + accessorKey: "active", header: t("clients.fields.isActive", "IŞJEŇ"), cell: ({ row }) => - row.original.isActive ? ( - - ) : ( - - ), + row.original.active ? : , size: 80, }, { diff --git a/src/pages/users/clientsView/index.tsx b/src/pages/users/clientsView/index.tsx index d7ae5c1..0801885 100644 --- a/src/pages/users/clientsView/index.tsx +++ b/src/pages/users/clientsView/index.tsx @@ -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 ? ( - - ) : ( - - ); + return active ? : ; } // ─── 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[] = [ { - accessorKey: 'id', - header: t('common.id', 'ID'), + accessorKey: "id", + header: t("common.id", "ID"), cell: ({ row }) => {row.original.id}, size: 80, }, { - accessorKey: 'code', - header: t('roles.fields.code', 'KOD'), + accessorKey: "code", + header: t("roles.fields.code", "KOD"), cell: ({ row }) => {row.original.code}, }, { - accessorKey: 'name', - header: t('roles.fields.name', 'ADY'), + accessorKey: "name", + header: t("roles.fields.name", "ADY"), cell: ({ row }) => {row.original.name}, }, { - accessorKey: 'guardName', - header: t('roles.fields.guardName', 'GUARD NAME'), + accessorKey: "guardName", + header: t("roles.fields.guardName", "GUARD NAME"), cell: ({ row }) => {row.original.guardName}, }, { - id: 'actions', - header: '', + id: "actions", + header: "", cell: () => (
- ) + ); } - 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 (
- {/* ── Page header ──────────────────────────────────────────────────── */}

- {t('clients.detailTitle', 'Müşderi giňişleýin')}: {client.name} + {t("clients.detailTitle", "Müşderi giňişleýin")}: {client.name}

- ) -} \ No newline at end of file + ); +} diff --git a/src/pages/users/operators/index.tsx b/src/pages/users/operators/index.tsx index c9dc2bd..03ffb4c 100644 --- a/src/pages/users/operators/index.tsx +++ b/src/pages/users/operators/index.tsx @@ -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[] = [ @@ -77,14 +77,10 @@ export default function OperatorsPage() { cell: ({ row }) => {row.original.email ?? "—"}, }, { - accessorKey: "isActive", + accessorKey: "active", header: t("operators.fields.isActive", "IŞJEŇ"), cell: ({ row }) => - row.original.isActive ? ( - - ) : ( - - ), + row.original.active ? : , size: 80, }, { diff --git a/src/pages/users/operatorsView/index.tsx b/src/pages/users/operatorsView/index.tsx index 6ef7421..ba4cf5f 100644 --- a/src/pages/users/operatorsView/index.tsx +++ b/src/pages/users/operatorsView/index.tsx @@ -236,7 +236,7 @@ export default function OperatorDetailPage() { - + @@ -258,9 +258,7 @@ export default function OperatorDetailPage() { columnOrder={[]} onColumnOrderChange={() => {}} actionLabel={t("operators.addRole", "Rol birikdiriň")} - onAction={() => { - /* modal aç ya da navigate */ - }} + onAction={() => {}} /> String(r.id)} enableRowSelection />