From 1f797661925518219849a3ffc145c4e467ee7abd Mon Sep 17 00:00:00 2001 From: "@jcarymuhammedow" Date: Fri, 15 May 2026 14:13:57 +0500 Subject: [PATCH] added zod validation --- PROJECT_STANDARDS.md | 10 + package-lock.json | 37 +- package.json | 3 + src/app/providers/ErrorBoundary.tsx | 74 ++ src/app/providers/QueryProvider.tsx | 26 +- src/app/providers/ThemeProvider.tsx | 14 + src/app/router/index.tsx | 4 + .../allUsers/components/allUsersForm.tsx | 144 ++-- .../allUsers/schemas/allUser.schema.ts | 55 ++ .../branches/components/branchesForm.tsx | 167 ++-- .../branches/schemas/branch.schema.ts | 68 ++ .../cardBalance/api/cardBalanceApi.ts | 2 +- .../components/cardBalanceForm.tsx | 87 +-- .../cardBalance/schemas/cardBalance.schema.ts | 30 + src/features/cardPins/api/cardPinApi.ts | 271 +++---- .../cardPins/components/cardPinForm.tsx | 191 ++--- .../cardPins/schemas/cardPin.schema.ts | 91 +++ .../cardReasons/components/reasonForm.tsx | 130 ++-- .../cardReasons/schemas/cardReason.schema.ts | 34 + .../cardRequisites/api/cardRequisitesApi.ts | 2 +- .../components/cardRequisiteForm.tsx | 143 +--- .../schemas/cardRequisite.schema.ts | 112 +++ .../api/cardTransactionsApi.ts | 2 +- .../components/cardTransactionForm.tsx | 97 +-- .../schemas/cardTransaction.schema.ts | 30 + .../cardTypes/components/cardTypesForm.tsx | 102 ++- .../cardTypes/schemas/cardType.schema.ts | 34 + .../clients/components/clientForm.tsx | 139 ++-- src/features/clients/schemas/client.schema.ts | 41 + .../components/currencyRatesForm.tsx | 112 ++- .../schemas/currencyRate.schema.ts | 27 + .../districts/components/districtsForm.tsx | 78 +- .../districts/schemas/district.schema.ts | 28 + .../api/loanOrderMobilesApi.ts | 725 ++++++++++-------- .../components/loanOrderMobileForm.tsx | 348 +++------ .../schemas/loanOrderMobile.schema.ts | 164 ++++ .../loanOrders/components/loanOrderForm.tsx | 354 +++------ .../loanOrders/schemas/loanOrder.schema.ts | 171 +++++ .../api/loanPaidOffLettersApi.ts | 93 +-- .../loanRemaining/api/loanRemainingApi.ts | 127 ++- .../components/LoanRemainingForm.tsx | 121 +-- .../schemas/loanRemaining.schema.ts | 25 + .../loanTypes/components/loanTypesForm.tsx | 156 ++-- .../loanTypes/schemas/loanType.schema.ts | 47 ++ .../operators/components/operatorForms.tsx | 138 ++-- .../operators/schemas/operator.schema.ts | 41 + .../orderNewCard/api/orderNewCardApi.ts | 2 +- .../components/orderNewCardForm.tsx | 235 ++---- .../schemas/orderNewCard.schema.ts | 138 ++++ .../components/requiredDocumentsForm.tsx | 127 ++- .../schemas/requiredDocument.schema.ts | 40 + .../components/sberPaymentsForm.tsx | 265 +++---- .../schemas/sberPayment.schema.ts | 126 +++ .../api/visaMasterPaymentsApi.ts | 317 ++++---- .../schemas/visaMasterPayment.schema.ts | 93 +++ .../components/visaMasterSberSettingsForm.tsx | 127 ++- .../schemas/visaMasterSberSetting.schema.ts | 24 + src/main.tsx | 14 +- 58 files changed, 3605 insertions(+), 2798 deletions(-) create mode 100644 src/app/providers/ErrorBoundary.tsx create mode 100644 src/app/providers/ThemeProvider.tsx create mode 100644 src/features/allUsers/schemas/allUser.schema.ts create mode 100644 src/features/branches/schemas/branch.schema.ts create mode 100644 src/features/cardBalance/schemas/cardBalance.schema.ts create mode 100644 src/features/cardPins/schemas/cardPin.schema.ts create mode 100644 src/features/cardReasons/schemas/cardReason.schema.ts create mode 100644 src/features/cardRequisites/schemas/cardRequisite.schema.ts create mode 100644 src/features/cardTransactions/schemas/cardTransaction.schema.ts create mode 100644 src/features/cardTypes/schemas/cardType.schema.ts create mode 100644 src/features/clients/schemas/client.schema.ts create mode 100644 src/features/currencyRates/schemas/currencyRate.schema.ts create mode 100644 src/features/districts/schemas/district.schema.ts create mode 100644 src/features/loanOrderMobiles/schemas/loanOrderMobile.schema.ts create mode 100644 src/features/loanOrders/schemas/loanOrder.schema.ts create mode 100644 src/features/loanRemaining/schemas/loanRemaining.schema.ts create mode 100644 src/features/loanTypes/schemas/loanType.schema.ts create mode 100644 src/features/operators/schemas/operator.schema.ts create mode 100644 src/features/orderNewCard/schemas/orderNewCard.schema.ts create mode 100644 src/features/requiredDocuments/schemas/requiredDocument.schema.ts create mode 100644 src/features/sberPayments/schemas/sberPayment.schema.ts create mode 100644 src/features/visaMasterPayments/schemas/visaMasterPayment.schema.ts create mode 100644 src/features/visaMasterSberSettings/schemas/visaMasterSberSetting.schema.ts diff --git a/PROJECT_STANDARDS.md b/PROJECT_STANDARDS.md index 41bb536..bc2dca9 100644 --- a/PROJECT_STANDARDS.md +++ b/PROJECT_STANDARDS.md @@ -107,3 +107,13 @@ src/ 2. **Çakışma Önleme:** Aynı anda birden fazla 401 gelirse, `isRefreshing` bayrağı ile diğer istekler beklemede tutulur. - **Başarısız Refresh:** Yeni token alınamazsa (`refreshToken` hata dönerse), sistem kullanıcıyı otomatik olarak çıkışa zorlar (`logout()`) ve kullanıcıyı Login sayfasına yönlendirir. - **403 Forbidden:** Kullanıcının o sayfaya erişim izni yoksa (Rol yetkisi eksik), toast ile uyarı verilir ancak kullanıcı aynı sayfada kalır (Kritik sayfadan atılmaz). +10. **Error Boundary Kuralları:** + - Her sayfa route'u `PageErrorBoundary` ile sarılır. + - App kökü `GlobalErrorBoundary` ile sarılır. + - Boş ekran göstermek **yasaktır**; her boundary anlamlı fallback UI döner. +11. **Zod + RHF Kuralları:** + - Her form için `src/features/[feature]/schemas/[feature].schema.ts` oluşturulur. + - Manuel `if/else` validation **kesinlikle yasaktır**. + - `zodResolver` dışında resolver kullanılamaz. + - Server hataları `setError()` ile ilgili field'a atanır. + - `z.infer` ile tip üretilir; ayrıca tip yazmak **yasaktır**. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 863fdec..e4bca92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@fontsource-variable/geist": "^5.2.8", "@fontsource-variable/inter": "^5.2.8", + "@hookform/resolvers": "^5.2.2", "@tanstack/react-query": "^5.100.8", "@tanstack/react-table": "^8.21.3", "@tiptap/extension-link": "^3.23.2", @@ -26,6 +27,7 @@ "react": "^19.2.5", "react-day-picker": "^9.14.0", "react-dom": "^19.2.5", + "react-hook-form": "^7.75.0", "react-i18next": "^17.0.6", "react-router-dom": "^7.14.2", "recharts": "^3.8.0", @@ -35,6 +37,7 @@ "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0", "vaul": "^1.1.2", + "zod": "^4.4.3", "zustand": "^5.0.12" }, "devDependencies": { @@ -888,6 +891,18 @@ "hono": "^4" } }, + "node_modules/@hookform/resolvers": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz", + "integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==", + "license": "MIT", + "dependencies": { + "@standard-schema/utils": "^0.3.0" + }, + "peerDependencies": { + "react-hook-form": "^7.55.0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -8315,6 +8330,22 @@ "react": "^19.2.5" } }, + "node_modules/react-hook-form": { + "version": "7.75.0", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.75.0.tgz", + "integrity": "sha512-Ovv94H+0p3sJ7B9B5QxPuCP1u8V/cHuVGyH55cSwodYDtoJwK+fqk3vjfIgSX59I2U/bU4z0nRJ9HMLpNiWEmw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/react-hook-form" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19" + } + }, "node_modules/react-i18next": { "version": "17.0.6", "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.6.tgz", @@ -9879,9 +9910,9 @@ } }, "node_modules/zod": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.2.tgz", - "integrity": "sha512-IynmDyxsEsb9RKzO3J9+4SxXnl2FTFSzNBaKKaMV6tsSk0rw9gYw9gs+JFCq/qk2LCZ78KDwyj+Z289TijSkUw==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index 3d53708..8cfbe38 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dependencies": { "@fontsource-variable/geist": "^5.2.8", "@fontsource-variable/inter": "^5.2.8", + "@hookform/resolvers": "^5.2.2", "@tanstack/react-query": "^5.100.8", "@tanstack/react-table": "^8.21.3", "@tiptap/extension-link": "^3.23.2", @@ -28,6 +29,7 @@ "react": "^19.2.5", "react-day-picker": "^9.14.0", "react-dom": "^19.2.5", + "react-hook-form": "^7.75.0", "react-i18next": "^17.0.6", "react-router-dom": "^7.14.2", "recharts": "^3.8.0", @@ -37,6 +39,7 @@ "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0", "vaul": "^1.1.2", + "zod": "^4.4.3", "zustand": "^5.0.12" }, "devDependencies": { diff --git a/src/app/providers/ErrorBoundary.tsx b/src/app/providers/ErrorBoundary.tsx new file mode 100644 index 0000000..99af975 --- /dev/null +++ b/src/app/providers/ErrorBoundary.tsx @@ -0,0 +1,74 @@ +import { Component, type ErrorInfo, type ReactNode } from 'react' + +interface ErrorBoundaryProps { + children: ReactNode + fallback?: ReactNode +} + +interface ErrorBoundaryState { + hasError: boolean + error: Error | null +} + +class ErrorBoundary extends Component { + constructor(props: ErrorBoundaryProps) { + super(props) + this.state = { hasError: false, error: null } + } + + static getDerivedStateFromError(error: Error) { + return { hasError: true, error } + } + + componentDidCatch(error: Error, errorInfo: ErrorInfo) { + console.error('ErrorBoundary:', error, errorInfo) + } + + render() { + if (this.state.hasError) { + if (this.props.fallback) return this.props.fallback + return ( +
+
+

Something went wrong

+

{this.state.error?.message}

+ +
+
+ ) + } + return this.props.children + } +} + +const pageErrorFallback = ( +
+
+

Page Error

+

An unexpected error occurred on this page.

+ +
+
+) + +export function GlobalErrorBoundary({ children }: { children: ReactNode }) { + return {children} +} + +export function PageErrorBoundary({ children }: { children: ReactNode }) { + return {children} +} + +export function PageErrorFallback() { + return pageErrorFallback +} diff --git a/src/app/providers/QueryProvider.tsx b/src/app/providers/QueryProvider.tsx index 9032a92..7758aaf 100644 --- a/src/app/providers/QueryProvider.tsx +++ b/src/app/providers/QueryProvider.tsx @@ -2,23 +2,28 @@ import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@ta import type { ReactNode } from 'react' import { toast } from 'sonner' import i18next from 'i18next' +import { isAxiosError } from 'axios' + +function getErrorMessage(error: Error): string | undefined { + if (isAxiosError(error)) return error.response?.data?.message + return error.message +} const queryClient = new QueryClient({ queryCache: new QueryCache({ - onError: (error: any, query) => { - // Eğer sorguya özel gizlilik istenmediyse tekilleştirilmiş toast göster + onError: (error, query) => { if (query.meta?.silent !== true) { - const serverMessage = error?.response?.data?.message + const serverMessage = getErrorMessage(error) toast.error(serverMessage || i18next.t('errors.fetchFailed'), { - id: 'global-query-error', // Aynı ID'li toast'lar üst üste binmez + id: 'global-query-error', }) } }, }), mutationCache: new MutationCache({ - onError: (error: any, _variables, _context, mutation) => { + onError: (error, _variables, _context, mutation) => { if (mutation.meta?.silent !== true) { - const serverMessage = error?.response?.data?.message + const serverMessage = getErrorMessage(error) toast.error(serverMessage || i18next.t('errors.actionFailed'), { id: 'global-mutation-error', }) @@ -27,11 +32,10 @@ const queryClient = new QueryClient({ }), defaultOptions: { queries: { - staleTime: 1000 * 60 * 5, // 5 min - gcTime: 1000 * 60 * 10, // 10 min - retry: (failureCount, error: any) => { - // Kritik auth veya bulunamadı hatalarında boşa retry atıp ağı yorma - if ([401, 403, 404].includes(error.response?.status)) return false + staleTime: 1000 * 60 * 5, + gcTime: 1000 * 60 * 10, + retry: (failureCount, error) => { + if (isAxiosError(error) && [401, 403, 404].includes(error.response?.status ?? 0)) return false return failureCount < 1 }, refetchOnWindowFocus: false, diff --git a/src/app/providers/ThemeProvider.tsx b/src/app/providers/ThemeProvider.tsx new file mode 100644 index 0000000..6339c3c --- /dev/null +++ b/src/app/providers/ThemeProvider.tsx @@ -0,0 +1,14 @@ +import { ThemeProvider as NextThemesProvider } from 'next-themes' +import type { ReactNode } from 'react' + +interface ThemeProviderProps { + children: ReactNode +} + +export function ThemeProvider({ children }: ThemeProviderProps) { + return ( + + {children} + + ) +} diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index d3345b2..dd0cfd1 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -3,6 +3,7 @@ import { createBrowserRouter, Navigate, Outlet } from "react-router-dom"; import { useAuthStore } from "../store/authStore"; import { Spinner } from "@/components/ui/spinner"; import { DashboardLayout } from "@/layouts/DashboardLayout"; +import { PageErrorFallback } from "@/app/providers/ErrorBoundary"; import NotFoundPage from "@/pages/notFoundPage"; const LoginPage = lazy(() => import("@/pages/login")); @@ -146,6 +147,7 @@ function PageLoader() { export const router = createBrowserRouter([ { element: , + errorElement: , children: [ { path: "/login", @@ -159,9 +161,11 @@ export const router = createBrowserRouter([ }, { element: , + errorElement: , children: [ { element: , + errorElement: , children: [ { path: "/dashboard", diff --git a/src/features/allUsers/components/allUsersForm.tsx b/src/features/allUsers/components/allUsersForm.tsx index dd3787a..8babe68 100644 --- a/src/features/allUsers/components/allUsersForm.tsx +++ b/src/features/allUsers/components/allUsersForm.tsx @@ -1,12 +1,16 @@ -import { useEffect, useState } from 'react' +import { useMemo } 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 { Checkbox } from '@/components/ui/checkbox' import { Label } from '@/components/ui/label' import { FormActions } from '@/components/formActions' import { useCreateUser, useUpdateUser } from '../hooks/useAllUsers' -import type { User, CreateUserPayload, UpdateUserPayload } from '../api/allUsersApi' +import type { User } from '../api/allUsersApi' +import { allUserFormSchema, DEFAULT_FORM_VALUES, buildPayload } from '../schemas/allUser.schema' +import type { AllUserFormData } from '../schemas/allUser.schema' // ─── Types ──────────────────────────────────────────────────────────────────── @@ -16,47 +20,17 @@ interface UserFormProps { userId?: number } -interface FormState { - username: string - name: string - phone: string - email: string - password: string - phoneVerified: boolean - isActive: boolean -} +// ─── Helpers ────────────────────────────────────────────────────────────────── -interface FormErrors { - username?: string - name?: string - phone?: string - email?: string - password?: string -} +type FlatErrors = Partial> -// ─── Validation ─────────────────────────────────────────────────────────────── - -function validateForm(state: FormState, mode: 'create' | 'edit'): FormErrors { - const errors: FormErrors = {} - - if (!state.username.trim()) errors.username = 'Ulanyjy ady hökmany' - else if (state.username.length < 3) errors.username = 'Ulanyjy ady iň az 3 harp bolmaly' - - if (!state.name.trim()) errors.name = 'Ady hökmany' - - if (!state.phone.trim()) errors.phone = 'Telefon hökmany' - else if (!/^\d[\d\s-]{6,}$/.test(state.phone)) errors.phone = 'Nädogry telefon formaty' - - if (state.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(state.email)) { - errors.email = 'Nädogry e-poçta formaty' +function flattenErrors(errors: Record): FlatErrors { + const result: FlatErrors = {} + for (const key of Object.keys(errors)) { + const msg = errors[key]?.message + if (msg) result[key as keyof AllUserFormData] = msg } - - if (mode === 'create') { - if (!state.password) errors.password = 'Açar sözi hökmany' - else if (state.password.length < 6) errors.password = 'Açar sözi iň az 6 harp bolmaly' - } - - return errors + return result } // ─── UserForm ───────────────────────────────────────────────────────────────── @@ -70,69 +44,53 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) { const isPending = createUser.isPending || updateUser.isPending - const [form, setForm] = useState({ - username: '', - name: '', - phone: '', - email: '', - password: '', - phoneVerified: false, - isActive: true, + const schema = useMemo(() => allUserFormSchema(mode), [mode]) + + const { + watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger, + } = useForm({ + resolver: zodResolver(schema as any), + defaultValues: initialData + ? { + ...DEFAULT_FORM_VALUES, + username: initialData.username, + name: initialData.name, + phone: initialData.phone.replace(/^\+993[-\s]?/, ''), + email: initialData.email ?? '', + password: '', + phoneVerified: initialData.phoneVerified, + isActive: initialData.isActive, + } + : DEFAULT_FORM_VALUES, }) - const [errors, setErrors] = useState({}) + const form = watch() + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) - // Populate form when initialData is available (edit mode) - useEffect(() => { - if (initialData) { - setForm({ - username: initialData.username, - name: initialData.name, - phone: initialData.phone.replace(/^\+993[-\s]?/, ''), - email: initialData.email ?? '', - password: '', - phoneVerified: initialData.phoneVerified, - isActive: initialData.isActive, - }) - } - }, [initialData]) - - const setField = (key: K, value: FormState[K]) => { - setForm((prev) => ({ ...prev, [key]: value })) - if (errors[key as keyof FormErrors]) { - setErrors((prev) => ({ ...prev, [key]: undefined })) - } + const setField = (key: K, value: AllUserFormData[K]) => { + (setValue as (name: K, val: AllUserFormData[K]) => void)(key, value) + clearErrors(key) } const handleSubmit = async () => { - const validationErrors = validateForm(form, mode) - if (Object.keys(validationErrors).length > 0) { - setErrors(validationErrors) - return - } + const isValid = await trigger() + if (!isValid) return + + const data = getValues() if (mode === 'create') { - const payload: CreateUserPayload = { - username: form.username.trim(), - name: form.name.trim(), - phone: form.phone.trim(), - email: form.email.trim() || undefined, - password: form.password, - phoneVerified: form.phoneVerified, - isActive: form.isActive, - } + const payload = buildPayload(data) await createUser.mutateAsync(payload) navigate('/users') } else { - const payload: UpdateUserPayload = { - username: form.username.trim(), - name: form.name.trim(), - phone: form.phone.trim(), - email: form.email.trim() || undefined, - phoneVerified: form.phoneVerified, - isActive: form.isActive, - } - await updateUser.mutateAsync(payload) + 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/${userId}`) } } @@ -309,4 +267,4 @@ export function UserForm({ mode, initialData, userId }: UserFormProps) { /> ) -} \ No newline at end of file +} diff --git a/src/features/allUsers/schemas/allUser.schema.ts b/src/features/allUsers/schemas/allUser.schema.ts new file mode 100644 index 0000000..9a7e62f --- /dev/null +++ b/src/features/allUsers/schemas/allUser.schema.ts @@ -0,0 +1,55 @@ +import { z } from 'zod' +import type { CreateUserPayload } from '../api/allUsersApi' + +const baseSchema = z.object({ + username: z.string() + .min(1, 'Ulanyjy ady hökmany') + .min(3, 'Ulanyjy ady iň az 3 harp bolmaly'), + name: z.string().min(1, 'Ady hökmany'), + phone: z.string() + .min(1, 'Telefon hökmany') + .regex(/^\d[\d\s-]{6,}$/, 'Nädogry telefon formaty'), + email: z.string() + .refine( + (v) => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), + 'Nädogry e-poçta formaty', + ) + .default(''), + password: z.string(), + phoneVerified: z.boolean(), + isActive: z.boolean(), +}) + +export function allUserFormSchema(mode: 'create' | 'edit') { + return mode === 'create' + ? baseSchema.extend({ + password: z.string() + .min(1, 'Açar sözi hökmany') + .min(6, 'Açar sözi iň az 6 harp bolmaly'), + }) + : baseSchema +} + +export type AllUserFormData = z.infer + +export const DEFAULT_FORM_VALUES: AllUserFormData = { + username: '', + name: '', + phone: '', + email: '', + password: '', + phoneVerified: false, + isActive: 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, + password: data.password, + phoneVerified: data.phoneVerified, + isActive: data.isActive, + } +} diff --git a/src/features/branches/components/branchesForm.tsx b/src/features/branches/components/branchesForm.tsx index 6bbcaef..000fee9 100644 --- a/src/features/branches/components/branchesForm.tsx +++ b/src/features/branches/components/branchesForm.tsx @@ -1,6 +1,7 @@ import { useState, useCallback, useMemo } from 'react' import { useNavigate } from 'react-router-dom' import { useTranslation } from 'react-i18next' +import { useForm } from 'react-hook-form' import { toast } from 'sonner' import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react' import type { LucideIcon } from 'lucide-react' @@ -9,26 +10,23 @@ import { Button } from '@/components/ui/button' import { Checkbox } from '@/components/ui/checkbox' import { StepBarCards, type StepCardItem } from '@/components/stepBarV2' import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches' -import type { Branch, CreateBranchPayload } from '@/features/branches/api/branchesApi' +import type { Branch } from '@/features/branches/api/branchesApi' import { getDistrictOptions } from '@/features/branches/api/branchesApi' +import { validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema' +import type { BranchFormData } from '@/features/branches/schemas/branch.schema' -interface FormState { - nameTk: string - nameRu: string - nameEn: string - code: string - districtId: string - addressTk: string - addressRu: string - addressEn: string - phone: string - email: string - workingHours: string - description: string - isActive: boolean +type FlatErrors = Partial> + +function flattenErrors(errors: Record): FlatErrors { + const result: FlatErrors = {} + for (const key of Object.keys(errors)) { + const msg = errors[key]?.message + if (msg) result[key as keyof BranchFormData] = msg + } + return result } -type FormErrors = Partial> +type FormErrors = FlatErrors type LangKey = 'tk' | 'ru' | 'en' @@ -45,36 +43,7 @@ interface StepDef { shortLabel: string icon: LucideIcon subtitle: string - validate: (form: FormState) => FormErrors -} - -const INITIAL_STATE: FormState = { - nameTk: '', nameRu: '', nameEn: '', - code: '', - districtId: '', - addressTk: '', addressRu: '', addressEn: '', - phone: '', email: '', - workingHours: '', - description: '', - isActive: true, -} - -function mapToFormState(data: Branch): FormState { - return { - nameTk: data.name.tk, - nameRu: data.name.ru, - nameEn: data.name.en, - code: data.code, - districtId: String(data.districtId), - addressTk: data.address.tk, - addressRu: data.address.ru, - addressEn: data.address.en, - phone: data.phone, - email: data.email, - workingHours: data.workingHours, - description: data.description ?? '', - isActive: data.isActive, - } + validate: (form: BranchFormData, mode: 'create' | 'edit') => FlatErrors } const STEPS: StepDef[] = [ @@ -85,15 +54,7 @@ const STEPS: StepDef[] = [ shortLabel: 'Esasy', icon: Building2, subtitle: 'Ady, kody, etrapy', - validate: (form) => { - const e: FormErrors = {} - if (!form.nameTk.trim()) e.nameTk = 'Türkmen ady — hökmany' - if (!form.nameRu.trim()) e.nameRu = 'Rus ady — hökmany' - if (!form.nameEn.trim()) e.nameEn = 'Iňlis ady — hökmany' - if (!form.code.trim()) e.code = 'Kod — hökmany' - if (!form.districtId) e.districtId = 'Etrap — hökmany' - return e - }, + validate: (form, mode) => validateStep(0, form, mode), }, { id: 'address', @@ -102,15 +63,7 @@ const STEPS: StepDef[] = [ shortLabel: 'Salgy', icon: MapPin, subtitle: 'Salgy, telefon, e-poçta', - validate: (form) => { - const e: FormErrors = {} - if (!form.addressTk.trim()) e.addressTk = 'Türkmen salgysy — hökmany' - if (!form.addressRu.trim()) e.addressRu = 'Rus salgysy — hökmany' - if (!form.addressEn.trim()) e.addressEn = 'Iňlis salgysy — hökmany' - if (!form.phone.trim()) e.phone = 'Telefon — hökmany' - if (!form.email.trim()) e.email = 'E-poçta — hökmany' - return e - }, + validate: (form, mode) => validateStep(1, form, mode), }, { id: 'hours', @@ -119,18 +72,14 @@ const STEPS: StepDef[] = [ shortLabel: 'Wagt', icon: Clock, subtitle: 'Iş wagty we bellikler', - validate: (form) => { - const e: FormErrors = {} - if (!form.workingHours.trim()) e.workingHours = 'Iş wagty — hökmany' - return e - }, + validate: (form, mode) => validateStep(2, form, mode), }, ] interface StepContentProps { - form: FormState - errors: FormErrors - set: (k: K, v: FormState[K]) => void + form: BranchFormData + errors: FlatErrors + set: (k: K, v: BranchFormData[K]) => void activeLang: LangKey setActiveLang: (l: LangKey) => void } @@ -296,6 +245,24 @@ export interface BranchFormProps { branchId?: number } +function mapInitial(data: Branch): Partial { + return { + nameTk: data.name.tk, + nameRu: data.name.ru, + nameEn: data.name.en, + code: data.code, + districtId: String(data.districtId), + addressTk: data.address.tk, + addressRu: data.address.ru, + addressEn: data.address.en, + phone: data.phone, + email: data.email, + workingHours: data.workingHours, + description: data.description ?? '', + isActive: data.isActive, + } +} + export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { const { t } = useTranslation() const navigate = useNavigate() @@ -305,25 +272,31 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { const isPending = createMutation.isPending || updateMutation.isPending const [activeLang, setActiveLang] = useState('tk') - const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE) - const [errors, setErrors] = useState({}) + + const { + watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, + } = useForm({ defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES }) + + const form = watch() + const errors = useMemo(() => flattenErrors(rhfErrors as Record), [rhfErrors]) + const [currentStep, setCurrentStep] = useState(0) const [visited, setVisited] = useState>( - () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set() + () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(), ) const stepsWithErrors = useMemo(() => { const out = new Set() visited.forEach((i) => { - if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i) + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) out.add(i) }) return out - }, [form, visited]) + }, [form, mode, visited]) - const set = useCallback((key: K, value: FormState[K]) => { - setForm((prev) => ({ ...prev, [key]: value })) - setErrors((prev) => ({ ...prev, [key]: undefined })) - }, []) + const set = useCallback((key: K, value: BranchFormData[K]) => { + (setValue as (name: K, val: BranchFormData[K]) => void)(key, value) + clearErrors(key) + }, [setValue, clearErrors]) const stepProps = useMemo(() => ({ form, errors, set, activeLang, setActiveLang }), [form, errors, set, activeLang]) @@ -332,13 +305,11 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { const handleNext = () => { markVisited(currentStep) - const errs = STEPS[currentStep].validate(form) + const errs = STEPS[currentStep].validate(form, mode) if (Object.keys(errs).length > 0) { - setErrors(errs) toast.error('Dogry maglumat girizmegiňizi haýyş edýäris.') return } - setErrors({}) if (currentStep < STEPS.length - 1) { setCurrentStep(currentStep + 1) window.scrollTo({ top: 0, behavior: 'smooth' }) @@ -348,7 +319,6 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { const handleBack = () => { if (currentStep > 0) { markVisited(currentStep) - setErrors({}) setCurrentStep(currentStep - 1) window.scrollTo({ top: 0, behavior: 'smooth' }) } @@ -356,40 +326,27 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { const handleGoTo = (i: number) => { markVisited(currentStep) - setErrors({}) setCurrentStep(i) window.scrollTo({ top: 0, behavior: 'smooth' }) } - const handleSubmit = () => { + const doSubmit = () => { setVisited(new Set(STEPS.map((_, i) => i))) - const allErrors: FormErrors = {} - for (const step of STEPS) Object.assign(allErrors, step.validate(form)) + const allErrors: FlatErrors = {} + for (const step of STEPS) Object.assign(allErrors, step.validate(form, mode)) if (Object.keys(allErrors).length > 0) { - setErrors(allErrors) toast.error('Käbir hökmany meýdanlar doldurylan däldir.') for (let i = 0; i < STEPS.length; i++) { - if (Object.keys(STEPS[i].validate(form)).length > 0) { - setCurrentStep(i) - break + if (Object.keys(STEPS[i].validate(form, mode)).length > 0) { + setCurrentStep(i); break } } return } - const payload: CreateBranchPayload = { - name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn }, - code: form.code, - districtId: Number(form.districtId), - address: { tk: form.addressTk, ru: form.addressRu, en: form.addressEn }, - phone: form.phone, - email: form.email, - workingHours: form.workingHours, - description: form.description.trim() || null, - isActive: form.isActive, - } + const payload = buildPayload(getValues()) if (mode === 'create') { createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') }) @@ -466,7 +423,7 @@ export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { {isLastStep ? ( -