started connect with api
This commit is contained in:
@@ -1,198 +1,104 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface User {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string | null
|
||||
isActive: boolean
|
||||
phoneVerified: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
export interface SocialMedia {
|
||||
facebook: string;
|
||||
instagram: string;
|
||||
telegram: string;
|
||||
}
|
||||
|
||||
export interface UserListItem {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email: string | null
|
||||
isActive: boolean
|
||||
export interface User {
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
username: string;
|
||||
phone: string;
|
||||
avatar: string;
|
||||
socialMedia: SocialMedia;
|
||||
lightMode: number;
|
||||
role: string;
|
||||
active: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UsersListResponse {
|
||||
data: UserListItem[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
totalPages: number
|
||||
count: number;
|
||||
users: User[];
|
||||
}
|
||||
|
||||
export interface UsersListParams {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
isActive?: string;
|
||||
}
|
||||
|
||||
export interface CreateUserPayload {
|
||||
username: string
|
||||
name: string
|
||||
phone: string
|
||||
email?: string
|
||||
password: string
|
||||
phoneVerified: boolean
|
||||
isActive: boolean
|
||||
active: boolean;
|
||||
avatar: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
lightMode: number;
|
||||
name: string;
|
||||
password: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
socialMedia: SocialMedia;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserPayload {
|
||||
username?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
phoneVerified?: boolean
|
||||
isActive?: boolean
|
||||
active?: boolean;
|
||||
avatar?: string;
|
||||
email?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
lightMode?: number;
|
||||
name?: string;
|
||||
phone?: string;
|
||||
role?: string;
|
||||
socialMedia?: SocialMedia;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
||||
|
||||
const MOCK_USERS: User[] = Array.from({ length: 50 }, (_, i) => {
|
||||
const id = 5970 - i
|
||||
const names = [
|
||||
'Orazowa Nurtuwak Täşliyewna',
|
||||
'Hallyýewa Aýna Gurbanmyradowna',
|
||||
'Sopýýewa Maral Agamyradowna',
|
||||
'Babamurat Baýnazarow Şanazarowič',
|
||||
'Narmet Narmet',
|
||||
'Sheker Durdyyewa',
|
||||
'kamalowyusup',
|
||||
'Mahmudowberdimet',
|
||||
'allanazarowasayyara',
|
||||
'dadayewjepbar',
|
||||
]
|
||||
const usernames = [
|
||||
'Nurtuwak_1970', 'Ayna_1989', 'Maral_1974', 'Babamurat_0002', 'Narmet',
|
||||
'8319_ShekerDurdyyewa', 'kamalowyusup', 'Mahmudowberdimet',
|
||||
'allanazarowasayyara', 'dadayewjepbar',
|
||||
]
|
||||
const idx = i % names.length
|
||||
return {
|
||||
id,
|
||||
username: i < usernames.length ? usernames[idx] : `user_${id}`,
|
||||
name: names[idx],
|
||||
phone: `+(993)-6${Math.floor(Math.random() * 9 + 1)}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}-${String(Math.floor(Math.random() * 90 + 10))}`,
|
||||
email: i % 4 === 0 ? `user${id}@tbbank.gov.tm` : null,
|
||||
isActive: Math.random() > 0.1,
|
||||
phoneVerified: Math.random() > 0.3,
|
||||
createdAt: new Date(Date.now() - Math.random() * 1e10).toISOString(),
|
||||
updatedAt: new Date(Date.now() - Math.random() * 1e9).toISOString(),
|
||||
}
|
||||
})
|
||||
|
||||
// ─── Mock delay helper ────────────────────────────────────────────────────────
|
||||
|
||||
const delay = (ms = 500) => new Promise((res) => setTimeout(res, ms))
|
||||
|
||||
// ─── API Functions ────────────────────────────────────────────────────────────
|
||||
|
||||
export const usersApi = {
|
||||
/**
|
||||
* GET /users
|
||||
*/
|
||||
getUsers: async (params: UsersListParams = {}): Promise<UsersListResponse> => {
|
||||
await delay()
|
||||
// Uncomment for real API:
|
||||
// const res = await apiClient.get<UsersListResponse>('/users', { params })
|
||||
// return res.data
|
||||
|
||||
const { page = 1, perPage = 25, search = '', isActive } = params
|
||||
|
||||
let filtered = [...MOCK_USERS]
|
||||
|
||||
if (search.trim()) {
|
||||
const q = search.toLowerCase()
|
||||
filtered = filtered.filter(
|
||||
(u) =>
|
||||
u.username.toLowerCase().includes(q) ||
|
||||
u.name.toLowerCase().includes(q) ||
|
||||
u.phone.includes(q),
|
||||
)
|
||||
}
|
||||
|
||||
if (isActive !== undefined && isActive !== '') {
|
||||
const active = isActive === 'true'
|
||||
filtered = filtered.filter((u) => u.isActive === active)
|
||||
}
|
||||
|
||||
const total = filtered.length
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
const start = (page - 1) * perPage
|
||||
const data = filtered.slice(start, start + perPage).map(({ id, username, name, phone, email, isActive }) => ({
|
||||
id, username, name, phone, email, isActive,
|
||||
}))
|
||||
|
||||
return { data, total, page, perPage, totalPages }
|
||||
/** GET /users — backend filters by `username` */
|
||||
getUsers: async (params: UsersListParams = {}, signal?: AbortSignal): Promise<UsersListResponse> => {
|
||||
const { page, limit, search, isActive } = params;
|
||||
const { data } = await apiClient.get<UsersListResponse>("/users", {
|
||||
params: { page, limit, username: search, isActive },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* GET /users/:id
|
||||
*/
|
||||
/** GET /users/:id */
|
||||
getUserById: async (id: number): Promise<User> => {
|
||||
await delay()
|
||||
// const res = await apiClient.get<User>(`/users/${id}`)
|
||||
// return res.data
|
||||
|
||||
const user = MOCK_USERS.find((u) => u.id === id)
|
||||
if (!user) throw new Error(`User ${id} not found`)
|
||||
return user
|
||||
const { data } = await apiClient.get<User>(`/users/${id}`);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* POST /users
|
||||
*/
|
||||
/** POST /users */
|
||||
createUser: async (payload: CreateUserPayload): Promise<User> => {
|
||||
await delay(800)
|
||||
// const res = await apiClient.post<User>('/users', payload)
|
||||
// return res.data
|
||||
|
||||
const newUser: User = {
|
||||
id: Math.max(...MOCK_USERS.map((u) => u.id)) + 1,
|
||||
username: payload.username,
|
||||
name: payload.name,
|
||||
phone: payload.phone,
|
||||
email: payload.email ?? null,
|
||||
isActive: payload.isActive,
|
||||
phoneVerified: payload.phoneVerified,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
MOCK_USERS.unshift(newUser)
|
||||
return newUser
|
||||
const { data } = await apiClient.post<User>("/users", payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* PUT /users/:id
|
||||
*/
|
||||
/** PUT /users/:id */
|
||||
updateUser: async (id: number, payload: UpdateUserPayload): Promise<User> => {
|
||||
await delay(800)
|
||||
// const res = await apiClient.put<User>(`/users/${id}`, payload)
|
||||
// return res.data
|
||||
|
||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
||||
if (idx === -1) throw new Error(`User ${id} not found`)
|
||||
MOCK_USERS[idx] = { ...MOCK_USERS[idx], ...payload, updatedAt: new Date().toISOString() }
|
||||
return MOCK_USERS[idx]
|
||||
const { data } = await apiClient.put<User>(`/users/${id}`, payload);
|
||||
return data;
|
||||
},
|
||||
|
||||
/**
|
||||
* DELETE /users/:id
|
||||
*/
|
||||
/** DELETE /users/:id */
|
||||
deleteUser: async (id: number): Promise<void> => {
|
||||
await delay(600)
|
||||
// await apiClient.delete(`/users/${id}`)
|
||||
|
||||
const idx = MOCK_USERS.findIndex((u) => u.id === id)
|
||||
if (idx !== -1) MOCK_USERS.splice(idx, 1)
|
||||
await apiClient.delete(`/users/${id}`);
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useMemo, useEffect, useCallback } from "react";
|
||||
import { useMemo, useEffect, useCallback, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { BentoGrid, BentoCard } from "@/components/bento";
|
||||
import { useCreateUser, useUpdateUser } from "../hooks/useAllUsers";
|
||||
import { useInfiniteRoles } from "@/features/roles/hooks/useRoles";
|
||||
import type { User } from "../api/allUsersApi";
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from "../schemas/allUser.schema";
|
||||
import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload, buildUpdatePayload } from "../schemas/allUser.schema";
|
||||
import type { AllUserFormData } from "../schemas/allUser.schema";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
@@ -50,6 +52,35 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
|
||||
const schema = useMemo(() => allUserFormSchema(mode, t), [mode, t, i18n.language]);
|
||||
|
||||
// ── Role infinite-scroll select ──
|
||||
const [roleSearch, setRoleSearch] = useState("");
|
||||
const roleQuery = useInfiniteRoles(roleSearch);
|
||||
|
||||
const roleSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (roleQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p.roles)
|
||||
.map((r) => ({ value: r.name, label: r.name }));
|
||||
|
||||
// Ensure the currently-selected role is present (edit mode), even if it
|
||||
// lives beyond the pages loaded so far.
|
||||
if (initialData) {
|
||||
const current = initialData.role;
|
||||
if (current && !opts.some((o) => o.value === current)) {
|
||||
opts.unshift({ value: current, label: current });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
options: opts,
|
||||
loading: roleQuery.isLoading,
|
||||
isLoadingMore: roleQuery.isFetchingNextPage,
|
||||
hasNextPage: !!roleQuery.hasNextPage,
|
||||
onLoadMore: () => roleQuery.fetchNextPage(),
|
||||
searchValue: roleSearch,
|
||||
onSearchChange: setRoleSearch,
|
||||
};
|
||||
}, [roleQuery, roleSearch, initialData]);
|
||||
|
||||
const {
|
||||
watch,
|
||||
setValue,
|
||||
@@ -65,11 +96,18 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
...DEFAULT_FORM_VALUES,
|
||||
username: initialData.username,
|
||||
name: initialData.name,
|
||||
phone: initialData.phone.replace(/^\+993[-\s]?/, ""),
|
||||
firstName: initialData.firstName ?? "",
|
||||
lastName: initialData.lastName ?? "",
|
||||
phone: initialData.phone.replace(/\D/g, "").slice(-8),
|
||||
email: initialData.email ?? "",
|
||||
avatar: initialData.avatar ?? "",
|
||||
role: initialData.role ?? "",
|
||||
socialFacebook: initialData.socialMedia?.facebook ?? "",
|
||||
socialInstagram: initialData.socialMedia?.instagram ?? "",
|
||||
socialTelegram: initialData.socialMedia?.telegram ?? "",
|
||||
lightMode: !!initialData.lightMode,
|
||||
password: "",
|
||||
phoneVerified: initialData.phoneVerified,
|
||||
isActive: initialData.isActive,
|
||||
active: !!initialData.active,
|
||||
}
|
||||
: DEFAULT_FORM_VALUES,
|
||||
});
|
||||
@@ -99,17 +137,11 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
if (mode === "create") {
|
||||
const payload = buildPayload(data);
|
||||
await createUser.mutateAsync(payload);
|
||||
navigate("/users");
|
||||
navigate("/all-users");
|
||||
} else {
|
||||
await updateUser.mutateAsync({
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
});
|
||||
navigate(`/users/${initialData!.id}`);
|
||||
const payload = buildUpdatePayload(data);
|
||||
await updateUser.mutateAsync(payload);
|
||||
navigate(`/all-users/${initialData!.id}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -145,6 +177,28 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.nameHint", "Doly ady we familiýasy")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.firstName", "Ady (at)")}
|
||||
value={form.firstName}
|
||||
onChange={(v) => setField("firstName", v)}
|
||||
placeholder={t("users.fields.firstName", "Ady (at)")}
|
||||
error={errors.firstName}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.lastName", "Familiýasy")}
|
||||
value={form.lastName}
|
||||
onChange={(v) => setField("lastName", v)}
|
||||
placeholder={t("users.fields.lastName", "Familiýasy")}
|
||||
error={errors.lastName}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="phone"
|
||||
@@ -170,6 +224,29 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground -mt-3">{t("users.fields.emailHint", "Islege görä")}</p>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<InfiniteSelect
|
||||
label={t("users.fields.role", "Roly")}
|
||||
value={form.role}
|
||||
onChange={(v) => setField("role", v)}
|
||||
placeholder={t("users.fields.role", "Roly")}
|
||||
error={errors.role}
|
||||
disabled={isPending}
|
||||
required
|
||||
{...roleSelect}
|
||||
/>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.avatar", "Awatar URL")}
|
||||
value={form.avatar}
|
||||
onChange={(v) => setField("avatar", v)}
|
||||
placeholder="https://..."
|
||||
error={errors.avatar}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</BentoCard>
|
||||
{mode === "create" && (
|
||||
<BentoCard>
|
||||
<FormInput
|
||||
@@ -187,18 +264,46 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
)}
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.phoneVerified", "Telefon tassyklanan")}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.phoneVerifiedHint", "SMS arkaly tassyklandy")}</p>
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.socialMedia", "Sosial media")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="phoneVerified"
|
||||
checked={form.phoneVerified}
|
||||
onCheckedChange={(v) => setField("phoneVerified", !!v)}
|
||||
<div className="flex flex-col gap-3">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.facebook", "Facebook")}
|
||||
value={form.socialFacebook}
|
||||
onChange={(v) => setField("socialFacebook", v)}
|
||||
placeholder="facebook.com/..."
|
||||
error={errors.socialFacebook}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<Label htmlFor="phoneVerified" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.phoneVerified ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.instagram", "Instagram")}
|
||||
value={form.socialInstagram}
|
||||
onChange={(v) => setField("socialInstagram", v)}
|
||||
placeholder="instagram.com/..."
|
||||
error={errors.socialInstagram}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("users.fields.telegram", "Telegram")}
|
||||
value={form.socialTelegram}
|
||||
onChange={(v) => setField("socialTelegram", v)}
|
||||
placeholder="t.me/..."
|
||||
error={errors.socialTelegram}
|
||||
disabled={isPending}
|
||||
/>
|
||||
</div>
|
||||
</BentoCard>
|
||||
<BentoCard>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-muted-foreground">{t("users.fields.lightMode", "Light režimi")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox id="lightMode" checked={form.lightMode} onCheckedChange={(v) => setField("lightMode", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="lightMode" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.lightMode ? t("common.yes", "Hawa") : t("common.no", "Ýok")}
|
||||
</Label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
@@ -208,9 +313,9 @@ export function UserForm({ mode, initialData }: UserFormProps) {
|
||||
<p className="text-xs text-muted-foreground">{t("users.fields.isActiveHint", "Ulanyjynyň ulgama girip-bilmezligi")}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(v) => setField("isActive", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.isActive ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
<Checkbox id="active" checked={form.active} onCheckedChange={(v) => setField("active", !!v)} disabled={isPending} />
|
||||
<Label htmlFor="active" className="text-sm text-muted-foreground cursor-pointer">
|
||||
{form.active ? t("common.active", "Işjeň") : t("common.inactive", "Işjeň däl")}
|
||||
</Label>
|
||||
</div>
|
||||
</BentoCard>
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
usersApi,
|
||||
type CreateUserPayload,
|
||||
type UpdateUserPayload,
|
||||
type UsersListParams,
|
||||
} from '../api/allUsersApi'
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import { usersApi, type CreateUserPayload, type UpdateUserPayload, type UsersListParams } from "../api/allUsersApi";
|
||||
|
||||
export const userKeys = {
|
||||
all: ['users'] as const,
|
||||
lists: () => [...userKeys.all, 'list'] as const,
|
||||
all: ["users"] as const,
|
||||
lists: () => [...userKeys.all, "list"] as const,
|
||||
list: (params: UsersListParams) => [...userKeys.lists(), params] as const,
|
||||
details: () => [...userKeys.all, 'detail'] as const,
|
||||
details: () => [...userKeys.all, "detail"] as const,
|
||||
detail: (id: number) => [...userKeys.details(), id] as const,
|
||||
}
|
||||
};
|
||||
|
||||
export function useUsers(params: UsersListParams = {}) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: UsersListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: userKeys.list(params),
|
||||
queryFn: () => usersApi.getUsers(params),
|
||||
queryKey: userKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => usersApi.getUsers(queryParams, signal),
|
||||
placeholderData: (prev) => prev,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUser(id: number) {
|
||||
@@ -29,45 +28,45 @@ export function useUser(id: number) {
|
||||
queryKey: userKeys.detail(id),
|
||||
queryFn: () => usersApi.getUserById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateUser() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: CreateUserPayload) => usersApi.createUser(payload),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
toast.success(t('users.toast.createSuccess', 'Ulanyjy üstünlikli döredildi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
toast.success(t("users.toast.createSuccess", "Ulanyjy üstünlikli döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUser(id: number) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: UpdateUserPayload) => usersApi.updateUser(id, payload),
|
||||
onSuccess: (updatedUser) => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
queryClient.setQueryData(userKeys.detail(id), updatedUser)
|
||||
toast.success(t('users.toast.updateSuccess', 'Ulanyjy üstünlikli täzelendi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
queryClient.setQueryData(userKeys.detail(id), updatedUser);
|
||||
toast.success(t("users.toast.updateSuccess", "Ulanyjy üstünlikli täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUser() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => usersApi.deleteUser(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
|
||||
toast.success(t('users.toast.deleteSuccess', 'Ulanyjy üstünlikli öçürildi'))
|
||||
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
|
||||
toast.success(t("users.toast.deleteSuccess", "Ulanyjy üstünlikli öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { z } from "zod";
|
||||
import type { CreateUserPayload } from "../api/allUsersApi";
|
||||
import type { CreateUserPayload, UpdateUserPayload } from "../api/allUsersApi";
|
||||
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
const urlSchema = (t: (key: string, fallback?: string) => string) =>
|
||||
z
|
||||
.string()
|
||||
.refine((v) => !v || /^(https?:\/\/|www\.|[\w.-]+\.[a-z]{2,})/i.test(v), t("validation.invalidUrl", "validation.invalidUrl"))
|
||||
.default("");
|
||||
|
||||
export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fallback?: string) => string) {
|
||||
const baseSchema = z.object({
|
||||
username: z.string().min(1, t("validation.required", "validation.required")).min(3, t("validation.minLength", "validation.minLength")),
|
||||
name: z.string().min(1, t("validation.required", "validation.required")),
|
||||
firstName: z.string().default(""),
|
||||
lastName: z.string().default(""),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, t("validation.required", "validation.required"))
|
||||
@@ -29,9 +37,14 @@ export function allUserFormSchema(mode: "create" | "edit", t: (key: string, fall
|
||||
.string()
|
||||
.refine((v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), t("validation.invalidEmail", "validation.invalidEmail"))
|
||||
.default(""),
|
||||
avatar: urlSchema(t),
|
||||
role: z.string().min(1, t("validation.required", "validation.required")),
|
||||
socialFacebook: urlSchema(t),
|
||||
socialInstagram: urlSchema(t),
|
||||
socialTelegram: urlSchema(t),
|
||||
lightMode: z.boolean(),
|
||||
password: z.string(),
|
||||
phoneVerified: z.boolean(),
|
||||
isActive: z.boolean(),
|
||||
active: z.boolean(),
|
||||
});
|
||||
|
||||
return mode === "create"
|
||||
@@ -49,21 +62,57 @@ export type AllUserFormData = z.infer<ReturnType<typeof allUserFormSchema>>;
|
||||
export const DEFAULT_FORM_VALUES: AllUserFormData = {
|
||||
username: "",
|
||||
name: "",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
avatar: "",
|
||||
role: "",
|
||||
socialFacebook: "",
|
||||
socialInstagram: "",
|
||||
socialTelegram: "",
|
||||
lightMode: false,
|
||||
password: "",
|
||||
phoneVerified: false,
|
||||
isActive: true,
|
||||
active: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: AllUserFormData): CreateUserPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
phone: data.phone.trim(),
|
||||
email: data.email.trim() || undefined,
|
||||
firstName: data.firstName.trim(),
|
||||
lastName: data.lastName.trim(),
|
||||
phone: data.phone.replace(/\s+/g, ""),
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
telegram: data.socialTelegram.trim(),
|
||||
},
|
||||
lightMode: data.lightMode ? 1 : 0,
|
||||
password: data.password,
|
||||
phoneVerified: data.phoneVerified,
|
||||
isActive: data.isActive,
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildUpdatePayload(data: AllUserFormData): UpdateUserPayload {
|
||||
return {
|
||||
username: data.username.trim(),
|
||||
name: data.name.trim(),
|
||||
firstName: data.firstName.trim(),
|
||||
lastName: data.lastName.trim(),
|
||||
phone: data.phone.replace(/\s+/g, ""),
|
||||
email: data.email.trim(),
|
||||
avatar: data.avatar.trim(),
|
||||
role: data.role.trim(),
|
||||
socialMedia: {
|
||||
facebook: data.socialFacebook.trim(),
|
||||
instagram: data.socialInstagram.trim(),
|
||||
telegram: data.socialTelegram.trim(),
|
||||
},
|
||||
lightMode: data.lightMode ? 1 : 0,
|
||||
active: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user