added locations page

This commit is contained in:
@jcarymuhammedow
2026-05-13 19:10:07 +05:00
parent d8821a0199
commit 6a85c42fde
17 changed files with 2294 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -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 <Navigate to="/login" replace />;
@@ -901,6 +911,70 @@ export const router = createBrowserRouter([
</Suspense>
),
},
{ // Sidebar: /settings/location/districts
path: "/settings/location/districts",
element: (
<Suspense fallback={<PageLoader />}>
<DistrictsPage />
</Suspense>
),
},
{
path: "/settings/location/districts/create",
element: (
<Suspense fallback={<PageLoader />}>
<DistrictCreatePage />
</Suspense>
),
},
{
path: "/settings/location/districts/:id",
element: (
<Suspense fallback={<PageLoader />}>
<DistrictsViewPage />
</Suspense>
),
},
{
path: "/settings/location/districts/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<DistrictEditPage />
</Suspense>
),
},
{ // Sidebar: /settings/location/branches
path: "/settings/location/branches",
element: (
<Suspense fallback={<PageLoader />}>
<BranchesPage />
</Suspense>
),
},
{
path: "/settings/location/branches/create",
element: (
<Suspense fallback={<PageLoader />}>
<BranchCreatePage />
</Suspense>
),
},
{
path: "/settings/location/branches/:id",
element: (
<Suspense fallback={<PageLoader />}>
<BranchesViewPage />
</Suspense>
),
},
{
path: "/settings/location/branches/:id/edit",
element: (
<Suspense fallback={<PageLoader />}>
<BranchEditPage />
</Suspense>
),
},
],
},
],

View File

@@ -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<BranchListResponse> {
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<Branch> {
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<Branch> {
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<Branch> {
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<void> {
await delay(300)
mockStore = mockStore.filter((c) => c.id !== id)
}

View File

@@ -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<Record<keyof FormState, string>>
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 extends keyof FormState>(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 (
<div className="flex flex-col gap-6">
<div className="flex gap-3 justify-end mb-2">
{LANG_TABS.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveLang(tab.key)}
className={`text-sm transition-colors ${
activeLang === tab.key
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{tab.label}
</button>
))}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label="Şahamçanyň ady"
required
value={form[nameFieldKey]}
onChange={(v) => set(nameFieldKey, v)}
placeholder="Şahamçanyň ady"
error={errors[nameErrorKey]}
/>
<FormInput
type="text"
label="Kod"
required
value={form.code}
onChange={(v) => set('code', v)}
placeholder="BR-XXX"
error={errors.code}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="searchable-select"
label="Etrap"
required
value={form.districtId}
onChange={(v) => set('districtId', v)}
options={getDistrictOptions().map((d) => ({ value: String(d.id), label: d.name.tk }))}
placeholder="Etrap saýlaň"
error={errors.districtId}
/>
<div className="flex items-end pb-2">
<div className="flex items-center gap-2">
<Checkbox
id="isActive"
checked={form.isActive}
onCheckedChange={(checked) => set('isActive', !!checked)}
/>
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
Işjeň
</label>
</div>
</div>
</div>
</div>
)
}
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 (
<div className="flex flex-col gap-6">
<div className="flex gap-3 justify-end mb-2">
{LANG_TABS.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveLang(tab.key)}
className={`text-sm transition-colors ${
activeLang === tab.key
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{tab.label}
</button>
))}
</div>
<FormInput
type="text"
label="Salgy"
required
value={form[addrFieldKey]}
onChange={(v) => set(addrFieldKey, v)}
placeholder="Salgy"
error={errors[addrErrorKey]}
/>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="phone"
label="Telefon"
required
value={form.phone}
onChange={(v) => set('phone', v)}
placeholder="12 45-67-89"
error={errors.phone}
/>
<FormInput
type="email"
label="E-poçta"
required
value={form.email}
onChange={(v) => set('email', v)}
placeholder="email@tbbank.gov.tm"
error={errors.email}
/>
</div>
</div>
)
}
function StepHours({ form, errors, set }: StepContentProps) {
return (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<FormInput
type="text"
label="Iş wagty"
required
value={form.workingHours}
onChange={(v) => set('workingHours', v)}
placeholder="09:00 - 18:00"
error={errors.workingHours}
/>
</div>
<FormInput
type="textarea"
label="Bellikler"
value={form.description}
onChange={(v) => set('description', v)}
placeholder="Goşmaça maglumatlar..."
rows={3}
/>
</div>
)
}
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<LangKey>('tk')
const [form, setForm] = useState<FormState>(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
const [errors, setErrors] = useState<FormErrors>({})
const [currentStep, setCurrentStep] = useState(0)
const [visited, setVisited] = useState<Set<number>>(
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>()
)
const stepsWithErrors = useMemo(() => {
const out = new Set<number>()
visited.forEach((i) => {
if (Object.keys(STEPS[i].validate(form)).length > 0) out.add(i)
})
return out
}, [form, visited])
const set = useCallback(<K extends keyof FormState>(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 (
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold text-foreground">
{mode === 'create' ? t('branches.create.title', 'Şahamça döretmek') : t('branches.edit.title', 'Şahamçany üýtgetmek')}
</h1>
<p className="text-sm text-muted-foreground">
{t('branches.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
</p>
</div>
<StepBarCards steps={stepBarItems} onGoTo={handleGoTo} />
<div className="flex flex-col bg-card border border-border rounded-xl overflow-hidden">
<div className="flex items-center gap-2.5 px-5 py-3.5 border-b border-border">
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-primary/10 text-primary text-[11px] font-semibold tabular-nums">
{currentStep + 1} / {STEPS.length}
</span>
<h2 className="text-sm font-semibold text-foreground">
{t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
</h2>
</div>
<div className="p-5">
{currentStep === 0 && <StepBasic {...stepProps} />}
{currentStep === 1 && <StepAddress {...stepProps} />}
{currentStep === 2 && <StepHours {...stepProps} />}
</div>
<div className="flex items-center justify-between px-5 py-3.5 border-t border-border bg-muted/30">
<Button
type="button"
variant="outline"
size="sm"
onClick={currentStep === 0 ? () => navigate(-1) : handleBack}
disabled={isPending}
>
{currentStep === 0 ? (t('Cancel') || 'Ýatyr') : (
<span className="flex items-center gap-1.5">
<ChevronLeft className="w-3.5 h-3.5" />
{t('Back') || 'Yza'}
</span>
)}
</Button>
{isLastStep ? (
<Button type="button" size="sm" onClick={handleSubmit} disabled={isPending} className="min-w-[150px]">
{isPending ? (
<span className="flex items-center gap-2">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
{t('common.saving', 'Saklanýar...')}
</span>
) : mode === 'create'
? (t('branches.actions.create', 'Şahamça döret'))
: (t('branches.actions.update', 'Täzelemek'))
}
</Button>
) : (
<Button type="button" size="sm" onClick={handleNext} disabled={isPending} className="min-w-[120px]">
<span className="flex items-center gap-1.5">
{t('Next') || 'Indiki'}
<ChevronRight className="w-3.5 h-3.5" />
</span>
</Button>
)}
</div>
</div>
</div>
)
}

View File

@@ -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<string, unknown>) =>
[...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'))
},
})
}

View File

@@ -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<DistrictListResponse> {
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<District> {
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<District> {
await delay(400)
const newItem: District = { id: nextId++, ...payload }
mockStore = [newItem, ...mockStore]
return newItem
}
export async function updateDistrict(payload: UpdateDistrictPayload): Promise<District> {
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<void> {
await delay(300)
mockStore = mockStore.filter((c) => c.id !== id)
}

View File

@@ -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<LangKey>('tk')
const [form, setForm] = useState<FormState>(() => buildInitialState(initialData))
const [errors, setErrors] = useState<FormErrors>({})
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 (
<div>
<div className="flex gap-3 justify-end mb-4">
{LANG_TABS.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveLang(tab.key)}
className={`text-sm transition-colors ${
activeLang === tab.key
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{tab.label}
</button>
))}
</div>
<div className="bg-card border border-border rounded-xl overflow-hidden">
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
<span className="text-sm text-muted-foreground">
{t('districts.fields.name', 'Ady')}
<span className="text-destructive ml-0.5">*</span>
</span>
<FormInput
type="text"
value={form[nameFieldKey]}
onChange={set(nameFieldKey)}
placeholder={t('districts.fields.name', 'Ady')}
error={errors[nameErrorKey]}
/>
</div>
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border">
<span className="text-sm text-muted-foreground">
{t('districts.fields.description', 'Bellikler')}
</span>
<FormInput
type="text"
value={form.description}
onChange={set('description')}
placeholder={t('districts.fields.description', 'Bellikler')}
/>
</div>
<div className="grid grid-cols-[220px_1fr] items-center py-3 px-4">
<span className="text-sm text-muted-foreground">
{t('districts.fields.isActive', 'Işjeň')}
</span>
<Checkbox
checked={form.isActive}
onCheckedChange={(checked) => set('isActive')(!!checked)}
/>
</div>
</div>
<div className="flex items-center justify-end gap-3 mt-6">
<Button
type="button"
variant="ghost"
onClick={() => navigate('/settings/location/districts')}
disabled={isPending}
>
{t('common.cancel', 'Ýatyr')}
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isPending}
className="bg-primary text-primary-foreground hover:bg-primary/90"
>
{isPending
? t('common.saving', 'Saklanýar...')
: mode === 'create'
? t('districts.actions.create', 'Etrap döret')
: t('districts.actions.update', 'Täzelemek')}
</Button>
</div>
</div>
)
}

View File

@@ -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<string, unknown>) =>
[...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'))
},
})
}

View File

@@ -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<ActiveFilter[]>([
{ fieldId: 'isActive', value: '' },
{ fieldId: 'districtId', value: '' },
])
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([
'id', 'code', 'name', 'districtName', 'phone', 'isActive', 'actions',
])
const [deleteId, setDeleteId] = useState<number | null>(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<Branch>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-mono text-sm font-medium">{row.original.id}</span>
),
size: 70,
},
{
accessorKey: 'code',
id: 'code',
header: t('branches.fields.code', 'KOD').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm font-mono text-foreground">{row.original.code}</span>
),
size: 100,
},
{
accessorKey: 'name',
id: 'name',
header: t('branches.fields.name', 'ADY').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.name[lang]}</span>
),
},
{
accessorKey: 'districtName',
id: 'districtName',
header: t('branches.fields.district', 'ETRAP').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">{row.original.districtName[lang]}</span>
),
},
{
accessorKey: 'phone',
header: t('branches.fields.phone', 'TELEFON').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.phone}</span>
),
size: 150,
},
{
accessorKey: 'isActive',
id: 'isActive',
header: t('branches.fields.isActive', 'IŞJEŇ').toUpperCase(),
cell: ({ row }) =>
row.original.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
),
size: 100,
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center gap-2 justify-end">
<button
className="p-1.5 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
onClick={() => navigate(`/settings/location/branches/${row.original.id}`)}
title={t('common.view', 'Görmek')}
>
<Eye size={14} />
</button>
<button
className="p-1.5 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
onClick={() => navigate(`/settings/location/branches/${row.original.id}/edit`)}
title={t('common.edit', 'Üýtgetmek')}
>
<Pencil size={14} />
</button>
<button
className="p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Öçürmek')}
>
<Trash2 size={14} />
</button>
</div>
),
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 (
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<div>
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span>{t('nav.settings', 'Sazlamalar')}</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('branches.title', 'Şahamçalar')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{t('branches.title', 'Şahamçalar')}
</h1>
</div>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { 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')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={totalPages}
totalCount={data?.total}
onPageChange={setPage}
/>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
<AlertDialogDescription>
{t('branches.deleteConfirm', 'Bu şahamçany öçürmek isleýärsiňizmi?')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => {
if (deleteId !== null) {
deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) })
}
}}
>
{deleteMutation.isPending
? t('common.deleting', 'Öçürilýär...')
: t('common.delete', 'Öçürmek')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export default BranchesListPage

View File

@@ -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 (
<div className="p-6">
<div className="mb-6">
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('branches.title', 'Şahamçalar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('branches.create.breadcrumb', 'Şahamça döretmek')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{t('branches.create.title', 'Şahamça döretmek')}
</h1>
</div>
<BranchForm mode="create" />
</div>
)
}

View File

@@ -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 (
<div className="p-6">
<div className="mb-6">
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('branches.title', 'Şahamçalar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('branches.edit.breadcrumb', 'Üýtgetmek')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{isLoading
? '...'
: `${t('branches.edit.title', 'Şahamçany üýtgetmek')}: ${data?.name.tk ?? ''}`}
</h1>
</div>
{isLoading ? (
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 className="animate-spin text-muted-foreground" size={32} />
</div>
) : isError || !data ? (
<div className="flex items-center justify-center min-h-[400px]">
<p className="text-sm text-destructive">
{t('common.error', 'Maglumat ýüklenilmedi. Sahypany täzeleläň.')}
</p>
</div>
) : (
<BranchForm mode="edit" initialData={data} branchId={numericId} />
)}
</div>
)
}

View File

@@ -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 (
<div className="p-6">
<div className="flex items-start justify-between mb-6">
<div>
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/branches')}
>
{t('branches.title', 'Şahamçalar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{isLoading ? '...' : data?.name[lang] ?? ''}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{isLoading
? '...'
: `${t('branches.view.title', 'Şahamça giňişleýin')}: ${data?.name[lang] ?? ''}`}
</h1>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={() => navigate(`/settings/location/branches/${numericId}/edit`)}
title={t('common.edit', 'Üýtgetmek')}
>
<Pencil size={15} />
</Button>
<Button
variant="outline"
size="icon"
className="text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setDeleteOpen(true)}
title={t('common.delete', 'Öçürmek')}
>
<Trash2 size={15} />
</Button>
</div>
</div>
{isLoading ? (
<div className="bg-card border border-border rounded-xl overflow-hidden">
{Array.from({ length: 6 }).map((_, i) => (
<div
key={i}
className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0"
>
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
<div className="h-4 w-40 bg-muted rounded animate-pulse" />
</div>
))}
</div>
) : data ? (
<>
<Section title={t('branches.sections.basic', 'Esasy maglumatlar')}>
<InfoRow label="ID" value={data.id} />
<InfoRow label={t('branches.fields.code', 'Kod')} value={data.code} />
<div className="grid grid-cols-[220px_1fr] items-start py-2.5 px-4 border-b border-border">
<span className="text-sm text-muted-foreground pt-1">
{t('branches.fields.name', 'Ady')}
</span>
<div>
<div className="flex gap-3 mb-2 justify-end">
{(['tk', 'ru', 'en'] as const).map((l) => (
<span
key={l}
className={`text-sm cursor-default ${
l === lang
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground'
}`}
>
{l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'}
</span>
))}
</div>
<span className="text-sm text-foreground">{data.name[lang]}</span>
</div>
</div>
<InfoRow label={t('branches.fields.district', 'Etrap')} value={data.districtName[lang]} />
<div className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4">
<span className="text-sm text-muted-foreground">
{t('branches.fields.isActive', 'Işjeň')}
</span>
{data.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
)}
</div>
</Section>
<Section title={t('branches.sections.address', 'Salgy we habarlaşmak')}>
<div className="grid grid-cols-[220px_1fr] items-start py-2.5 px-4 border-b border-border">
<span className="text-sm text-muted-foreground pt-1">
{t('branches.fields.address', 'Salgy')}
</span>
<div>
<div className="flex gap-3 mb-2 justify-end">
{(['tk', 'ru', 'en'] as const).map((l) => (
<span
key={l}
className={`text-sm cursor-default ${
l === lang
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground'
}`}
>
{l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'}
</span>
))}
</div>
<span className="text-sm text-foreground">{data.address[lang]}</span>
</div>
</div>
<InfoRow label={t('branches.fields.phone', 'Telefon')} value={data.phone} />
<InfoRow label={t('branches.fields.email', 'E-poçta')} value={data.email} />
</Section>
<Section title={t('branches.sections.hours', 'Iş wagty')}>
<InfoRow label={t('branches.fields.workingHours', 'Iş wagty')} value={data.workingHours} />
<InfoRow
label={t('branches.fields.description', 'Bellikler')}
value={data.description ?? undefined}
/>
</Section>
</>
) : (
<p className="text-muted-foreground text-sm">{t('common.noData', 'Maglumat ýok')}</p>
)}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
<AlertDialogDescription>
{t('branches.deleteConfirm', 'Bu şahamçany öçürmek isleýärsiňizmi?')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() =>
deleteMutation.mutate(numericId, {
onSuccess: () => navigate('/settings/location/branches'),
})
}
>
{deleteMutation.isPending
? t('common.deleting', 'Öçürilýär...')
: t('common.delete', 'Öçürmek')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export default BranchViewPage

View File

@@ -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<ActiveFilter[]>([
{ fieldId: 'isActive', value: '' },
])
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [columnOrder, setColumnOrder] = useState<string[]>([
'id', 'name', 'description', 'isActive', 'actions',
])
const [deleteId, setDeleteId] = useState<number | null>(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<District>[] = [
{
accessorKey: 'id',
header: 'ID',
cell: ({ row }) => (
<span className="text-primary font-mono text-sm font-medium">{row.original.id}</span>
),
size: 70,
},
{
accessorKey: 'name',
id: 'name',
header: t('districts.fields.name', 'ADY').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm text-foreground">{row.original.name[lang]}</span>
),
},
{
accessorKey: 'description',
header: t('districts.fields.description', 'BELLIKLER').toUpperCase(),
cell: ({ row }) => (
<span className="text-sm text-muted-foreground">
{row.original.description ?? '—'}
</span>
),
},
{
accessorKey: 'isActive',
id: 'isActive',
header: t('districts.fields.isActive', 'IŞJEŇ').toUpperCase(),
cell: ({ row }) =>
row.original.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
),
size: 100,
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center gap-2 justify-end">
<button
className="p-1.5 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
onClick={() => navigate(`/settings/location/districts/${row.original.id}`)}
title={t('common.view', 'Görmek')}
>
<Eye size={14} />
</button>
<button
className="p-1.5 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors"
onClick={() => navigate(`/settings/location/districts/${row.original.id}/edit`)}
title={t('common.edit', 'Üýtgetmek')}
>
<Pencil size={14} />
</button>
<button
className="p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
onClick={() => setDeleteId(row.original.id)}
title={t('common.delete', 'Öçürmek')}
>
<Trash2 size={14} />
</button>
</div>
),
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 (
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<div>
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span>{t('nav.settings', 'Sazlamalar')}</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('districts.title', 'Etraplar')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{t('districts.title', 'Etraplar')}
</h1>
</div>
</div>
<DataTableToolbar
searchValue={search}
onSearchChange={(v) => { 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')}
/>
<DataTable
columns={columns}
data={data?.data ?? []}
isLoading={isLoading}
columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility}
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
enableRowSelection
getRowId={(row) => String(row.id)}
currentPage={page}
totalPages={totalPages}
totalCount={data?.total}
onPageChange={setPage}
/>
<AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
<AlertDialogDescription>
{t('districts.deleteConfirm', 'Bu etrapy öçürmek isleýärsiňizmi?')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => {
if (deleteId !== null) {
deleteMutation.mutate(deleteId, { onSuccess: () => setDeleteId(null) })
}
}}
>
{deleteMutation.isPending
? t('common.deleting', 'Öçürilýär...')
: t('common.delete', 'Öçürmek')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export default DistrictsListPage

View File

@@ -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 (
<div className="p-6">
<div className="mb-6">
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('districts.title', 'Etraplar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('districts.create.breadcrumb', 'Etrap döretmek')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{t('districts.create.title', 'Etrap döretmek')}
</h1>
</div>
<DistrictForm mode="create" />
</div>
)
}

View File

@@ -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 (
<div className="p-6">
<div className="mb-6">
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('districts.title', 'Etraplar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{t('districts.edit.breadcrumb', 'Üýtgetmek')}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{isLoading
? '...'
: `${t('districts.edit.title', 'Etrapy üýtgetmek')}: ${data?.name.tk ?? ''}`}
</h1>
</div>
{isLoading ? (
<div className="bg-card border border-border rounded-xl overflow-hidden">
{Array.from({ length: 3 }).map((_, i) => (
<div
key={i}
className="grid grid-cols-[220px_1fr] items-center py-3 px-4 border-b border-border last:border-0"
>
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
<div className="h-8 w-full bg-muted rounded animate-pulse" />
</div>
))}
</div>
) : isError || !data ? (
<div className="flex items-center justify-center py-20 text-destructive text-sm">
{t('common.error', 'Ýalňyşlyk ýüze çykdy')}
</div>
) : (
<DistrictForm mode="edit" initialData={data} districtId={numericId} />
)}
</div>
)
}

View File

@@ -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 (
<div className="p-6">
<div className="flex items-start justify-between mb-6">
<div>
<nav className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('nav.settings', 'Sazlamalar')}
</span>
<span>›</span>
<span
className="cursor-pointer hover:text-foreground transition-colors"
onClick={() => navigate('/settings/location/districts')}
>
{t('districts.title', 'Etraplar')}
</span>
<span>›</span>
<span className="text-foreground font-medium">
{isLoading ? '...' : data?.name[lang] ?? ''}
</span>
</nav>
<h1 className="text-2xl font-bold text-foreground">
{isLoading
? '...'
: `${t('districts.view.title', 'Etrap giňişleýin')}: ${data?.name[lang] ?? ''}`}
</h1>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={() => navigate(`/settings/location/districts/${numericId}/edit`)}
title={t('common.edit', 'Üýtgetmek')}
>
<Pencil size={15} />
</Button>
<Button
variant="outline"
size="icon"
className="text-destructive border-destructive/30 hover:bg-destructive/10"
onClick={() => setDeleteOpen(true)}
title={t('common.delete', 'Öçürmek')}
>
<Trash2 size={15} />
</Button>
</div>
</div>
{isLoading ? (
<div className="bg-card border border-border rounded-xl overflow-hidden">
{Array.from({ length: 3 }).map((_, i) => (
<div
key={i}
className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4 border-b border-border last:border-0"
>
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
<div className="h-4 w-40 bg-muted rounded animate-pulse" />
</div>
))}
</div>
) : data ? (
<Section>
<InfoRow label="ID" value={data.id} />
<div className="grid grid-cols-[220px_1fr] items-start py-2.5 px-4 border-b border-border">
<span className="text-sm text-muted-foreground pt-1">
{t('districts.fields.name', 'Ady')}
</span>
<div>
<div className="flex gap-3 mb-2 justify-end">
{(['tk', 'ru', 'en'] as const).map((l) => (
<span
key={l}
className={`text-sm cursor-default ${
l === lang
? 'text-primary font-semibold underline underline-offset-4'
: 'text-muted-foreground'
}`}
>
{l === 'tk' ? 'Türkmen' : l === 'ru' ? 'Русский' : 'English'}
</span>
))}
</div>
<span className="text-sm text-foreground">{data.name[lang]}</span>
</div>
</div>
<InfoRow
label={t('districts.fields.description', 'Bellikler')}
value={data.description ?? undefined}
/>
<div className="grid grid-cols-[220px_1fr] items-center py-2.5 px-4">
<span className="text-sm text-muted-foreground">
{t('districts.fields.isActive', 'Işjeň')}
</span>
{data.isActive ? (
<CheckCircle2 size={18} className="text-emerald-500" />
) : (
<XCircle size={18} className="text-destructive" />
)}
</div>
</Section>
) : (
<p className="text-muted-foreground text-sm">{t('common.noData', 'Maglumat ýok')}</p>
)}
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t('common.confirmDelete', 'Öçürmegi tassyklaň')}</AlertDialogTitle>
<AlertDialogDescription>
{t('districts.deleteConfirm', 'Bu etrapy öçürmek isleýärsiňizmi?')}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel', 'Ýatyr')}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() =>
deleteMutation.mutate(numericId, {
onSuccess: () => navigate('/settings/location/districts'),
})
}
>
{deleteMutation.isPending
? t('common.deleting', 'Öçürilýär...')
: t('common.delete', 'Öçürmek')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export default DistrictViewPage