added locations page
This commit is contained in:
172
src/features/branches/api/branchesApi.ts
Normal file
172
src/features/branches/api/branchesApi.ts
Normal 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)
|
||||
}
|
||||
492
src/features/branches/components/branchesForm.tsx
Normal file
492
src/features/branches/components/branchesForm.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
90
src/features/branches/hooks/useBranches.ts
Normal file
90
src/features/branches/hooks/useBranches.ts
Normal 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'))
|
||||
},
|
||||
})
|
||||
}
|
||||
99
src/features/districts/api/districtsApi.ts
Normal file
99
src/features/districts/api/districtsApi.ts
Normal 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)
|
||||
}
|
||||
192
src/features/districts/components/districtsForm.tsx
Normal file
192
src/features/districts/components/districtsForm.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
89
src/features/districts/hooks/useDistricts.ts
Normal file
89
src/features/districts/hooks/useDistricts.ts
Normal 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'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user