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,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>
|
||||
)
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user