started connect with api
This commit is contained in:
1 parent
0ca218505d
commit
6da59f42d9
112 files changed
+7091
-6989
No files matched your search
@@ -1,172 +1,135 @@
|
||||
import apiClient from "@/lib/api/client";
|
||||
|
||||
// ─── Localized text (backend keys: tm | ru | en) ──────────────────────────────
|
||||
|
||||
export interface LocalizedText {
|
||||
tm: string;
|
||||
ru: string;
|
||||
en: string;
|
||||
}
|
||||
|
||||
// ─── Province (for the provinceId select) ─────────────────────────────────────
|
||||
|
||||
export interface Province {
|
||||
id: number;
|
||||
name: LocalizedText;
|
||||
region: LocalizedText;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
// ─── Branch ───────────────────────────────────────────────────────────────────
|
||||
|
||||
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
|
||||
id: number;
|
||||
uniqueCode: string;
|
||||
name: LocalizedText;
|
||||
address: LocalizedText;
|
||||
region: string;
|
||||
provinceId: number;
|
||||
provinceName: LocalizedText;
|
||||
phoneNumbers: string;
|
||||
billingUsername: string;
|
||||
billingPassword: string;
|
||||
billingSberUsername: string;
|
||||
billingSberPassword: string;
|
||||
billingVisaMasterUsername: string;
|
||||
billingVisaMasterPassword: string;
|
||||
billingSwiftUsername: string;
|
||||
billingSwiftPassword: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface BranchListParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
provinceId?: string;
|
||||
provinceName?: string;
|
||||
uniqueCode?: string;
|
||||
}
|
||||
|
||||
export interface BranchListResponse {
|
||||
data: Branch[]
|
||||
total: number
|
||||
page: number
|
||||
perPage: number
|
||||
count: number;
|
||||
branches: Branch[];
|
||||
}
|
||||
|
||||
// ─── API Payloads ─────────────────────────────────────────────────────────────
|
||||
|
||||
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
|
||||
active: boolean;
|
||||
address: LocalizedText;
|
||||
billingPassword: string;
|
||||
billingSberPassword: string;
|
||||
billingSberUsername: string;
|
||||
billingSwiftPassword: string;
|
||||
billingSwiftUsername: string;
|
||||
billingUsername: string;
|
||||
billingVisaMasterPassword: string;
|
||||
billingVisaMasterUsername: string;
|
||||
name: LocalizedText;
|
||||
phoneNumbers: string;
|
||||
provinceId: number;
|
||||
region: string;
|
||||
uniqueCode: string;
|
||||
}
|
||||
|
||||
export interface UpdateBranchPayload extends CreateBranchPayload {
|
||||
id: number
|
||||
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' } },
|
||||
]
|
||||
// ─── Branch CRUD ──────────────────────────────────────────────────────────────
|
||||
|
||||
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 fetchBranches(params: BranchListParams = {}, signal?: AbortSignal): Promise<BranchListResponse> {
|
||||
const { page, limit, search, provinceId, provinceName, uniqueCode } = params;
|
||||
const { data } = await apiClient.get<BranchListResponse>("/branches", {
|
||||
params: {
|
||||
page,
|
||||
limit,
|
||||
branch_name: search || undefined,
|
||||
province_id: provinceId || undefined,
|
||||
province_name: provinceName || undefined,
|
||||
unique_code: uniqueCode || undefined,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
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 }
|
||||
const { data } = await apiClient.get<Branch>(`/branches/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
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
|
||||
const { data } = await apiClient.post<Branch>("/branches", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
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
|
||||
const { id, ...rest } = payload;
|
||||
const { data } = await apiClient.put<Branch>(`/branches/${id}`, rest);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function deleteBranch(id: number): Promise<void> {
|
||||
await delay(300)
|
||||
mockStore = mockStore.filter((c) => c.id !== id)
|
||||
await apiClient.delete(`/branches/${id}`);
|
||||
}
|
||||
|
||||
// ─── Province options (for the provinceId select) ─────────────────────────────
|
||||
|
||||
export interface ProvinceListResponse {
|
||||
count: number;
|
||||
provinces: Province[];
|
||||
}
|
||||
|
||||
export async function fetchProvinces(
|
||||
params: { page?: number; limit?: number; search?: string } = {},
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProvinceListResponse> {
|
||||
const { page, limit, search } = params;
|
||||
const { data } = await apiClient.get<ProvinceListResponse>("/provinces", {
|
||||
params: { page, limit, name: search || undefined },
|
||||
signal,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
@@ -1,368 +1,466 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { toast } from 'sonner'
|
||||
import { Building2, MapPin, Clock } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { FormInput } from '@/components/formInput'
|
||||
import { FormActions } from '@/components/formActions'
|
||||
import { MultiLangInput } from '@/components/multiLangInput'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
|
||||
import { useCreateBranch, useUpdateBranch } from '@/features/branches/hooks/useBranches'
|
||||
import type { Branch } from '@/features/branches/api/branchesApi'
|
||||
import { getDistrictOptions } from '@/features/branches/api/branchesApi'
|
||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from '@/features/branches/schemas/branch.schema'
|
||||
import type { BranchFormData } from '@/features/branches/schemas/branch.schema'
|
||||
import { useState, useCallback, useMemo, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { toast } from "sonner";
|
||||
import { Building2, MapPin, CreditCard } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { FormInput } from "@/components/formInput";
|
||||
import { FormActions } from "@/components/formActions";
|
||||
import { MultiLangInput } from "@/components/multiLangInput";
|
||||
import { InfiniteSelect, type InfiniteSelectOption, type InfiniteSelectProps } from "@/components/infiniteSelect";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { StepBarCards, type StepCardItem } from "@/components/stepBarV2";
|
||||
import { useCreateBranch, useUpdateBranch, useInfiniteProvinces } from "@/features/branches/hooks/useBranches";
|
||||
import type { Branch } from "@/features/branches/api/branchesApi";
|
||||
import { createBranchFormSchema, validateStep, DEFAULT_FORM_VALUES, buildPayload } from "@/features/branches/schemas/branch.schema";
|
||||
import type { BranchFormData } from "@/features/branches/schemas/branch.schema";
|
||||
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>
|
||||
type FlatErrors = Partial<Record<keyof BranchFormData, string>>;
|
||||
|
||||
function flattenErrors(errors: Record<string, { message?: string } | undefined>): FlatErrors {
|
||||
const result: FlatErrors = {}
|
||||
const result: FlatErrors = {};
|
||||
for (const key of Object.keys(errors)) {
|
||||
const msg = errors[key]?.message
|
||||
if (msg) result[key as keyof BranchFormData] = msg
|
||||
const msg = errors[key]?.message;
|
||||
if (msg) result[key as keyof BranchFormData] = msg;
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
interface StepDef {
|
||||
id: string
|
||||
titleKey: string
|
||||
titleFallback: string
|
||||
shortLabel: string
|
||||
icon: LucideIcon
|
||||
subtitle: string
|
||||
validate: (form: BranchFormData, mode: 'create' | 'edit', t: (key: string, fallback?: string) => string) => FlatErrors
|
||||
id: string;
|
||||
titleKey: string;
|
||||
titleFallback: string;
|
||||
shortLabel: string;
|
||||
icon: LucideIcon;
|
||||
subtitle: string;
|
||||
validate: (form: BranchFormData, mode: "create" | "edit", t: (key: string, fallback?: string) => string) => FlatErrors;
|
||||
}
|
||||
|
||||
const STEPS: StepDef[] = [
|
||||
{
|
||||
id: 'basic',
|
||||
titleKey: 'branches.steps.basic',
|
||||
titleFallback: 'Esasy maglumatlar',
|
||||
shortLabel: 'Esasy',
|
||||
id: "basic",
|
||||
titleKey: "branches.steps.basic",
|
||||
titleFallback: "Esasy maglumatlar",
|
||||
shortLabel: "Esasy",
|
||||
icon: Building2,
|
||||
subtitle: 'Ady, kody, etrapy',
|
||||
subtitle: "Ady, unikal belgisi, welayaty",
|
||||
validate: (form, mode, t) => validateStep(0, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'address',
|
||||
titleKey: 'branches.steps.address',
|
||||
titleFallback: 'Salgy we habarlaşmak',
|
||||
shortLabel: 'Salgy',
|
||||
id: "address",
|
||||
titleKey: "branches.steps.address",
|
||||
titleFallback: "Salgy we habarlaşmak",
|
||||
shortLabel: "Salgy",
|
||||
icon: MapPin,
|
||||
subtitle: 'Salgy, telefon, e-poçta',
|
||||
subtitle: "Salgy, telefonlar",
|
||||
validate: (form, mode, t) => validateStep(1, form, mode, t),
|
||||
},
|
||||
{
|
||||
id: 'hours',
|
||||
titleKey: 'branches.steps.hours',
|
||||
titleFallback: 'Iş wagty',
|
||||
shortLabel: 'Wagt',
|
||||
icon: Clock,
|
||||
subtitle: 'Iş wagty we bellikler',
|
||||
id: "billing",
|
||||
titleKey: "branches.steps.billing",
|
||||
titleFallback: "Billing maglumatlary",
|
||||
shortLabel: "Billing",
|
||||
icon: CreditCard,
|
||||
subtitle: "Ulanyjy ady we parollar",
|
||||
validate: (form, mode, t) => validateStep(2, form, mode, t),
|
||||
},
|
||||
]
|
||||
];
|
||||
|
||||
const STEP_FIELDS: Record<number, (keyof BranchFormData)[]> = {
|
||||
0: ['nameTk', 'nameRu', 'nameEn', 'code', 'districtId', 'isActive'],
|
||||
1: ['addressTk', 'addressRu', 'addressEn', 'phone', 'email'],
|
||||
2: ['workingHours', 'description'],
|
||||
}
|
||||
0: ["nameTk", "nameRu", "nameEn", "uniqueCode", "provinceId", "region", "isActive"],
|
||||
1: ["addressTk", "addressRu", "addressEn", "phoneNumbers"],
|
||||
2: [
|
||||
"billingUsername",
|
||||
"billingPassword",
|
||||
"billingSberUsername",
|
||||
"billingSberPassword",
|
||||
"billingVisaMasterUsername",
|
||||
"billingVisaMasterPassword",
|
||||
"billingSwiftUsername",
|
||||
"billingSwiftPassword",
|
||||
],
|
||||
};
|
||||
|
||||
interface StepContentProps {
|
||||
form: BranchFormData
|
||||
errors: FlatErrors
|
||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void
|
||||
t: (key: string, fallback?: string) => string
|
||||
lang: 'tk' | 'ru' | 'en'
|
||||
form: BranchFormData;
|
||||
errors: FlatErrors;
|
||||
set: <K extends keyof BranchFormData>(k: K, v: BranchFormData[K]) => void;
|
||||
t: (key: string, fallback?: string) => string;
|
||||
lang: "tm" | "ru" | "en";
|
||||
provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder">;
|
||||
}
|
||||
|
||||
function StepBasic({ form, errors, set, t, lang }: StepContentProps) {
|
||||
function StepBasic({ form, errors, set, t, provinceSelect }: StepContentProps) {
|
||||
const nameFields = {
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set('nameTk', v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set('nameRu', v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set('nameEn', v), error: errors.nameEn },
|
||||
}
|
||||
tk: { value: form.nameTk, onChange: (v: string) => set("nameTk", v), error: errors.nameTk },
|
||||
ru: { value: form.nameRu, onChange: (v: string) => set("nameRu", v), error: errors.nameRu },
|
||||
en: { value: form.nameEn, onChange: (v: string) => set("nameEn", v), error: errors.nameEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<MultiLangInput fields={nameFields} placeholder={t('branches.fields.name', 'Şahamçanyň ady')} />
|
||||
<MultiLangInput fields={nameFields} placeholder={t("branches.fields.name", "Şahamçanyň ady")} />
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t('branches.fields.code', 'Kod')}
|
||||
label={t("branches.fields.uniqueCode", "Unikal belgisi")}
|
||||
required
|
||||
value={form.code}
|
||||
onChange={(v) => set('code', v)}
|
||||
placeholder="BR-XXX"
|
||||
error={errors.code}
|
||||
value={form.uniqueCode}
|
||||
onChange={(v) => set("uniqueCode", v)}
|
||||
placeholder="ORG-XXX-XXXX"
|
||||
error={errors.uniqueCode}
|
||||
/>
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.region", "Welaýat")}
|
||||
required
|
||||
value={form.region}
|
||||
onChange={(v) => set("region", v)}
|
||||
placeholder="Aşgabat şäheri"
|
||||
error={errors.region}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="searchable-select"
|
||||
label={t('branches.fields.district', 'Etrap')}
|
||||
<InfiniteSelect
|
||||
label={t("branches.fields.district", "Etrap")}
|
||||
required
|
||||
value={form.districtId}
|
||||
onChange={(v) => set('districtId', v)}
|
||||
options={getDistrictOptions().map((d) => ({ value: String(d.id), label: d.name[lang] }))}
|
||||
placeholder={t('branches.fields.district', 'Etrap saýlaň')}
|
||||
error={errors.districtId}
|
||||
placeholder={t("branches.fields.district", "Etrap saýlaň")}
|
||||
{...provinceSelect}
|
||||
error={provinceSelect.error ?? errors.provinceId}
|
||||
value={form.provinceId}
|
||||
onChange={(v) => set("provinceId", v)}
|
||||
/>
|
||||
<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)}
|
||||
/>
|
||||
<Checkbox id="isActive" checked={form.isActive} onCheckedChange={(checked) => set("isActive", !!checked)} />
|
||||
<label htmlFor="isActive" className="text-sm text-muted-foreground cursor-pointer select-none">
|
||||
{t('branches.fields.isActive', 'Işjeň')}
|
||||
{t("branches.fields.isActive", "Işjeň")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepAddress({ form, errors, set, t }: StepContentProps) {
|
||||
const addressFields = {
|
||||
tk: { value: form.addressTk, onChange: (v: string) => set('addressTk', v), error: errors.addressTk },
|
||||
ru: { value: form.addressRu, onChange: (v: string) => set('addressRu', v), error: errors.addressRu },
|
||||
en: { value: form.addressEn, onChange: (v: string) => set('addressEn', v), error: errors.addressEn },
|
||||
}
|
||||
tk: { value: form.addressTk, onChange: (v: string) => set("addressTk", v), error: errors.addressTk },
|
||||
ru: { value: form.addressRu, onChange: (v: string) => set("addressRu", v), error: errors.addressRu },
|
||||
en: { value: form.addressEn, onChange: (v: string) => set("addressEn", v), error: errors.addressEn },
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<MultiLangInput fields={addressFields} placeholder={t('branches.fields.address', 'Salgy')} />
|
||||
<MultiLangInput fields={addressFields} placeholder={t("branches.fields.address", "Salgy")} />
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="phone"
|
||||
label={t('branches.fields.phone', 'Telefon')}
|
||||
type="text"
|
||||
label={t("branches.fields.phoneNumbers", "Telefonlar")}
|
||||
required
|
||||
value={form.phone}
|
||||
onChange={(v) => set('phone', v)}
|
||||
placeholder="12 45-67-89"
|
||||
error={errors.phone}
|
||||
/>
|
||||
<FormInput
|
||||
type="email"
|
||||
label={t('branches.fields.email', 'E-poçta')}
|
||||
required
|
||||
value={form.email}
|
||||
onChange={(v) => set('email', v)}
|
||||
placeholder="email@tbbank.gov.tm"
|
||||
error={errors.email}
|
||||
value={form.phoneNumbers}
|
||||
onChange={(v) => set("phoneNumbers", v)}
|
||||
placeholder="+99312998877, +99365123456"
|
||||
error={errors.phoneNumbers}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function StepHours({ form, errors, set, t }: StepContentProps) {
|
||||
function StepBilling({ form, errors, set, t }: 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={t('branches.fields.workingHours', 'Iş wagty')}
|
||||
label={t("branches.fields.billingIbr", "Billing ulanyjy ady")}
|
||||
required
|
||||
value={form.workingHours}
|
||||
onChange={(v) => set('workingHours', v)}
|
||||
placeholder="09:00 - 18:00"
|
||||
error={errors.workingHours}
|
||||
value={form.billingUsername}
|
||||
onChange={(v) => set("billingUsername", v)}
|
||||
placeholder="billing_user"
|
||||
error={errors.billingUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingPassword", "Billing paroly")}
|
||||
required
|
||||
value={form.billingPassword}
|
||||
onChange={(v) => set("billingPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingSber", "Billing ulanyjy ady (SBER)")}
|
||||
required
|
||||
value={form.billingSberUsername}
|
||||
onChange={(v) => set("billingSberUsername", v)}
|
||||
placeholder="sber_merchant"
|
||||
error={errors.billingSberUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingSberPassword", "Parol (SBER)")}
|
||||
required
|
||||
value={form.billingSberPassword}
|
||||
onChange={(v) => set("billingSberPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingSberPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingVisa", "Billing ulanyjy ady (VISA)")}
|
||||
required
|
||||
value={form.billingVisaMasterUsername}
|
||||
onChange={(v) => set("billingVisaMasterUsername", v)}
|
||||
placeholder="visamaster_merchant"
|
||||
error={errors.billingVisaMasterUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingVisaPassword", "Parol (VISA)")}
|
||||
required
|
||||
value={form.billingVisaMasterPassword}
|
||||
onChange={(v) => set("billingVisaMasterPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingVisaMasterPassword}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormInput
|
||||
type="text"
|
||||
label={t("branches.fields.billingSwift", "Billing ulanyjy ady (SWIFT)")}
|
||||
required
|
||||
value={form.billingSwiftUsername}
|
||||
onChange={(v) => set("billingSwiftUsername", v)}
|
||||
placeholder="SWIFT_TM_BANK"
|
||||
error={errors.billingSwiftUsername}
|
||||
/>
|
||||
<FormInput
|
||||
type="password"
|
||||
label={t("branches.fields.billingSwiftPassword", "Parol (SWIFT)")}
|
||||
required
|
||||
value={form.billingSwiftPassword}
|
||||
onChange={(v) => set("billingSwiftPassword", v)}
|
||||
placeholder="••••••••"
|
||||
error={errors.billingSwiftPassword}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
type="textarea"
|
||||
label={t('branches.fields.description', '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
|
||||
mode: "create" | "edit";
|
||||
initialData?: Branch;
|
||||
}
|
||||
|
||||
function mapInitial(data: Branch): Partial<BranchFormData> {
|
||||
return {
|
||||
nameTk: data.name.tk,
|
||||
nameTk: data.name.tm,
|
||||
nameRu: data.name.ru,
|
||||
nameEn: data.name.en,
|
||||
code: data.code,
|
||||
districtId: String(data.districtId),
|
||||
addressTk: data.address.tk,
|
||||
uniqueCode: data.uniqueCode,
|
||||
provinceId: String(data.provinceId),
|
||||
region: data.region,
|
||||
addressTk: data.address.tm,
|
||||
addressRu: data.address.ru,
|
||||
addressEn: data.address.en,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: data.description ?? '',
|
||||
isActive: data.isActive,
|
||||
}
|
||||
phoneNumbers: data.phoneNumbers,
|
||||
billingUsername: data.billingUsername,
|
||||
billingPassword: data.billingPassword,
|
||||
billingSberUsername: data.billingSberUsername,
|
||||
billingSberPassword: data.billingSberPassword,
|
||||
billingVisaMasterUsername: data.billingVisaMasterUsername,
|
||||
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||
billingSwiftUsername: data.billingSwiftUsername,
|
||||
billingSwiftPassword: data.billingSwiftPassword,
|
||||
isActive: data.active,
|
||||
};
|
||||
}
|
||||
|
||||
export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
const { t: _t, i18n } = useTranslation()
|
||||
const t: (key: string, fallback?: string) => string = useCallback(
|
||||
(key, fallback) => _t(key, fallback ?? key) as string,
|
||||
[_t],
|
||||
)
|
||||
const lang = (i18n.language?.slice(0, 2) ?? 'tk') as 'tk' | 'ru' | 'en'
|
||||
const navigate = useNavigate()
|
||||
const { t: _t, i18n } = useTranslation();
|
||||
const t: (key: string, fallback?: string) => string = useCallback((key, fallback) => _t(key, fallback ?? key) as string, [_t]);
|
||||
const lang = ((i18n.language?.slice(0, 2) === "tk" ? "tm" : i18n.language?.slice(0, 2)) ?? "tm") as "tm" | "ru" | "en";
|
||||
const navigate = useNavigate();
|
||||
|
||||
const createMutation = useCreateBranch()
|
||||
const updateMutation = useUpdateBranch()
|
||||
const isPending = createMutation.isPending || updateMutation.isPending
|
||||
const createMutation = useCreateBranch();
|
||||
const updateMutation = useUpdateBranch();
|
||||
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language])
|
||||
const [provinceSearch, setProvinceSearch] = useState("");
|
||||
const provinceQuery = useInfiniteProvinces(provinceSearch);
|
||||
|
||||
const provinceSelect: Omit<InfiniteSelectProps, "label" | "required" | "placeholder"> = useMemo(() => {
|
||||
const opts: InfiniteSelectOption[] = (provinceQuery.data?.pages ?? [])
|
||||
.flatMap((p) => p.provinces)
|
||||
.map((p) => ({ value: String(p.id), label: p.name[lang] }));
|
||||
|
||||
// Ensure the currently-selected province is present (edit mode), even if it
|
||||
// lives beyond the pages loaded so far.
|
||||
if (initialData) {
|
||||
const current = String(initialData.provinceId);
|
||||
if (!opts.some((o) => o.value === current)) {
|
||||
opts.unshift({ value: current, label: initialData.provinceName?.[lang] ?? current });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
options: opts,
|
||||
loading: provinceQuery.isLoading,
|
||||
isLoadingMore: provinceQuery.isFetchingNextPage,
|
||||
hasNextPage: !!provinceQuery.hasNextPage,
|
||||
onLoadMore: () => provinceQuery.fetchNextPage(),
|
||||
searchValue: provinceSearch,
|
||||
onSearchChange: setProvinceSearch,
|
||||
};
|
||||
}, [provinceQuery, provinceSearch, lang, initialData]);
|
||||
|
||||
const schema = useMemo(() => createBranchFormSchema(t), [t, i18n.language]);
|
||||
|
||||
const {
|
||||
watch, setValue, getValues, formState: { errors: rhfErrors }, clearErrors, trigger,
|
||||
watch,
|
||||
setValue,
|
||||
getValues,
|
||||
formState: { errors: rhfErrors },
|
||||
clearErrors,
|
||||
trigger,
|
||||
} = useForm<BranchFormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: initialData ? { ...DEFAULT_FORM_VALUES, ...mapInitial(initialData) } : DEFAULT_FORM_VALUES,
|
||||
})
|
||||
});
|
||||
|
||||
const form = watch()
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors])
|
||||
const form = watch();
|
||||
const errors = useMemo(() => flattenErrors(rhfErrors as Record<string, { message?: string } | undefined>), [rhfErrors]);
|
||||
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [visited, setVisited] = useState<Set<number>>(
|
||||
() => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set<number>(),
|
||||
)
|
||||
const [isValidated, setIsValidated] = useState(false)
|
||||
const [currentStep, setCurrentStep] = useState(0);
|
||||
const [visited, setVisited] = useState<Set<number>>(() => (mode === "edit" ? new Set(STEPS.map((_, i) => i)) : new Set<number>()));
|
||||
const [isValidated, setIsValidated] = useState(false);
|
||||
|
||||
const stepsWithErrors = useMemo(() => {
|
||||
const out = new Set<number>()
|
||||
const out = new Set<number>();
|
||||
visited.forEach((i) => {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i)
|
||||
})
|
||||
return out
|
||||
}, [form, mode, visited, t])
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) out.add(i);
|
||||
});
|
||||
return out;
|
||||
}, [form, mode, visited, t]);
|
||||
|
||||
const set = useCallback(<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value)
|
||||
clearErrors(key)
|
||||
}, [setValue, clearErrors])
|
||||
const set = useCallback(
|
||||
<K extends keyof BranchFormData>(key: K, value: BranchFormData[K]) => {
|
||||
(setValue as (name: K, val: BranchFormData[K]) => void)(key, value);
|
||||
clearErrors(key);
|
||||
},
|
||||
[setValue, clearErrors],
|
||||
);
|
||||
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, lang }), [form, errors, set, t, lang])
|
||||
const stepProps = useMemo(() => ({ form, errors, set, t, lang, provinceSelect }), [form, errors, set, t, lang, provinceSelect]);
|
||||
|
||||
const markVisited = (i: number) =>
|
||||
setVisited((prev) => new Set([...prev, i]))
|
||||
const markVisited = (i: number) => setVisited((prev) => new Set([...prev, i]));
|
||||
|
||||
// ── Re-validate on language change ──
|
||||
useEffect(() => {
|
||||
if (!isValidated) return
|
||||
if (!isValidated) return;
|
||||
|
||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || [])
|
||||
const visitedFields = Array.from(visited).flatMap((stepIdx) => STEP_FIELDS[stepIdx] || []);
|
||||
if (visitedFields.length > 0) {
|
||||
trigger(visitedFields)
|
||||
trigger(visitedFields);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [i18n.language, isValidated])
|
||||
}, [i18n.language, isValidated]);
|
||||
|
||||
const handleNext = async () => {
|
||||
setIsValidated(true)
|
||||
markVisited(currentStep)
|
||||
setIsValidated(true);
|
||||
markVisited(currentStep);
|
||||
|
||||
const fields = STEP_FIELDS[currentStep] || []
|
||||
const isValid = await trigger(fields)
|
||||
const fields = STEP_FIELDS[currentStep] || [];
|
||||
const isValid = await trigger(fields);
|
||||
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.fillRequiredCorrectly', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
|
||||
return
|
||||
toast.error(t("common.errors.fillRequiredCorrectly", "Dogry maglumat girizmegiňizi haýyş edýäris."));
|
||||
return;
|
||||
}
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setCurrentStep(currentStep + 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
setCurrentStep(currentStep + 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (currentStep > 0) {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(currentStep - 1)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(currentStep - 1);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleGoTo = (i: number) => {
|
||||
markVisited(currentStep)
|
||||
setCurrentStep(i)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
markVisited(currentStep);
|
||||
setCurrentStep(i);
|
||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const doSubmit = async () => {
|
||||
setIsValidated(true)
|
||||
setVisited(new Set(STEPS.map((_, i) => i)))
|
||||
setIsValidated(true);
|
||||
setVisited(new Set(STEPS.map((_, i) => i)));
|
||||
|
||||
const isValid = await trigger()
|
||||
const isValid = await trigger();
|
||||
if (!isValid) {
|
||||
toast.error(t('common.errors.requiredFieldsMissing', 'Käbir hökmany meýdanlar doldurylan däldir.'))
|
||||
toast.error(t("common.errors.requiredFieldsMissing", "Käbir hökmany meýdanlar doldurylan däldir."));
|
||||
for (let i = 0; i < STEPS.length; i++) {
|
||||
if (Object.keys(STEPS[i].validate(form, mode, t)).length > 0) {
|
||||
setCurrentStep(i); break
|
||||
setCurrentStep(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayload(getValues())
|
||||
const payload = buildPayload(getValues());
|
||||
|
||||
if (mode === 'create') {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate('/settings/location/branches') })
|
||||
if (mode === "create") {
|
||||
createMutation.mutate(payload, { onSuccess: () => navigate("/settings/location/branches") });
|
||||
} else if (initialData) {
|
||||
updateMutation.mutate(
|
||||
{ id: initialData.id, ...payload },
|
||||
{ onSuccess: () => navigate('/settings/location/branches') },
|
||||
)
|
||||
updateMutation.mutate({ id: initialData.id, ...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
|
||||
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',
|
||||
}
|
||||
})
|
||||
status: isActive ? "active" : hasErrors ? "error" : isDone ? "done" : "idle",
|
||||
};
|
||||
});
|
||||
|
||||
const isLastStep = currentStep === STEPS.length - 1
|
||||
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.createTitle', 'Şahamça döretmek') : t('branches.editTitle', 'Şahamçany üýtgetmek')}
|
||||
{mode === "create" ? t("branches.createTitle", "Şahamça döretmek") : t("branches.editTitle", "Şahamçany üýtgetmek")}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('branches.form.subtitle', 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.')}
|
||||
</p>
|
||||
<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} />
|
||||
@@ -372,15 +470,13 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
<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>
|
||||
<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} />}
|
||||
{currentStep === 2 && <StepBilling {...stepProps} />}
|
||||
</div>
|
||||
|
||||
<FormActions
|
||||
@@ -390,12 +486,10 @@ export function BranchForm({ mode, initialData }: BranchFormProps) {
|
||||
onNext={!isLastStep ? handleNext : undefined}
|
||||
showSubmit={isLastStep}
|
||||
onSubmit={isLastStep ? doSubmit : undefined}
|
||||
submitLabel={mode === 'create'
|
||||
? t('branches.actions.create', 'Şahamça döret')
|
||||
: t('branches.actions.update', 'Täzelemek')}
|
||||
submitLabel={mode === "create" ? t("branches.actions.create", "Şahamça döret") : t("branches.actions.update", "Täzelemek")}
|
||||
className="px-5 py-3.5 border-t border-border bg-muted/30"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1,35 +1,79 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useMutation, useQuery, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDebouncedValue, normalizeSearch } from "@/hooks/useDebouncedSearch";
|
||||
import {
|
||||
fetchBranches,
|
||||
fetchBranchById,
|
||||
fetchProvinces,
|
||||
createBranch,
|
||||
updateBranch,
|
||||
deleteBranch,
|
||||
type BranchListParams,
|
||||
type CreateBranchPayload,
|
||||
type UpdateBranchPayload,
|
||||
} from '../api/branchesApi'
|
||||
type Province,
|
||||
} 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,
|
||||
all: ["branches"] as const,
|
||||
lists: () => [...branchKeys.all, "list"] as const,
|
||||
list: (params: BranchListParams) => [...branchKeys.lists(), params] as const,
|
||||
detail: (id: number) => [...branchKeys.all, "detail", id] as const,
|
||||
provinces: ["provinces"] as const,
|
||||
};
|
||||
|
||||
export function useBranches(params: BranchListParams) {
|
||||
const debouncedSearch = useDebouncedValue(params.search ?? "");
|
||||
const queryParams: BranchListParams = { ...params, search: normalizeSearch(debouncedSearch) };
|
||||
|
||||
return useQuery({
|
||||
queryKey: branchKeys.list(queryParams),
|
||||
queryFn: ({ signal }) => fetchBranches(queryParams, signal),
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranches(params: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
search?: string
|
||||
isActive?: string
|
||||
districtId?: string
|
||||
}) {
|
||||
const PROVINCE_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Paginated provinces for infinite-scroll selects.
|
||||
* `search` is debounced server-side search; each keystroke resets to page 1.
|
||||
*/
|
||||
export function useInfiniteProvinces(search = "") {
|
||||
const debouncedSearch = useDebouncedValue(search);
|
||||
const effectiveSearch = normalizeSearch(debouncedSearch);
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: [...branchKeys.provinces, "infinite", effectiveSearch],
|
||||
initialPageParam: 1,
|
||||
queryFn: ({ pageParam, signal }) => fetchProvinces({ page: pageParam, limit: PROVINCE_PAGE_SIZE, search: effectiveSearch }, signal),
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, p) => sum + p.provinces.length, 0);
|
||||
return loaded < lastPage.count ? allPages.length + 1 : undefined;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads every province page and flattens them.
|
||||
* Intended for static option lists (e.g. table filter dropdowns) where the
|
||||
* dataset is small and an infinite-scroll select is overkill.
|
||||
*/
|
||||
export function useProvinceOptions() {
|
||||
return useQuery({
|
||||
queryKey: branchKeys.list(params),
|
||||
queryFn: () => fetchBranches(params),
|
||||
})
|
||||
queryKey: [...branchKeys.provinces, "all"] as const,
|
||||
queryFn: async (): Promise<Province[]> => {
|
||||
const all: Province[] = [];
|
||||
let page = 1;
|
||||
for (;;) {
|
||||
const res = await fetchProvinces({ page, limit: PROVINCE_PAGE_SIZE });
|
||||
all.push(...res.provinces);
|
||||
if (all.length >= res.count || res.provinces.length === 0) break;
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBranchById(id: number) {
|
||||
@@ -37,45 +81,45 @@ export function useBranchById(id: number) {
|
||||
queryKey: branchKeys.detail(id),
|
||||
queryFn: () => fetchBranchById(id),
|
||||
enabled: !!id,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
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'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
toast.success(t("branches.toast.createSuccess", "Şahamça döredildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
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'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.detail(data.id) });
|
||||
toast.success(t("branches.toast.updateSuccess", "Şahamça täzelendi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteBranch() {
|
||||
const queryClient = useQueryClient()
|
||||
const { t } = useTranslation()
|
||||
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'))
|
||||
queryClient.invalidateQueries({ queryKey: branchKeys.lists() });
|
||||
toast.success(t("branches.toast.deleteSuccess", "Şahamça öçürildi"));
|
||||
},
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -1,39 +1,26 @@
|
||||
import { z } from "zod";
|
||||
import type { CreateBranchPayload } from "@/features/branches/api/branchesApi";
|
||||
|
||||
const VALID_PHONE_PREFIXES = ["61", "62", "63", "64", "65", "71"];
|
||||
|
||||
export function createBranchFormSchema(t: (key: string, fallback?: string) => string) {
|
||||
return z.object({
|
||||
nameTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
nameEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
code: z.string().min(1, t("validation.required", "validation.required")),
|
||||
districtId: z.string().min(1, t("validation.required", "validation.required")),
|
||||
uniqueCode: z.string().min(1, t("validation.required", "validation.required")),
|
||||
provinceId: z.string().min(1, t("validation.required", "validation.required")),
|
||||
region: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressTk: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressRu: z.string().min(1, t("validation.required", "validation.required")),
|
||||
addressEn: z.string().min(1, t("validation.required", "validation.required")),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, t("validation.required", "validation.required"))
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
return digits.length === 8;
|
||||
},
|
||||
{ message: t("validation.invalidPhone", "validation.invalidPhone") },
|
||||
)
|
||||
.refine(
|
||||
(val) => {
|
||||
const digits = val.replace(/\D/g, "");
|
||||
const prefix = digits.slice(0, 2);
|
||||
return VALID_PHONE_PREFIXES.includes(prefix);
|
||||
},
|
||||
{ message: t("validation.invalidPhonePrefix", "validation.invalidPhonePrefix") },
|
||||
),
|
||||
email: z.string().min(1, t("validation.required", "validation.required")),
|
||||
workingHours: z.string().min(1, t("validation.required", "validation.required")),
|
||||
description: z.string().optional(),
|
||||
phoneNumbers: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSberUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSberPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingVisaMasterUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingVisaMasterPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSwiftUsername: z.string().min(1, t("validation.required", "validation.required")),
|
||||
billingSwiftPassword: z.string().min(1, t("validation.required", "validation.required")),
|
||||
isActive: z.boolean(),
|
||||
});
|
||||
}
|
||||
@@ -45,9 +32,18 @@ type StepSchemas = Record<number, z.ZodType<Partial<BranchFormData>>>;
|
||||
function createStepSchemas(t: (key: string, fallback?: string) => string): StepSchemas {
|
||||
const schema = createBranchFormSchema(t);
|
||||
return {
|
||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, code: true, districtId: true }),
|
||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phone: true, email: true }),
|
||||
2: schema.pick({ workingHours: true }),
|
||||
0: schema.pick({ nameTk: true, nameRu: true, nameEn: true, uniqueCode: true, provinceId: true, region: true }),
|
||||
1: schema.pick({ addressTk: true, addressRu: true, addressEn: true, phoneNumbers: true }),
|
||||
2: schema.pick({
|
||||
billingUsername: true,
|
||||
billingPassword: true,
|
||||
billingSberUsername: true,
|
||||
billingSberPassword: true,
|
||||
billingVisaMasterUsername: true,
|
||||
billingVisaMasterPassword: true,
|
||||
billingSwiftUsername: true,
|
||||
billingSwiftPassword: true,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -75,28 +71,40 @@ export const DEFAULT_FORM_VALUES: BranchFormData = {
|
||||
nameTk: "",
|
||||
nameRu: "",
|
||||
nameEn: "",
|
||||
code: "",
|
||||
districtId: "",
|
||||
uniqueCode: "",
|
||||
provinceId: "",
|
||||
region: "",
|
||||
addressTk: "",
|
||||
addressRu: "",
|
||||
addressEn: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
workingHours: "",
|
||||
description: "",
|
||||
phoneNumbers: "",
|
||||
billingUsername: "",
|
||||
billingPassword: "",
|
||||
billingSberUsername: "",
|
||||
billingSberPassword: "",
|
||||
billingVisaMasterUsername: "",
|
||||
billingVisaMasterPassword: "",
|
||||
billingSwiftUsername: "",
|
||||
billingSwiftPassword: "",
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
export function buildPayload(data: BranchFormData): CreateBranchPayload {
|
||||
return {
|
||||
name: { tk: data.nameTk, ru: data.nameRu, en: data.nameEn },
|
||||
code: data.code,
|
||||
districtId: Number(data.districtId),
|
||||
address: { tk: data.addressTk, ru: data.addressRu, en: data.addressEn },
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
workingHours: data.workingHours,
|
||||
description: (data.description ?? "").trim() || null,
|
||||
isActive: data.isActive,
|
||||
name: { tm: data.nameTk.trim(), ru: data.nameRu.trim(), en: data.nameEn.trim() },
|
||||
uniqueCode: data.uniqueCode.trim(),
|
||||
provinceId: Number(data.provinceId),
|
||||
region: data.region.trim(),
|
||||
address: { tm: data.addressTk.trim(), ru: data.addressRu.trim(), en: data.addressEn.trim() },
|
||||
phoneNumbers: data.phoneNumbers.trim(),
|
||||
billingUsername: data.billingUsername.trim(),
|
||||
billingPassword: data.billingPassword,
|
||||
billingSberUsername: data.billingSberUsername.trim(),
|
||||
billingSberPassword: data.billingSberPassword,
|
||||
billingVisaMasterUsername: data.billingVisaMasterUsername.trim(),
|
||||
billingVisaMasterPassword: data.billingVisaMasterPassword,
|
||||
billingSwiftUsername: data.billingSwiftUsername.trim(),
|
||||
billingSwiftPassword: data.billingSwiftPassword,
|
||||
active: data.isActive,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user