diff --git a/public/Inter-Italic-VariableFont_opsz,wght.ttf b/public/Inter-Italic-VariableFont_opsz,wght.ttf new file mode 100644 index 0000000..43ed4f5 Binary files /dev/null and b/public/Inter-Italic-VariableFont_opsz,wght.ttf differ diff --git a/public/Inter-VariableFont_opsz,wght.ttf b/public/Inter-VariableFont_opsz,wght.ttf new file mode 100644 index 0000000..e31b51e Binary files /dev/null and b/public/Inter-VariableFont_opsz,wght.ttf differ diff --git a/src/app/router/index.tsx b/src/app/router/index.tsx index 6439dd7..fc5bed7 100644 --- a/src/app/router/index.tsx +++ b/src/app/router/index.tsx @@ -157,6 +157,16 @@ const CardTypeCreatePage = lazy(() => import("@/pages/settings/card/cardTypesCre const CardTypesViewPage = lazy(() => import("@/pages/settings/card/cardTypesView")); const CardTypeEditPage = lazy(() => import("@/pages/settings/card/cardTypesEdit")); +const DistrictsPage = lazy(() => import("@/pages/settings/location/districts")); +const DistrictCreatePage = lazy(() => import("@/pages/settings/location/districtsCreate")); +const DistrictsViewPage = lazy(() => import("@/pages/settings/location/districtsView")); +const DistrictEditPage = lazy(() => import("@/pages/settings/location/districtsEdit")); + +const BranchesPage = lazy(() => import("@/pages/settings/location/branches")); +const BranchCreatePage = lazy(() => import("@/pages/settings/location/branchesCreate")); +const BranchesViewPage = lazy(() => import("@/pages/settings/location/branchesView")); +const BranchEditPage = lazy(() => import("@/pages/settings/location/branchesEdit")); + function AuthGuard() { const isAuthenticated = useAuthStore((s) => s.isAuthenticated); if (!isAuthenticated) return ; @@ -901,6 +911,70 @@ export const router = createBrowserRouter([ ), }, + { // Sidebar: /settings/location/districts + path: "/settings/location/districts", + element: ( + }> + + + ), + }, + { + path: "/settings/location/districts/create", + element: ( + }> + + + ), + }, + { + path: "/settings/location/districts/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/location/districts/:id/edit", + element: ( + }> + + + ), + }, + { // Sidebar: /settings/location/branches + path: "/settings/location/branches", + element: ( + }> + + + ), + }, + { + path: "/settings/location/branches/create", + element: ( + }> + + + ), + }, + { + path: "/settings/location/branches/:id", + element: ( + }> + + + ), + }, + { + path: "/settings/location/branches/:id/edit", + element: ( + }> + + + ), + }, ], }, ], diff --git a/src/features/branches/api/branchesApi.ts b/src/features/branches/api/branchesApi.ts new file mode 100644 index 0000000..421f1f6 --- /dev/null +++ b/src/features/branches/api/branchesApi.ts @@ -0,0 +1,172 @@ +export interface Branch { + id: number + name: Record<'tk' | 'ru' | 'en', string> + code: string + districtId: number + districtName: Record<'tk' | 'ru' | 'en', string> + address: Record<'tk' | 'ru' | 'en', string> + phone: string + email: string + workingHours: string + description: string | null + isActive: boolean +} + +export interface BranchListResponse { + data: Branch[] + total: number + page: number + perPage: number +} + +export interface CreateBranchPayload { + name: Record<'tk' | 'ru' | 'en', string> + code: string + districtId: number + address: Record<'tk' | 'ru' | 'en', string> + phone: string + email: string + workingHours: string + description: string | null + isActive: boolean +} + +export interface UpdateBranchPayload extends CreateBranchPayload { + id: number +} + +const DISTRICTS = [ + { id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' } }, + { id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' } }, + { id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' } }, + { id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' } }, + { id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' } }, + { id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' } }, + { id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' } }, +] + +export function getDistrictOptions() { + return DISTRICTS +} + +function findDistrict(id: number) { + return DISTRICTS.find((d) => d.id === id) ?? DISTRICTS[0] +} + +const MOCK_BRANCHES: Branch[] = [ + { + id: 1, + name: { tk: 'Merkezi şahamça', ru: 'Главное отделение', en: 'Main branch' }, + code: 'BR-001', + districtId: 1, + districtName: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' }, + address: { tk: 'Bitarap Türkmenistan şaýoly, 100', ru: 'Проспект Битарap Туркменистан, 100', en: 'Bitarap Turkmenistan avenue, 100' }, + phone: '+993 12 45-67-89', + email: 'main@tbbank.gov.tm', + workingHours: '09:00 - 18:00', + description: null, + isActive: true, + }, + { + id: 2, + name: { tk: 'Mary şahamçasy', ru: 'Марыйское отделение', en: 'Mary branch' }, + code: 'BR-002', + districtId: 5, + districtName: { tk: 'Mary', ru: 'Мары', en: 'Mary' }, + address: { tk: 'Gurbansoltan eje köçesi, 25', ru: 'Улица Гурбансолтан эдже, 25', en: 'Gurbansoltan eje street, 25' }, + phone: '+993 55 12-34-56', + email: 'mary@tbbank.gov.tm', + workingHours: '09:00 - 17:00', + description: null, + isActive: true, + }, + { + id: 3, + name: { tk: 'Daşoguz şahamçasy', ru: 'Дашогузское отделение', en: 'Dashoguz branch' }, + code: 'BR-003', + districtId: 4, + districtName: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' }, + address: { tk: 'Garaşsyzlyk köçesi, 10', ru: 'Улица Гарашсызлык, 10', en: 'Garashsyzlyk street, 10' }, + phone: '+993 32 98-76-54', + email: 'dashoguz@tbbank.gov.tm', + workingHours: '08:30 - 17:30', + description: 'Şenbe güni 09:00 - 13:00', + isActive: false, + }, +] + +let mockStore = [...MOCK_BRANCHES] +let nextId = 4 + +const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)) + +export async function fetchBranches(params: { + page?: number + perPage?: number + search?: string + isActive?: string + districtId?: string +}): Promise { + await delay() + const { page = 1, perPage = 25, search = '', isActive, districtId } = params + + let filtered = mockStore.filter((item) => { + const matchSearch = + !search || + Object.values(item.name).some((n) => + n.toLowerCase().includes(search.toLowerCase()) + ) || + item.code.toLowerCase().includes(search.toLowerCase()) + const matchActive = + isActive === '' || isActive === undefined + ? true + : isActive === 'true' + ? item.isActive + : !item.isActive + const matchDistrict = + !districtId || String(item.districtId) === districtId + return matchSearch && matchActive && matchDistrict + }) + + filtered = [...filtered].sort((a, b) => b.id - a.id) + + const total = filtered.length + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage } +} + +export async function fetchBranchById(id: number): Promise { + await delay() + const item = mockStore.find((c) => c.id === id) + if (!item) throw new Error('Not found') + return { ...item } +} + +export async function createBranch(payload: CreateBranchPayload): Promise { + await delay(400) + const district = findDistrict(payload.districtId) + const newItem: Branch = { + id: nextId++, + ...payload, + districtName: district.name, + } + mockStore = [newItem, ...mockStore] + return newItem +} + +export async function updateBranch(payload: UpdateBranchPayload): Promise { + await delay(400) + const idx = mockStore.findIndex((c) => c.id === payload.id) + if (idx === -1) throw new Error('Not found') + const district = findDistrict(payload.districtId) + const updated = { ...mockStore[idx], ...payload, districtName: district.name } + mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c)) + return updated +} + +export async function deleteBranch(id: number): Promise { + await delay(300) + mockStore = mockStore.filter((c) => c.id !== id) +} diff --git a/src/features/branches/components/branchesForm.tsx b/src/features/branches/components/branchesForm.tsx new file mode 100644 index 0000000..6bbcaef --- /dev/null +++ b/src/features/branches/components/branchesForm.tsx @@ -0,0 +1,492 @@ +import { useState, useCallback, useMemo } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { ChevronLeft, ChevronRight, Loader2, Building2, MapPin, Clock } from 'lucide-react' +import type { LucideIcon } from 'lucide-react' +import { FormInput } from '@/components/formInput' +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 { getDistrictOptions } from '@/features/branches/api/branchesApi' + +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 FormErrors = Partial> + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +interface StepDef { + id: string + titleKey: string + titleFallback: string + 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, + } +} + +const STEPS: StepDef[] = [ + { + id: 'basic', + titleKey: 'branches.steps.basic', + titleFallback: 'Esasy maglumatlar', + 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 + }, + }, + { + id: 'address', + titleKey: 'branches.steps.address', + titleFallback: 'Salgy we habarlaşmak', + 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 + }, + }, + { + id: 'hours', + titleKey: 'branches.steps.hours', + titleFallback: 'Iş wagty', + 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 + }, + }, +] + +interface StepContentProps { + form: FormState + errors: FormErrors + set: (k: K, v: FormState[K]) => void + activeLang: LangKey + setActiveLang: (l: LangKey) => void +} + +function StepBasic({ form, errors, set, activeLang, setActiveLang }: StepContentProps) { + const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'nameTk' | 'nameRu' | 'nameEn' + const nameErrorKey = nameFieldKey as keyof FormErrors + + return ( +
+
+ {LANG_TABS.map((tab) => ( + + ))} +
+ +
+ set(nameFieldKey, v)} + placeholder="Şahamçanyň ady" + error={errors[nameErrorKey]} + /> + set('code', v)} + placeholder="BR-XXX" + error={errors.code} + /> +
+ +
+ set('districtId', v)} + options={getDistrictOptions().map((d) => ({ value: String(d.id), label: d.name.tk }))} + placeholder="Etrap saýlaň" + error={errors.districtId} + /> +
+
+ set('isActive', !!checked)} + /> + +
+
+
+
+ ) +} + +function StepAddress({ form, errors, set, activeLang, setActiveLang }: StepContentProps) { + const addrFieldKey = `address${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as 'addressTk' | 'addressRu' | 'addressEn' + const addrErrorKey = addrFieldKey as keyof FormErrors + + return ( +
+
+ {LANG_TABS.map((tab) => ( + + ))} +
+ + set(addrFieldKey, v)} + placeholder="Salgy" + error={errors[addrErrorKey]} + /> + +
+ set('phone', v)} + placeholder="12 45-67-89" + error={errors.phone} + /> + set('email', v)} + placeholder="email@tbbank.gov.tm" + error={errors.email} + /> +
+
+ ) +} + +function StepHours({ form, errors, set }: StepContentProps) { + return ( +
+
+ set('workingHours', v)} + placeholder="09:00 - 18:00" + error={errors.workingHours} + /> +
+ set('description', v)} + placeholder="Goşmaça maglumatlar..." + rows={3} + /> +
+ ) +} + +export interface BranchFormProps { + mode: 'create' | 'edit' + initialData?: Branch + branchId?: number +} + +export function BranchForm({ mode, initialData, branchId }: BranchFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createMutation = useCreateBranch() + const updateMutation = useUpdateBranch() + 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 [currentStep, setCurrentStep] = useState(0) + const [visited, setVisited] = useState>( + () => 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) + }) + return out + }, [form, visited]) + + const set = useCallback((key: K, value: FormState[K]) => { + setForm((prev) => ({ ...prev, [key]: value })) + setErrors((prev) => ({ ...prev, [key]: undefined })) + }, []) + + const stepProps = useMemo(() => ({ form, errors, set, activeLang, setActiveLang }), [form, errors, set, activeLang]) + + const markVisited = (i: number) => + setVisited((prev) => new Set([...prev, i])) + + const handleNext = () => { + markVisited(currentStep) + const errs = STEPS[currentStep].validate(form) + 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' }) + } + } + + const handleBack = () => { + if (currentStep > 0) { + markVisited(currentStep) + setErrors({}) + setCurrentStep(currentStep - 1) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + } + + const handleGoTo = (i: number) => { + markVisited(currentStep) + setErrors({}) + setCurrentStep(i) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + const handleSubmit = () => { + setVisited(new Set(STEPS.map((_, i) => i))) + + const allErrors: FormErrors = {} + for (const step of STEPS) Object.assign(allErrors, step.validate(form)) + + 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 + } + } + 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, + } + + if (mode === 'create') { + createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') }) + } else if (branchId !== undefined) { + updateMutation.mutate( + { id: branchId, ...payload }, + { onSuccess: () => navigate('/settings/location/branches') }, + ) + } + } + + const stepBarItems: StepCardItem[] = STEPS.map((s, i) => { + const isActive = i === currentStep + const hasErrors = stepsWithErrors.has(i) + const isDone = visited.has(i) && !hasErrors + + return { + id: s.id, + title: t(s.titleKey) || s.titleFallback, + subtitle: s.subtitle, + icon: s.icon, + status: isActive ? 'active' + : hasErrors ? 'error' + : isDone ? 'done' + : 'idle', + } + }) + + const isLastStep = currentStep === STEPS.length - 1 + + return ( +
+
+

+ {mode === 'create' ? t('branches.create.title', 'Şahamça döretmek') : t('branches.edit.title', 'Şahamçany üýtgetmek')} +

+

+ {t('branches.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')} +

+
+ + + +
+
+ + {currentStep + 1} / {STEPS.length} + +

+ {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback} +

+
+ +
+ {currentStep === 0 && } + {currentStep === 1 && } + {currentStep === 2 && } +
+ +
+ + + {isLastStep ? ( + + ) : ( + + )} +
+
+
+ ) +} diff --git a/src/features/branches/hooks/useBranches.ts b/src/features/branches/hooks/useBranches.ts new file mode 100644 index 0000000..7ec474c --- /dev/null +++ b/src/features/branches/hooks/useBranches.ts @@ -0,0 +1,90 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchBranches, + fetchBranchById, + createBranch, + updateBranch, + deleteBranch, + type CreateBranchPayload, + type UpdateBranchPayload, +} from '../api/branchesApi' + +export const branchKeys = { + all: ['branches'] as const, + lists: () => [...branchKeys.all, 'list'] as const, + list: (params: Record) => + [...branchKeys.lists(), params] as const, + detail: (id: number) => [...branchKeys.all, 'detail', id] as const, +} + +export function useBranches(params: { + page?: number + perPage?: number + search?: string + isActive?: string + districtId?: string +}) { + return useQuery({ + queryKey: branchKeys.list(params), + queryFn: () => fetchBranches(params), + }) +} + +export function useBranchById(id: number) { + return useQuery({ + queryKey: branchKeys.detail(id), + queryFn: () => fetchBranchById(id), + enabled: !!id, + }) +} + +export function useCreateBranch() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: CreateBranchPayload) => createBranch(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: branchKeys.lists() }) + toast.success(t('branches.toast.createSuccess', 'Şahamça döredildi')) + }, + onError: () => { + toast.error(t('branches.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +export function useUpdateBranch() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: UpdateBranchPayload) => updateBranch(payload), + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: branchKeys.lists() }) + queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) }) + toast.success(t('branches.toast.updateSuccess', 'Şahamça täzelendi')) + }, + onError: () => { + toast.error(t('branches.toast.updateError', 'Täzelemek başartmady')) + }, + }) +} + +export function useDeleteBranch() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteBranch(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: branchKeys.lists() }) + toast.success(t('branches.toast.deleteSuccess', 'Şahamça öçürildi')) + }, + onError: () => { + toast.error(t('branches.toast.deleteError', 'Öçürmek başartmady')) + }, + }) +} diff --git a/src/features/districts/api/districtsApi.ts b/src/features/districts/api/districtsApi.ts new file mode 100644 index 0000000..106eefe --- /dev/null +++ b/src/features/districts/api/districtsApi.ts @@ -0,0 +1,99 @@ +export interface District { + id: number + name: Record<'tk' | 'ru' | 'en', string> + description: string | null + isActive: boolean +} + +export interface DistrictListResponse { + data: District[] + total: number + page: number + perPage: number +} + +export interface CreateDistrictPayload { + name: Record<'tk' | 'ru' | 'en', string> + description: string | null + isActive: boolean +} + +export interface UpdateDistrictPayload extends CreateDistrictPayload { + id: number +} + +const MOCK_DISTRICTS: District[] = [ + { id: 1, name: { tk: 'Aşgabat', ru: 'Ашхабад', en: 'Ashgabat' }, description: null, isActive: true }, + { id: 2, name: { tk: 'Änew', ru: 'Анев', en: 'Anew' }, description: null, isActive: true }, + { id: 3, name: { tk: 'Baýramaly', ru: 'Байрамалы', en: 'Bayramaly' }, description: null, isActive: true }, + { id: 4, name: { tk: 'Daşoguz', ru: 'Дашогуз', en: 'Dashoguz' }, description: null, isActive: true }, + { id: 5, name: { tk: 'Mary', ru: 'Мары', en: 'Mary' }, description: null, isActive: true }, + { id: 6, name: { tk: 'Türkmenabat', ru: 'Туркменабат', en: 'Turkmenabat' }, description: null, isActive: false }, + { id: 7, name: { tk: 'Balkanabat', ru: 'Балканабат', en: 'Balkanabat' }, description: null, isActive: true }, +] + +let mockStore = [...MOCK_DISTRICTS] +let nextId = 8 + +const delay = (ms = 300) => new Promise((r) => setTimeout(r, ms)) + +export async function fetchDistricts(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}): Promise { + await delay() + const { page = 1, perPage = 25, search = '', isActive } = params + + let filtered = mockStore.filter((item) => { + const matchSearch = + !search || + Object.values(item.name).some((n) => + n.toLowerCase().includes(search.toLowerCase()) + ) + const matchActive = + isActive === '' || isActive === undefined + ? true + : isActive === 'true' + ? item.isActive + : !item.isActive + return matchSearch && matchActive + }) + + filtered = [...filtered].sort((a, b) => b.id - a.id) + + const total = filtered.length + const start = (page - 1) * perPage + const data = filtered.slice(start, start + perPage) + + return { data, total, page, perPage } +} + +export async function fetchDistrictById(id: number): Promise { + await delay() + const item = mockStore.find((c) => c.id === id) + if (!item) throw new Error('Not found') + return { ...item } +} + +export async function createDistrict(payload: CreateDistrictPayload): Promise { + await delay(400) + const newItem: District = { id: nextId++, ...payload } + mockStore = [newItem, ...mockStore] + return newItem +} + +export async function updateDistrict(payload: UpdateDistrictPayload): Promise { + await delay(400) + const idx = mockStore.findIndex((c) => c.id === payload.id) + if (idx === -1) throw new Error('Not found') + const updated = { ...mockStore[idx], ...payload } + mockStore = mockStore.map((c) => (c.id === payload.id ? updated : c)) + return updated +} + +export async function deleteDistrict(id: number): Promise { + await delay(300) + mockStore = mockStore.filter((c) => c.id !== id) +} diff --git a/src/features/districts/components/districtsForm.tsx b/src/features/districts/components/districtsForm.tsx new file mode 100644 index 0000000..30f38f0 --- /dev/null +++ b/src/features/districts/components/districtsForm.tsx @@ -0,0 +1,192 @@ +import { useState, useEffect } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Button } from '@/components/ui/button' +import { Checkbox } from '@/components/ui/checkbox' +import { FormInput } from '@/components/formInput' +import type { District, CreateDistrictPayload } from '../api/districtsApi' +import { useCreateDistrict, useUpdateDistrict } from '../hooks/useDistricts' + +interface FormErrors { + nameTk?: string + nameRu?: string + nameEn?: string +} + +interface FormState { + nameTk: string + nameRu: string + nameEn: string + description: string + isActive: boolean +} + +export interface DistrictFormProps { + mode: 'create' | 'edit' + initialData?: District + districtId?: number +} + +type LangKey = 'tk' | 'ru' | 'en' + +const LANG_TABS: { key: LangKey; label: string }[] = [ + { key: 'tk', label: 'Türkmen' }, + { key: 'ru', label: 'Русский' }, + { key: 'en', label: 'English' }, +] + +function buildInitialState(data?: District): FormState { + if (!data) { + return { nameTk: '', nameRu: '', nameEn: '', description: '', isActive: true } + } + return { + nameTk: data.name.tk, + nameRu: data.name.ru, + nameEn: data.name.en, + description: data.description ?? '', + isActive: data.isActive, + } +} + +function validate(form: FormState, t: (k: string, fb: string) => string): FormErrors { + const errors: FormErrors = {} + if (!form.nameTk.trim()) errors.nameTk = t('validation.required', 'Hökmany meýdan') + if (!form.nameRu.trim()) errors.nameRu = t('validation.required', 'Hökmany meýdan') + if (!form.nameEn.trim()) errors.nameEn = t('validation.required', 'Hökmany meýdan') + return errors +} + +export function DistrictForm({ mode, initialData, districtId }: DistrictFormProps) { + const { t } = useTranslation() + const navigate = useNavigate() + + const createMutation = useCreateDistrict() + const updateMutation = useUpdateDistrict() + + const isPending = createMutation.isPending || updateMutation.isPending + + const [activeLang, setActiveLang] = useState('tk') + const [form, setForm] = useState(() => buildInitialState(initialData)) + const [errors, setErrors] = useState({}) + + useEffect(() => { + if (initialData) setForm(buildInitialState(initialData)) + }, [initialData]) + + const set = (key: keyof FormState) => (value: string | boolean) => + setForm((prev) => ({ ...prev, [key]: value })) + + const handleSubmit = () => { + const errs = validate(form, t) + if (Object.keys(errs).length > 0) { + setErrors(errs) + return + } + setErrors({}) + + const payload: CreateDistrictPayload = { + name: { tk: form.nameTk, ru: form.nameRu, en: form.nameEn }, + description: form.description.trim() || null, + isActive: form.isActive, + } + + if (mode === 'create') { + createMutation.mutate(payload, { + onSuccess: () => navigate('/settings/location/districts'), + }) + } else if (districtId !== undefined) { + updateMutation.mutate( + { id: districtId, ...payload }, + { onSuccess: () => navigate('/settings/location/districts') }, + ) + } + } + + const nameFieldKey = `name${activeLang.charAt(0).toUpperCase() + activeLang.slice(1)}` as + | 'nameTk' + | 'nameRu' + | 'nameEn' + const nameErrorKey = nameFieldKey as keyof FormErrors + + return ( +
+
+ {LANG_TABS.map((tab) => ( + + ))} +
+ +
+
+ + {t('districts.fields.name', 'Ady')} + * + + +
+ +
+ + {t('districts.fields.description', 'Bellikler')} + + +
+ +
+ + {t('districts.fields.isActive', 'Işjeň')} + + set('isActive')(!!checked)} + /> +
+
+ +
+ + +
+
+ ) +} diff --git a/src/features/districts/hooks/useDistricts.ts b/src/features/districts/hooks/useDistricts.ts new file mode 100644 index 0000000..571c167 --- /dev/null +++ b/src/features/districts/hooks/useDistricts.ts @@ -0,0 +1,89 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useTranslation } from 'react-i18next' +import { + fetchDistricts, + fetchDistrictById, + createDistrict, + updateDistrict, + deleteDistrict, + type CreateDistrictPayload, + type UpdateDistrictPayload, +} from '../api/districtsApi' + +export const districtKeys = { + all: ['districts'] as const, + lists: () => [...districtKeys.all, 'list'] as const, + list: (params: Record) => + [...districtKeys.lists(), params] as const, + detail: (id: number) => [...districtKeys.all, 'detail', id] as const, +} + +export function useDistricts(params: { + page?: number + perPage?: number + search?: string + isActive?: string +}) { + return useQuery({ + queryKey: districtKeys.list(params), + queryFn: () => fetchDistricts(params), + }) +} + +export function useDistrictById(id: number) { + return useQuery({ + queryKey: districtKeys.detail(id), + queryFn: () => fetchDistrictById(id), + enabled: !!id, + }) +} + +export function useCreateDistrict() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: CreateDistrictPayload) => createDistrict(payload), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: districtKeys.lists() }) + toast.success(t('districts.toast.createSuccess', 'Etrap döredildi')) + }, + onError: () => { + toast.error(t('districts.toast.createError', 'Döretmek başartmady')) + }, + }) +} + +export function useUpdateDistrict() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (payload: UpdateDistrictPayload) => updateDistrict(payload), + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: districtKeys.lists() }) + queryClient.invalidateQueries({ queryKey: districtKeys.detail(data.id) }) + toast.success(t('districts.toast.updateSuccess', 'Etrap täzelendi')) + }, + onError: () => { + toast.error(t('districts.toast.updateError', 'Täzelemek başartmady')) + }, + }) +} + +export function useDeleteDistrict() { + const queryClient = useQueryClient() + const { t } = useTranslation() + + return useMutation({ + mutationFn: (id: number) => deleteDistrict(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: districtKeys.lists() }) + toast.success(t('districts.toast.deleteSuccess', 'Etrap öçürildi')) + }, + onError: () => { + toast.error(t('districts.toast.deleteError', 'Öçürmek başartmady')) + }, + }) +} diff --git a/src/pages/settings/location/branches/index.tsx b/src/pages/settings/location/branches/index.tsx new file mode 100644 index 0000000..b540e1f --- /dev/null +++ b/src/pages/settings/location/branches/index.tsx @@ -0,0 +1,269 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { Eye, Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import type { FilterField, ActiveFilter } from '@/components/dataTableToolbar' +import { useBranches, useDeleteBranch } from '@/features/branches/hooks/useBranches' +import type { Branch } from '@/features/branches/api/branchesApi' +import { getDistrictOptions } from '@/features/branches/api/branchesApi' + +export function BranchesListPage() { + const { t, i18n } = useTranslation() + const navigate = useNavigate() + + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [search, setSearch] = useState('') + const [activeFilters, setActiveFilters] = useState([ + { fieldId: 'isActive', value: '' }, + { fieldId: 'districtId', value: '' }, + ]) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([ + 'id', 'code', 'name', 'districtName', 'phone', 'isActive', 'actions', + ]) + const [deleteId, setDeleteId] = useState(null) + + const deleteMutation = useDeleteBranch() + const isActiveFilter = activeFilters.find((f) => f.fieldId === 'isActive')?.value ?? '' + const districtIdFilter = activeFilters.find((f) => f.fieldId === 'districtId')?.value ?? '' + + const { data, isLoading } = useBranches({ page, perPage, search, isActive: isActiveFilter, districtId: districtIdFilter }) + + const districtOptions = getDistrictOptions().map((d) => ({ + value: String(d.id), + label: d.name.tk, + })) + + const filterFields: FilterField[] = [ + { + id: 'isActive', + label: t('branches.fields.isActive', 'Işjeň'), + options: [ + { value: 'true', label: t('common.active', 'Işjeň') }, + { value: 'false', label: t('common.inactive', 'Işjeň däl') }, + ], + }, + { + id: 'districtId', + label: t('branches.fields.district', 'Etrap'), + options: districtOptions, + }, + ] + + const handleFilterChange = (fieldId: string, value: string) => { + setActiveFilters((prev) => + prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)) + ) + setPage(1) + } + + const handleFilterReset = () => { + setActiveFilters([ + { fieldId: 'isActive', value: '' }, + { fieldId: 'districtId', value: '' }, + ]) + setPage(1) + } + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 70, + }, + { + accessorKey: 'code', + id: 'code', + header: t('branches.fields.code', 'KOD').toUpperCase(), + cell: ({ row }) => ( + {row.original.code} + ), + size: 100, + }, + { + accessorKey: 'name', + id: 'name', + header: t('branches.fields.name', 'ADY').toUpperCase(), + cell: ({ row }) => ( + {row.original.name[lang]} + ), + }, + { + accessorKey: 'districtName', + id: 'districtName', + header: t('branches.fields.district', 'ETRAP').toUpperCase(), + cell: ({ row }) => ( + {row.original.districtName[lang]} + ), + }, + { + accessorKey: 'phone', + header: t('branches.fields.phone', 'TELEFON').toUpperCase(), + cell: ({ row }) => ( + {row.original.phone} + ), + size: 150, + }, + { + accessorKey: 'isActive', + id: 'isActive', + header: t('branches.fields.isActive', 'IŞJEŇ').toUpperCase(), + cell: ({ row }) => + row.original.isActive ? ( + + ) : ( + + ), + size: 100, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + enableSorting: false, + enableHiding: false, + size: 120, + }, + ] + + const columnMeta = columns + .filter( + (c) => + c.id !== 'actions' && + (c as { accessorKey?: string }).accessorKey !== undefined + ) + .map((c) => ({ + id: (c.id ?? (c as { accessorKey?: string }).accessorKey) as string, + label: + typeof c.header === 'string' + ? c.header + : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ''), + })) + + const totalPages = data ? Math.ceil(data.total / perPage) : 1 + + return ( +
+
+
+ +

+ {t('branches.title', 'Şahamçalar')} +

+
+
+ + { setSearch(v); setPage(1) }} + searchPlaceholder={t('common.search', 'Gözlemek')} + columns={columnMeta} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + actionLabel={t('branches.actions.create', 'Şahamça döret')} + onAction={() => navigate('/settings/location/branches/create')} + /> + + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={data?.total} + onPageChange={setPage} + /> + + setDeleteId(null)}> + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('branches.deleteConfirm', 'Bu şahamçany öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteId !== null) { + deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) }) + } + }} + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default BranchesListPage diff --git a/src/pages/settings/location/branchesCreate/index.tsx b/src/pages/settings/location/branchesCreate/index.tsx new file mode 100644 index 0000000..e96ff16 --- /dev/null +++ b/src/pages/settings/location/branchesCreate/index.tsx @@ -0,0 +1,40 @@ +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { BranchForm } from '@/features/branches/components/branchesForm' + +export default function BranchCreatePage() { + const navigate = useNavigate() + const { t } = useTranslation() + + return ( +
+
+ + +

+ {t('branches.create.title', 'Şahamça döretmek')} +

+
+ + +
+ ) +} diff --git a/src/pages/settings/location/branchesEdit/index.tsx b/src/pages/settings/location/branchesEdit/index.tsx new file mode 100644 index 0000000..de3e9f3 --- /dev/null +++ b/src/pages/settings/location/branchesEdit/index.tsx @@ -0,0 +1,60 @@ +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { BranchForm } from '@/features/branches/components/branchesForm' +import { useBranchById } from '@/features/branches/hooks/useBranches' +import { Loader2 } from 'lucide-react' + +export default function BranchEditPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t } = useTranslation() + + const numericId = Number(id) + const { data, isLoading, isError } = useBranchById(numericId) + + return ( +
+
+ + +

+ {isLoading + ? '...' + : `${t('branches.edit.title', 'Şahamçany üýtgetmek')}: ${data?.name.tk ?? ''}`} +

+
+ + {isLoading ? ( +
+ +
+ ) : isError || !data ? ( +
+

+ {t('common.error', 'Maglumat ýüklenilmedi. Sahypany täzeleläň.')} +

+
+ ) : ( + + )} +
+ ) +} diff --git a/src/pages/settings/location/branchesView/index.tsx b/src/pages/settings/location/branchesView/index.tsx new file mode 100644 index 0000000..db3a0c3 --- /dev/null +++ b/src/pages/settings/location/branchesView/index.tsx @@ -0,0 +1,205 @@ +import { useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useBranchById, useDeleteBranch } from '@/features/branches/hooks/useBranches' + +export function BranchViewPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t, i18n } = useTranslation() + + const numericId = Number(id) + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const { data, isLoading } = useBranchById(numericId) + const deleteMutation = useDeleteBranch() + const [deleteOpen, setDeleteOpen] = useState(false) + + return ( +
+
+
+ +

+ {isLoading + ? '...' + : `${t('branches.view.title', 'Şahamça giňişleýin')}: ${data?.name[lang] ?? ''}`} +

+
+ +
+ + +
+
+ + {isLoading ? ( +
+ {Array.from({ length: 6 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : data ? ( + <> +
+ + + +
+ + {t('branches.fields.name', 'Ady')} + +
+
+ {(['tk', 'ru', 'en'] as const).map((l) => ( + + {l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'} + + ))} +
+ {data.name[lang]} +
+
+ + + +
+ + {t('branches.fields.isActive', 'Işjeň')} + + {data.isActive ? ( + + ) : ( + + )} +
+
+ +
+
+ + {t('branches.fields.address', 'Salgy')} + +
+
+ {(['tk', 'ru', 'en'] as const).map((l) => ( + + {l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'} + + ))} +
+ {data.address[lang]} +
+
+ + +
+ +
+ + +
+ + ) : ( +

{t('common.noData', 'Maglumat ýok')}

+ )} + + + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('branches.deleteConfirm', 'Bu şahamçany öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + + deleteMutation.mutate(numericId, { + onSuccess: () => navigate('/settings/location/branches'), + }) + } + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default BranchViewPage diff --git a/src/pages/settings/location/districts/index.tsx b/src/pages/settings/location/districts/index.tsx new file mode 100644 index 0000000..5299480 --- /dev/null +++ b/src/pages/settings/location/districts/index.tsx @@ -0,0 +1,237 @@ +import { useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import type { ColumnDef, VisibilityState } from '@tanstack/react-table' +import { Eye, Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { DataTable } from '@/components/dataTable' +import { DataTableToolbar } from '@/components/dataTableToolbar' +import type { FilterField, ActiveFilter } from '@/components/dataTableToolbar' +import { useDistricts, useDeleteDistrict } from '@/features/districts/hooks/useDistricts' +import type { District } from '@/features/districts/api/districtsApi' + +export function DistrictsListPage() { + const { t, i18n } = useTranslation() + const navigate = useNavigate() + + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const [page, setPage] = useState(1) + const [perPage, setPerPage] = useState(25) + const [search, setSearch] = useState('') + const [activeFilters, setActiveFilters] = useState([ + { fieldId: 'isActive', value: '' }, + ]) + const [columnVisibility, setColumnVisibility] = useState({}) + const [columnOrder, setColumnOrder] = useState([ + 'id', 'name', 'description', 'isActive', 'actions', + ]) + const [deleteId, setDeleteId] = useState(null) + + const deleteMutation = useDeleteDistrict() + const isActiveFilter = activeFilters.find((f) => f.fieldId === 'isActive')?.value ?? '' + + const { data, isLoading } = useDistricts({ page, perPage, search, isActive: isActiveFilter }) + + const filterFields: FilterField[] = [ + { + id: 'isActive', + label: t('districts.fields.isActive', 'Işjeň'), + options: [ + { value: 'true', label: t('common.active', 'Işjeň') }, + { value: 'false', label: t('common.inactive', 'Işjeň däl') }, + ], + }, + ] + + const handleFilterChange = (fieldId: string, value: string) => { + setActiveFilters((prev) => + prev.map((f) => (f.fieldId === fieldId ? { ...f, value } : f)) + ) + setPage(1) + } + + const handleFilterReset = () => { + setActiveFilters([{ fieldId: 'isActive', value: '' }]) + setPage(1) + } + + const columns: ColumnDef[] = [ + { + accessorKey: 'id', + header: 'ID', + cell: ({ row }) => ( + {row.original.id} + ), + size: 70, + }, + { + accessorKey: 'name', + id: 'name', + header: t('districts.fields.name', 'ADY').toUpperCase(), + cell: ({ row }) => ( + {row.original.name[lang]} + ), + }, + { + accessorKey: 'description', + header: t('districts.fields.description', 'BELLIKLER').toUpperCase(), + cell: ({ row }) => ( + + {row.original.description ?? '—'} + + ), + }, + { + accessorKey: 'isActive', + id: 'isActive', + header: t('districts.fields.isActive', 'IŞJEŇ').toUpperCase(), + cell: ({ row }) => + row.original.isActive ? ( + + ) : ( + + ), + size: 100, + }, + { + id: 'actions', + header: '', + cell: ({ row }) => ( +
+ + + +
+ ), + enableSorting: false, + enableHiding: false, + size: 120, + }, + ] + + const columnMeta = columns + .filter( + (c) => + c.id !== 'actions' && + (c as { accessorKey?: string }).accessorKey !== undefined + ) + .map((c) => ({ + id: (c.id ?? (c as { accessorKey?: string }).accessorKey) as string, + label: + typeof c.header === 'string' + ? c.header + : (c.id ?? (c as { accessorKey?: string }).accessorKey ?? ''), + })) + + const totalPages = data ? Math.ceil(data.total / perPage) : 1 + + return ( +
+
+
+ +

+ {t('districts.title', 'Etraplar')} +

+
+
+ + { setSearch(v); setPage(1) }} + searchPlaceholder={t('common.search', 'Gözlemek')} + columns={columnMeta} + columnVisibility={columnVisibility} + onColumnVisibilityChange={setColumnVisibility} + columnOrder={columnOrder} + onColumnOrderChange={setColumnOrder} + filterFields={filterFields} + activeFilters={activeFilters} + onFilterChange={handleFilterChange} + onFilterReset={handleFilterReset} + perPage={perPage} + onPerPageChange={(v) => { setPerPage(v); setPage(1) }} + actionLabel={t('districts.actions.create', 'Etrap döret')} + onAction={() => navigate('/settings/location/districts/create')} + /> + + String(row.id)} + currentPage={page} + totalPages={totalPages} + totalCount={data?.total} + onPageChange={setPage} + /> + + setDeleteId(null)}> + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('districts.deleteConfirm', 'Bu etrapy öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + { + if (deleteId !== null) { + deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) }) + } + }} + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default DistrictsListPage diff --git a/src/pages/settings/location/districtsCreate/index.tsx b/src/pages/settings/location/districtsCreate/index.tsx new file mode 100644 index 0000000..6c839f9 --- /dev/null +++ b/src/pages/settings/location/districtsCreate/index.tsx @@ -0,0 +1,40 @@ +import { useNavigate } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { DistrictForm } from '@/features/districts/components/districtsForm' + +export default function DistrictCreatePage() { + const navigate = useNavigate() + const { t } = useTranslation() + + return ( +
+
+ + +

+ {t('districts.create.title', 'Etrap döretmek')} +

+
+ + +
+ ) +} diff --git a/src/pages/settings/location/districtsEdit/index.tsx b/src/pages/settings/location/districtsEdit/index.tsx new file mode 100644 index 0000000..9aa6132 --- /dev/null +++ b/src/pages/settings/location/districtsEdit/index.tsx @@ -0,0 +1,65 @@ +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { DistrictForm } from '@/features/districts/components/districtsForm' +import { useDistrictById } from '@/features/districts/hooks/useDistricts' + +export default function DistrictEditPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t } = useTranslation() + + const numericId = Number(id) + const { data, isLoading, isError } = useDistrictById(numericId) + + return ( +
+
+ + +

+ {isLoading + ? '...' + : `${t('districts.edit.title', 'Etrapy üýtgetmek')}: ${data?.name.tk ?? ''}`} +

+
+ + {isLoading ? ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : isError || !data ? ( +
+ {t('common.error', 'Ýalňyşlyk ýüze çykdy')} +
+ ) : ( + + )} +
+ ) +} diff --git a/src/pages/settings/location/districtsView/index.tsx b/src/pages/settings/location/districtsView/index.tsx new file mode 100644 index 0000000..172463e --- /dev/null +++ b/src/pages/settings/location/districtsView/index.tsx @@ -0,0 +1,170 @@ +import { useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' +import { useTranslation } from 'react-i18next' +import { Pencil, Trash2, CheckCircle2, XCircle } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { Section, InfoRow } from '@/components/viewPageComponents' +import { useDistrictById, useDeleteDistrict } from '@/features/districts/hooks/useDistricts' + +export function DistrictViewPage() { + const { id } = useParams<{ id: string }>() + const navigate = useNavigate() + const { t, i18n } = useTranslation() + + const numericId = Number(id) + const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en' + + const { data, isLoading } = useDistrictById(numericId) + const deleteMutation = useDeleteDistrict() + const [deleteOpen, setDeleteOpen] = useState(false) + + return ( +
+
+
+ +

+ {isLoading + ? '...' + : `${t('districts.view.title', 'Etrap giňişleýin')}: ${data?.name[lang] ?? ''}`} +

+
+ +
+ + +
+
+ + {isLoading ? ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+
+
+
+ ))} +
+ ) : data ? ( +
+ + +
+ + {t('districts.fields.name', 'Ady')} + +
+
+ {(['tk', 'ru', 'en'] as const).map((l) => ( + + {l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'} + + ))} +
+ {data.name[lang]} +
+
+ + + +
+ + {t('districts.fields.isActive', 'Işjeň')} + + {data.isActive ? ( + + ) : ( + + )} +
+
+ ) : ( +

{t('common.noData', 'Maglumat ýok')}

+ )} + + + + + {t('common.confirmDelete', 'Öçürmegi tassyklaň')} + + {t('districts.deleteConfirm', 'Bu etrapy öçürmek isleýärsiňizmi?')} + + + + {t('common.cancel', 'Ýatyr')} + + deleteMutation.mutate(numericId, { + onSuccess: () => navigate('/settings/location/districts'), + }) + } + > + {deleteMutation.isPending + ? t('common.deleting', 'Öçürilýär...') + : t('common.delete', 'Öçürmek')} + + + + +
+ ) +} + +export default DistrictViewPage