+
- )
+ );
}
// ─── Grid helpers ─────────────────────────────────────────────────────────────
-const grid2 = 'grid grid-cols-1 sm:grid-cols-2 gap-6'
-const grid3 = 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6'
-const grid4 = 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6'
+const grid2 = "grid grid-cols-1 sm:grid-cols-2 gap-6";
+const grid3 = "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6";
+const grid4 = "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6";
// ─── Static options ───────────────────────────────────────────────────────────
const REGION_OPTIONS = [
- { value: 'Aşgabat', label: 'Aşgabat' },
- { value: 'Ahal', label: 'Ahal' },
- { value: 'Balkan', label: 'Balkan' },
- { value: 'Daşoguz', label: 'Daşoguz' },
- { value: 'Lebap', label: 'Lebap' },
- { value: 'Mary', label: 'Mary' },
- { value: 'Arkadag', label: 'Arkadag' },
-]
+ { value: "Aşgabat", label: "Aşgabat" },
+ { value: "Ahal", label: "Ahal" },
+ { value: "Balkan", label: "Balkan" },
+ { value: "Daşoguz", label: "Daşoguz" },
+ { value: "Lebap", label: "Lebap" },
+ { value: "Mary", label: "Mary" },
+ { value: "Arkadag", label: "Arkadag" },
+];
const EDUCATION_OPTIONS = [
- { value: 'high', label: 'Ýokary bilim' },
- { value: 'unfinished_high', label: 'Gutarylmadyk ýokary bilim' },
- { value: 'masters', label: 'Magistr' },
- { value: 'phd', label: 'Ylymlaryň doktory' },
- { value: 'middle', label: 'Orta mekdep' },
- { value: 'school', label: 'Orta bilim' },
- { value: 'school_dropout', label: 'Gutarylmadyk orta bilim' },
-]
+ { value: "high", label: "Ýokary bilim" },
+ { value: "unfinished_high", label: "Gutarylmadyk ýokary bilim" },
+ { value: "masters", label: "Magistr" },
+ { value: "phd", label: "Ylymlaryň doktory" },
+ { value: "middle", label: "Orta mekdep" },
+ { value: "school", label: "Orta bilim" },
+ { value: "school_dropout", label: "Gutarylmadyk orta bilim" },
+];
const MARRIAGE_OPTIONS = [
- { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' },
- { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' },
- { value: 'DIVORCED', label: 'Aýrylşan' },
- { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' },
- { value: 'LEGAL', label: 'Raýat nika' },
-]
+ { value: "MARRIED", label: "Öýlenen / Durmuşa çykan" },
+ { value: "SINGLE", label: "Öýlenmedik / Durmuşa çykmadyk" },
+ { value: "DIVORCED", label: "Aýrylşan" },
+ { value: "WIDOW", label: "Adamsy ýa-da aýaly aradan çykan" },
+ { value: "LEGAL", label: "Raýat nika" },
+];
const STATUS_OPTIONS = [
- { value: 'GARAŞYLÝAR', label: 'Garaşylýar' },
- { value: 'IŞLENÝÄR', label: 'Işlenýär' },
- { value: 'KANAGATLANDYRYLAN', label: 'Kanagatlandyrylan' },
- { value: 'RED_EDILDI', label: 'Red edildi' },
-]
+ { value: "GARAŞYLÝAR", label: "Garaşylýar" },
+ { value: "IŞLENÝÄR", label: "Işlenýär" },
+ { value: "KANAGATLANDYRYLAN", label: "Kanagatlandyrylan" },
+ { value: "RED_EDILDI", label: "Red edildi" },
+];
const LOAN_TYPE_OPTIONS = [
- { value: 'consumer', label: 'Sarp ediş karzy' },
- { value: 'mortgage', label: 'Ipoteka' },
- { value: 'car', label: 'Awtoulag karzy' },
- { value: 'student', label: 'Talyplar üçin' },
- { value: 'business', label: 'Işewürlik karzy' },
-]
+ { value: "consumer", label: "Sarp ediş karzy" },
+ { value: "mortgage", label: "Ipoteka" },
+ { value: "car", label: "Awtoulag karzy" },
+ { value: "student", label: "Talyplar üçin" },
+ { value: "business", label: "Işewürlik karzy" },
+];
const PASSPORT_SERIES_OPTIONS = [
- { value: 'I', label: 'I' },
- { value: 'II', label: 'II' },
-]
+ { value: "I", label: "I" },
+ { value: "II", label: "II" },
+];
// ─── Form State ───────────────────────────────────────────────────────────────
interface FormState {
- status: string
- loanType: string
- region: string
- branch: string
- firstName: string
- lastName: string
- patronicName: string
- education: string
- marriageStatus: string
- dateOfBirth: string
- residence: string
- currentResidence: string
- passportSerie: string
- passportNumber: string
- passportDateOfIssue: string
- passportGivenBy: string
- bornPlace: string
- email: string
- phone: string
- phoneAdditional: string
- homePhone: string
- workCompany: string
- workHrPhone: string
- workRegion: string
- workProvince: string
- position: string
- salary: string
- workStartedAt: string
- passportPage1: File | null
- passportPage23: File | null
- passportPage89: File | null
- passportPage32: File | null
-
- // New fields
- note: string
- loanAmount: string
- loanHistory: string
-
- cardNumber: string
- cardName: string
- cardExpMonth: string
- cardExpYear: string
-
- guarantor1Name: string
- guarantor1Surname: string
- guarantor1Patronic: string
- guarantor1PassportSerie: string
- guarantor1PassportNumber: string
- guarantor1CardNumber: string
- guarantor1CardName: string
- guarantor1CardExpMonth: string
- guarantor1CardExpYear: string
- guarantor1Salary: string
+ status: string;
+ loanType: string;
+ region: string;
+ branch: string;
+ firstName: string;
+ lastName: string;
+ patronicName: string;
+ education: string;
+ marriageStatus: string;
+ dateOfBirth: string;
+ residence: string;
+ currentResidence: string;
+ passportSerie: string;
+ passportNumber: string;
+ passportDateOfIssue: string;
+ passportGivenBy: string;
+ bornPlace: string;
+ email: string;
+ phone: string;
+ phoneAdditional: string;
+ homePhone: string;
+ workCompany: string;
+ workHrPhone: string;
+ workRegion: string;
+ workProvince: string;
+ position: string;
+ salary: string;
+ workStartedAt: string;
+ passportPage1: File | null;
+ passportPage23: File | null;
+ passportPage89: File | null;
+ passportPage32: File | null;
+ note: string;
+ loanAmount: string;
+ loanHistory: string;
+ cardNumber: string;
+ cardName: string;
+ cardExpMonth: string;
+ cardExpYear: string;
+ guarantor1Name: string;
+ guarantor1Surname: string;
+ guarantor1Patronic: string;
+ guarantor1PassportSerie: string;
+ guarantor1PassportNumber: string;
+ guarantor1CardNumber: string;
+ guarantor1CardName: string;
+ guarantor1CardExpMonth: string;
+ guarantor1CardExpYear: string;
+ guarantor1Salary: string;
}
-type FormErrors = Partial
>
+type FormErrors = Partial>;
const INITIAL_STATE: FormState = {
- status: 'GARAŞYLÝAR',
- loanType: '',
- region: 'Aşgabat',
- branch: '',
- firstName: '',
- lastName: '',
- patronicName: '',
- education: '',
- marriageStatus: '',
- dateOfBirth: '',
- residence: '',
- currentResidence: '',
- passportSerie: '',
- passportNumber: '',
- passportDateOfIssue: '',
- passportGivenBy: '',
- bornPlace: '',
- email: '',
- phone: '',
- phoneAdditional: '',
- homePhone: '',
- workCompany: '',
- workHrPhone: '',
- workRegion: 'Aşgabat',
- workProvince: '',
- position: '',
- salary: '',
- workStartedAt: '',
+ status: "GARAŞYLÝAR",
+ loanType: "",
+ region: "Aşgabat",
+ branch: "",
+ firstName: "",
+ lastName: "",
+ patronicName: "",
+ education: "",
+ marriageStatus: "",
+ dateOfBirth: "",
+ residence: "",
+ currentResidence: "",
+ passportSerie: "",
+ passportNumber: "",
+ passportDateOfIssue: "",
+ passportGivenBy: "",
+ bornPlace: "",
+ email: "",
+ phone: "",
+ phoneAdditional: "",
+ homePhone: "",
+ workCompany: "",
+ workHrPhone: "",
+ workRegion: "Aşgabat",
+ workProvince: "",
+ position: "",
+ salary: "",
+ workStartedAt: "",
passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
-
- note: '',
- loanAmount: '',
- loanHistory: '',
-
- cardNumber: '',
- cardName: '',
- cardExpMonth: '',
- cardExpYear: '',
-
- guarantor1Name: '',
- guarantor1Surname: '',
- guarantor1Patronic: '',
- guarantor1PassportSerie: '',
- guarantor1PassportNumber: '',
- guarantor1CardNumber: '',
- guarantor1CardName: '',
- guarantor1CardExpMonth: '',
- guarantor1CardExpYear: '',
- guarantor1Salary: '',
-}
-
-// ─── Map LoanOrder → FormState (edit modunda başlangıç değerleri) ─────────────
+ note: "",
+ loanAmount: "",
+ loanHistory: "",
+ cardNumber: "",
+ cardName: "",
+ cardExpMonth: "",
+ cardExpYear: "",
+ guarantor1Name: "",
+ guarantor1Surname: "",
+ guarantor1Patronic: "",
+ guarantor1PassportSerie: "",
+ guarantor1PassportNumber: "",
+ guarantor1CardNumber: "",
+ guarantor1CardName: "",
+ guarantor1CardExpMonth: "",
+ guarantor1CardExpYear: "",
+ guarantor1Salary: "",
+};
function mapToFormState(order: LoanOrderMobile): FormState {
return {
- status: order.status ?? 'GARAŞYLÝAR',
- loanType: order.loanType ?? '',
- region: order.region ?? 'Aşgabat',
- branch: order.branch ?? '',
- firstName: order.firstName ?? '',
- lastName: order.lastName ?? '',
- patronicName: order.patronicName ?? '',
- education: order.education ?? '',
- marriageStatus: order.marriageStatus ?? '',
- dateOfBirth: order.dateOfBirth ?? '',
- residence: order.residence ?? '',
- currentResidence: order.currentResidence ?? '',
- passportSerie: order.passportSerie ?? '',
- passportNumber: order.passportNumber ?? '',
- passportDateOfIssue: order.passportDateOfIssue ?? '',
- passportGivenBy: order.passportGivenBy ?? '',
- bornPlace: order.bornPlace ?? '',
- email: order.email ?? '',
- phone: order.phone ?? '',
- phoneAdditional: order.phoneAdditional ?? '',
- homePhone: order.homePhone ?? '',
- workCompany: order.workCompany ?? '',
- workHrPhone: order.workHrPhone ?? '',
- workRegion: order.workRegion ?? 'Aşgabat',
- workProvince: order.workProvince ?? '',
- position: order.position ?? '',
- salary: order.salary != null ? String(order.salary) : '',
- workStartedAt: order.workStartedAt ?? '',
- // File field'ları edit modunda null kalır — mevcut URL'ler ayrı gösterilir
- passportPage1: null,
+ status: order.status ?? "GARAŞYLÝAR",
+ loanType: order.loanType ?? "",
+ region: order.region ?? "Aşgabat",
+ branch: order.branch ?? "",
+ firstName: order.firstName ?? "",
+ lastName: order.lastName ?? "",
+ patronicName: order.patronicName ?? "",
+ education: order.education ?? "",
+ marriageStatus: order.marriageStatus ?? "",
+ dateOfBirth: order.dateOfBirth ?? "",
+ residence: order.residence ?? "",
+ currentResidence: order.currentResidence ?? "",
+ passportSerie: order.passportSerie ?? "",
+ passportNumber: order.passportNumber ?? "",
+ passportDateOfIssue: order.passportDateOfIssue ?? "",
+ passportGivenBy: order.passportGivenBy ?? "",
+ bornPlace: order.bornPlace ?? "",
+ email: order.email ?? "",
+ phone: order.phone ?? "",
+ phoneAdditional: order.phoneAdditional ?? "",
+ homePhone: order.homePhone ?? "",
+ workCompany: order.workCompany ?? "",
+ workHrPhone: order.workHrPhone ?? "",
+ workRegion: order.workRegion ?? "Aşgabat",
+ workProvince: order.workProvince ?? "",
+ position: order.position ?? "",
+ salary: order.salary != null ? String(order.salary) : "",
+ workStartedAt: order.workStartedAt ?? "",
+ passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
-
- note: order.note ?? '',
- loanAmount: order.loanAmount != null ? String(order.loanAmount) : '',
- loanHistory: order.loanHistory ?? '',
-
- cardNumber: order.cardNumber ?? '',
- cardName: order.cardName ?? '',
- cardExpMonth: order.cardExpMonth ?? '',
- cardExpYear: order.cardExpYear ?? '',
-
- guarantor1Name: order.guarantor1Name ?? '',
- guarantor1Surname: order.guarantor1Surname ?? '',
- guarantor1Patronic: order.guarantor1Patronic ?? '',
- guarantor1PassportSerie: order.guarantor1PassportSerie ?? '',
- guarantor1PassportNumber: order.guarantor1PassportNumber ?? '',
- guarantor1CardNumber: order.guarantor1CardNumber ?? '',
- guarantor1CardName: order.guarantor1CardName ?? '',
- guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? '',
- guarantor1CardExpYear: order.guarantor1CardExpYear ?? '',
- guarantor1Salary: order.guarantor1Salary != null ? String(order.guarantor1Salary) : '',
- }
+ note: order.note ?? "",
+ loanAmount: order.loanAmount != null ? String(order.loanAmount) : "",
+ loanHistory: order.loanHistory ?? "",
+ cardNumber: order.cardNumber ?? "",
+ cardName: order.cardName ?? "",
+ cardExpMonth: order.cardExpMonth ?? "",
+ cardExpYear: order.cardExpYear ?? "",
+ guarantor1Name: order.guarantor1Name ?? "",
+ guarantor1Surname: order.guarantor1Surname ?? "",
+ guarantor1Patronic: order.guarantor1Patronic ?? "",
+ guarantor1PassportSerie: order.guarantor1PassportSerie ?? "",
+ guarantor1PassportNumber: order.guarantor1PassportNumber ?? "",
+ guarantor1CardNumber: order.guarantor1CardNumber ?? "",
+ guarantor1CardName: order.guarantor1CardName ?? "",
+ guarantor1CardExpMonth: order.guarantor1CardExpMonth ?? "",
+ guarantor1CardExpYear: order.guarantor1CardExpYear ?? "",
+ guarantor1Salary:
+ order.guarantor1Salary != null ? String(order.guarantor1Salary) : "",
+ };
}
+// ─── Step definitions ─────────────────────────────────────────────────────────
+
+// Keys that belong to each step — used for per-step validation
+const STEP_FIELDS: Array> = [
+ // Step 0 — Karz & Lokasiýa
+ ["loanType", "loanAmount", "region", "branch"],
+ // Step 1 — Şahsy maglumatlar & Pasport
+ [
+ "firstName",
+ "lastName",
+ "education",
+ "marriageStatus",
+ "dateOfBirth",
+ "residence",
+ "passportSerie",
+ "passportNumber",
+ "passportDateOfIssue",
+ "passportGivenBy",
+ ],
+ // Step 2 — Habarlaşmak & Iş
+ [
+ "phone",
+ "workCompany",
+ "position",
+ "salary",
+ "workStartedAt",
+ ],
+ // Step 3 — Kart & Zamun
+ [
+ "cardNumber",
+ "cardName",
+ "cardExpMonth",
+ "cardExpYear",
+ "guarantor1Name",
+ "guarantor1Surname",
+ "guarantor1PassportSerie",
+ "guarantor1PassportNumber",
+ "guarantor1CardNumber",
+ "guarantor1CardName",
+ "guarantor1CardExpMonth",
+ "guarantor1CardExpYear",
+ "guarantor1Salary",
+ ],
+ // Step 4 — Faýllar & Status
+ ["passportPage1", "passportPage23"],
+];
+
// ─── Validation ───────────────────────────────────────────────────────────────
function validate(
form: FormState,
t: (k: string) => string,
- mode: 'create' | 'edit'
+ mode: "create" | "edit",
+ stepIndex?: number,
): FormErrors {
- const errors: FormErrors = {}
+ const allErrors: FormErrors = {};
const req = (key: keyof FormState, label: string) => {
- const val = form[key]
- if (!val || (typeof val === 'string' && !val.trim())) {
- errors[key] = `${label} — ${t('required') || 'hökmany'}`
+ const val = form[key];
+ if (!val || (typeof val === "string" && !val.trim())) {
+ allErrors[key] = `${label} — ${t("required") || "hökmany"}`;
}
+ };
+
+ req("loanType", t("Loan type") || "Karz görnüşi");
+ req("region", t("Region") || "Welaýat");
+ req("branch", t("Branch") || "Şahamça");
+ req("firstName", t("Name") || "Ady");
+ req("lastName", t("Surname") || "Familiýasy");
+ req("education", t("Education") || "Bilimi");
+ req("marriageStatus", t("Marriage status") || "Maşgala ýagdaýy");
+ req("dateOfBirth", t("Date of birth") || "Doglan güni");
+ req("residence", t("Residence (passport)") || "Ýazgy edilen salgy");
+ req("passportSerie", t("Passport serie") || "Pasport seriýasy");
+ req("passportNumber", t("Passport number") || "Pasport belgisi");
+ req("passportDateOfIssue", t("Passport date of issue") || "Pasport berlen senesi");
+ req("passportGivenBy", t("Passport given by") || "Kim tarapyndan berildi");
+ req("phone", t("Phone") || "Telefon");
+ req("workCompany", t("Work company name") || "Kärhananyň ady");
+ req("position", t("Position") || "Wezipe");
+ req("salary", t("Salary") || "Zähmet haky");
+ req("workStartedAt", t("Work started at") || "Işe başlan wagty");
+ req("loanAmount", t("Loan amount") || "Karz möçberi");
+ req("cardNumber", t("Card number") || "Kart belgisi");
+ req("cardName", t("Card name") || "Kartdaky ady");
+ req("cardExpMonth", t("Card exp month") || "Kart Möhleti (aý)");
+ req("cardExpYear", t("Card exp year") || "Kart Möhleti (ýyl)");
+ req("guarantor1Name", t("Guarantor name") || "Zamunyň ady");
+ req("guarantor1Surname", t("Guarantor surname") || "Zamunyň familiýasy");
+ req("guarantor1PassportSerie", t("Guarantor passport serie") || "Pasport seriýasy (Zamun)");
+ req("guarantor1PassportNumber", t("Guarantor passport number") || "Pasport belgisi (Zamun)");
+ req("guarantor1CardNumber", t("Guarantor card number") || "Kart belgisi (Zamun)");
+ req("guarantor1CardName", t("Guarantor card name") || "Kartdaky ady (Zamun)");
+ req("guarantor1CardExpMonth", t("Guarantor card exp month") || "Möhleti (aý) (Zamun)");
+ req("guarantor1CardExpYear", t("Guarantor card exp year") || "Möhleti (ýyl) (Zamun)");
+ req("guarantor1Salary", t("Guarantor salary") || "Ortaca zähmet haky (Zamun)");
+
+ if (form.phone && form.phone.replace(/\D/g, "").length < 8) {
+ allErrors.phone = "Telefon belgisi nädogry";
}
- req('loanType', t('Loan type') || 'Karz görnüşi')
- req('region', t('Region') || 'Welaýat')
- req('branch', t('Branch') || 'Şahamça')
- req('firstName', t('Name') || 'Ady')
- req('lastName', t('Surname') || 'Familiýasy')
- req('education', t('Education') || 'Bilimi')
- req('marriageStatus', t('Marriage status') || 'Maşgala ýagdaýy')
- req('dateOfBirth', t('Date of birth') || 'Doglan güni')
- req('residence', t('Residence (passport)') || 'Ýazgy edilen salgy')
- req('passportSerie', t('Passport serie') || 'Pasport seriýasy')
- req('passportNumber', t('Passport number') || 'Pasport belgisi')
- req('passportDateOfIssue', t('Passport date of issue') || 'Pasport berlen senesi')
- req('passportGivenBy', t('Passport given by') || 'Kim tarapyndan berildi')
- req('phone', t('Phone') || 'Telefon')
- req('workCompany', t('Work company name') || 'Kärhananyň ady')
- req('position', t('Position') || 'Wezipe')
- req('salary', t('Salary') || 'Zähmet haky')
- req('workStartedAt', t('Work started at') || 'Işe başlan wagty')
-
- req('loanAmount', t('Loan amount') || 'Karz möçberi')
- req('cardNumber', t('Card number') || 'Kart belgisi')
- req('cardName', t('Card name') || 'Kartdaky ady')
- req('cardExpMonth', t('Card exp month') || 'Kart Möhleti (aý)')
- req('cardExpYear', t('Card exp year') || 'Kart Möhleti (ýyl)')
-
- req('guarantor1Name', t('Guarantor name') || 'Zamunyň ady')
- req('guarantor1Surname', t('Guarantor surname') || 'Zamunyň familiýasy')
- req('guarantor1PassportSerie', t('Guarantor passport serie') || 'Pasport seriýasy (Zamun)')
- req('guarantor1PassportNumber', t('Guarantor passport number') || 'Pasport belgisi (Zamun)')
- req('guarantor1CardNumber',t('Guarantor card number') || 'Kart belgisi (Zamun)')
- req('guarantor1CardName', t('Guarantor card name') || 'Kartdaky ady (Zamun)')
- req('guarantor1CardExpMonth', t('Guarantor card exp month') || 'Möhleti (aý) (Zamun)')
- req('guarantor1CardExpYear', t('Guarantor card exp year') || 'Möhleti (ýyl) (Zamun)')
- req('guarantor1Salary', t('Guarantor salary') || 'Ortaca zähmet haky (Zamun)')
-
- if (form.phone && form.phone.replace(/\D/g, '').length < 8) {
- errors.phone = 'Telefon belgisi nädogry'
+ if (mode === "create") {
+ if (!form.passportPage1) allErrors.passportPage1 = "Pasport (sahypa 1) hökmany";
+ if (!form.passportPage23) allErrors.passportPage23 = "Pasport (sahypa 2-3) hökmany";
}
- // File'lar diňe create modunda hökmany
- if (mode === 'create') {
- if (!form.passportPage1) errors.passportPage1 = 'Pasport (sahypa 1) hökmany'
- if (!form.passportPage23) errors.passportPage23 = 'Pasport (sahypa 2-3) hökmany'
+ // If stepIndex provided, filter to only that step's fields
+ if (stepIndex !== undefined) {
+ const stepKeys = STEP_FIELDS[stepIndex];
+ const stepErrors: FormErrors = {};
+ for (const key of stepKeys) {
+ if (allErrors[key]) stepErrors[key] = allErrors[key];
+ }
+ return stepErrors;
}
- return errors
+ return allErrors;
}
// ─── Props ────────────────────────────────────────────────────────────────────
interface LoanOrderMobileFormProps {
- mode: 'create' | 'edit'
- initialData?: LoanOrderMobile
- loanOrderId?: string
+ mode: "create" | "edit";
+ initialData?: LoanOrderMobile;
+ loanOrderId?: string;
}
// ─── Component ────────────────────────────────────────────────────────────────
-export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrderMobileFormProps) {
- const { t } = useTranslation()
- const navigate = useNavigate()
+export function LoanOrderMobileForm({
+ mode,
+ initialData,
+ loanOrderId,
+}: LoanOrderMobileFormProps) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
- const createMutation = useCreateLoanOrderMobile()
- const updateMutation = useUpdateLoanOrderMobile()
-
- const isPending = createMutation.isPending || updateMutation.isPending
+ const createMutation = useCreateLoanOrderMobile();
+ const updateMutation = useUpdateLoanOrderMobile();
+ const isPending = createMutation.isPending || updateMutation.isPending;
const [form, setForm] = useState(() =>
- initialData ? mapToFormState(initialData) : INITIAL_STATE
- )
- const [errors, setErrors] = useState({})
- const [submitted, setSubmitted] = useState(false)
+ initialData ? mapToFormState(initialData) : INITIAL_STATE,
+ );
+ const [errors, setErrors] = useState({});
+ // Track which steps have been validated (done or error)
+ const [stepStatuses, setStepStatuses] = useState<
+ Array<"idle" | "active" | "done" | "error">
+ >(["active", "idle", "idle", "idle", "idle"]);
+ const [currentStep, setCurrentStep] = useState(0);
- const set = useCallback(
- (key: K, value: FormState[K]) => {
- setForm((prev) => ({ ...prev, [key]: value }))
- if (submitted) {
- setErrors((prev) => ({ ...prev, [key]: undefined }))
- }
+ const set = useCallback((key: K, value: FormState[K]) => {
+ setForm((prev) => ({ ...prev, [key]: value }));
+ setErrors((prev) => ({ ...prev, [key]: undefined }));
+ }, []);
+
+ // Build step items for StepBarCards
+ const STEP_DEFS = [
+ {
+ id: "loan",
+ title: t("Loan") || "Karz",
+ subtitle: t("Type & amount") || "Görnüş & möçber",
+ icon: FileText,
},
- [submitted]
- )
+ {
+ id: "personal",
+ title: t("Personal") || "Şahsy",
+ subtitle: t("Identity & passport") || "Şahsyýet & pasport",
+ icon: User,
+ },
+ {
+ id: "contact",
+ title: t("Contact & Job") || "Habarlaşmak & Iş",
+ subtitle: t("Phone & employment") || "Telefon & iş",
+ icon: Phone,
+ },
+ {
+ id: "card",
+ title: t("Card & Guarantor") || "Kart & Zamun",
+ subtitle: t("Payment & guarantor") || "Töleg & zamun",
+ icon: CreditCard,
+ },
+ {
+ id: "files",
+ title: t("Files & Status") || "Faýllar & Status",
+ subtitle: t("Documents & review") || "Resminamalar",
+ icon: Upload,
+ },
+ ];
+
+ const stepItems: StepCardItem[] = STEP_DEFS.map((def, i) => ({
+ ...def,
+ status: stepStatuses[i],
+ }));
+
+ const updateStepStatus = (
+ index: number,
+ status: "idle" | "active" | "done" | "error",
+ ) => {
+ setStepStatuses((prev) => {
+ const next = [...prev];
+ next[index] = status;
+ return next;
+ });
+ };
+
+ const goToStep = (index: number) => {
+ updateStepStatus(currentStep, stepStatuses[currentStep] === "error" ? "error" : "done");
+ updateStepStatus(index, "active");
+ setCurrentStep(index);
+ window.scrollTo({ top: 0, behavior: "smooth" });
+ };
+
+ const handleNext = () => {
+ const stepErrors = validate(form, t, mode, currentStep);
+ if (Object.keys(stepErrors).length > 0) {
+ setErrors((prev) => ({ ...prev, ...stepErrors }));
+ updateStepStatus(currentStep, "error");
+ toast.error(t("Write a correct data please") || "Dogry maglumat girizmegiňizi haýyş edýäris.");
+ const firstKey = Object.keys(stepErrors)[0];
+ document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: "smooth", block: "center" });
+ return;
+ }
+ updateStepStatus(currentStep, "done");
+ const next = currentStep + 1;
+ updateStepStatus(next, "active");
+ setCurrentStep(next);
+ window.scrollTo({ top: 0, behavior: "smooth" });
+ };
+
+ const handlePrev = () => {
+ const prev = currentStep - 1;
+ updateStepStatus(currentStep, stepStatuses[currentStep] === "error" ? "error" : "idle");
+ updateStepStatus(prev, "active");
+ setCurrentStep(prev);
+ window.scrollTo({ top: 0, behavior: "smooth" });
+ };
const handleSubmit = () => {
- setSubmitted(true)
- const errs = validate(form, t, mode)
- if (Object.keys(errs).length > 0) {
- setErrors(errs)
- toast.error(t('Write a correct data please') || 'Dogry maglumat girizmegiňizi haýyş edýäris.')
- const firstKey = Object.keys(errs)[0]
- document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' })
- return
+ // Full validation across all steps
+ const allErrors = validate(form, t, mode);
+ if (Object.keys(allErrors).length > 0) {
+ setErrors(allErrors);
+ // Mark steps with errors
+ const newStatuses = stepStatuses.map((s, i) => {
+ const stepKeys = STEP_FIELDS[i];
+ const hasError = stepKeys.some((k) => allErrors[k]);
+ if (i === currentStep) return hasError ? "error" : "active";
+ if (hasError) return "error";
+ return s === "idle" ? "idle" : "done";
+ }) as typeof stepStatuses;
+ setStepStatuses(newStatuses);
+ toast.error(t("Write a correct data please") || "Dogry maglumat girizmegiňizi haýyş edýäris.");
+ return;
}
const payload: LoanOrderMobilePayload = {
- status: form.status,
- loanType: form.loanType,
- region: form.region,
- branch: form.branch,
- firstName: form.firstName,
- lastName: form.lastName,
- patronicName: form.patronicName || undefined,
- education: form.education,
- marriageStatus: form.marriageStatus,
- dateOfBirth: form.dateOfBirth,
- residence: form.residence,
- currentResidence: form.currentResidence || undefined,
- passportSerie: form.passportSerie,
- passportNumber: form.passportNumber,
+ status: form.status,
+ loanType: form.loanType,
+ region: form.region,
+ branch: form.branch,
+ firstName: form.firstName,
+ lastName: form.lastName,
+ patronicName: form.patronicName || undefined,
+ education: form.education,
+ marriageStatus: form.marriageStatus,
+ dateOfBirth: form.dateOfBirth,
+ residence: form.residence,
+ currentResidence: form.currentResidence || undefined,
+ passportSerie: form.passportSerie,
+ passportNumber: form.passportNumber,
passportDateOfIssue: form.passportDateOfIssue,
- passportGivenBy: form.passportGivenBy,
- bornPlace: form.bornPlace || undefined,
- email: form.email || undefined,
- phone: form.phone,
- phoneAdditional: form.phoneAdditional || undefined,
- homePhone: form.homePhone || undefined,
- workCompany: form.workCompany,
- workHrPhone: form.workHrPhone || undefined,
- workRegion: form.workRegion || undefined,
- workProvince: form.workProvince || undefined,
- position: form.position,
- salary: Number(form.salary),
- workStartedAt: form.workStartedAt,
- note: form.note || undefined,
- loanAmount: Number(form.loanAmount) || undefined,
- loanHistory: form.loanHistory || undefined,
- cardNumber: form.cardNumber || undefined,
- cardName: form.cardName || undefined,
- cardExpMonth: form.cardExpMonth || undefined,
- cardExpYear: form.cardExpYear || undefined,
- guarantor1Name: form.guarantor1Name || undefined,
- guarantor1Surname: form.guarantor1Surname || undefined,
- guarantor1Patronic: form.guarantor1Patronic || undefined,
- guarantor1PassportSerie: form.guarantor1PassportSerie || undefined,
+ passportGivenBy: form.passportGivenBy,
+ bornPlace: form.bornPlace || undefined,
+ email: form.email || undefined,
+ phone: form.phone,
+ phoneAdditional: form.phoneAdditional || undefined,
+ homePhone: form.homePhone || undefined,
+ workCompany: form.workCompany,
+ workHrPhone: form.workHrPhone || undefined,
+ workRegion: form.workRegion || undefined,
+ workProvince: form.workProvince || undefined,
+ position: form.position,
+ salary: Number(form.salary),
+ workStartedAt: form.workStartedAt,
+ note: form.note || undefined,
+ loanAmount: Number(form.loanAmount) || undefined,
+ loanHistory: form.loanHistory || undefined,
+ cardNumber: form.cardNumber || undefined,
+ cardName: form.cardName || undefined,
+ cardExpMonth: form.cardExpMonth || undefined,
+ cardExpYear: form.cardExpYear || undefined,
+ guarantor1Name: form.guarantor1Name || undefined,
+ guarantor1Surname: form.guarantor1Surname || undefined,
+ guarantor1Patronic: form.guarantor1Patronic || undefined,
+ guarantor1PassportSerie: form.guarantor1PassportSerie || undefined,
guarantor1PassportNumber: form.guarantor1PassportNumber || undefined,
- guarantor1CardNumber: form.guarantor1CardNumber || undefined,
- guarantor1CardName: form.guarantor1CardName || undefined,
- guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined,
- guarantor1CardExpYear: form.guarantor1CardExpYear || undefined,
- guarantor1Salary: Number(form.guarantor1Salary) || undefined,
- }
+ guarantor1CardNumber: form.guarantor1CardNumber || undefined,
+ guarantor1CardName: form.guarantor1CardName || undefined,
+ guarantor1CardExpMonth: form.guarantor1CardExpMonth || undefined,
+ guarantor1CardExpYear: form.guarantor1CardExpYear || undefined,
+ guarantor1Salary: Number(form.guarantor1Salary) || undefined,
+ };
- if (mode === 'create') {
+ if (mode === "create") {
createMutation.mutate(payload, {
- onSuccess: () => navigate('/loan-order-mobiles'),
- })
+ onSuccess: () => navigate("/loan-order-mobiles"),
+ });
} else {
updateMutation.mutate(
{ id: loanOrderId!, payload },
- { onSuccess: () => navigate('/loan-order-mobiles') }
- )
+ { onSuccess: () => navigate("/loan-order-mobiles") },
+ );
}
- }
+ };
+
+ const isLastStep = currentStep === STEP_DEFS.length - 1;
+ const isFirstStep = currentStep === 0;
// ── Render ──────────────────────────────────────────────────────────────────
return (
@@ -436,729 +592,763 @@ export function LoanOrderMobileForm({ mode, initialData, loanOrderId }: LoanOrde
{/* Page title */}
- {mode === 'create'
- ? (t('Loan order create') || 'Karz sargyt döredüň')
- : (t('Loan order edit') || 'Karz sargydy üýtget')}
+ {mode === "create"
+ ? t("Loan order create") || "Karz sargyt döredüň"
+ : t("Loan order edit") || "Karz sargydy üýtget"}
- {/* ── Status ─────────────────────────────────────────────────────────── */}
-
-
-
- set('status', v)}
- options={STATUS_OPTIONS}
- error={errors.status}
- placeholder="Saýlaň"
- />
-
-
- set('note', v)}
- placeholder={t('Note') || 'Bellik'}
- />
-
-
-
-
- {/* ── Loan Type ──────────────────────────────────────────────────────── */}
-
-
-
- set('loanType', v)}
- options={LOAN_TYPE_OPTIONS}
- placeholder="Saýlamak üçin basyň"
- error={errors.loanType}
- />
-
-
- set('loanAmount', v)}
- placeholder="Karz möçberi"
- error={errors.loanAmount}
- />
-
-
-
-
- {/* ── Location ───────────────────────────────────────────────────────── */}
-
-
-
- set('region', v)}
- options={REGION_OPTIONS}
- placeholder="Saýlamak üçin basyň"
- error={errors.region}
- />
-
-
- set('branch', v)}
- options={[]}
- placeholder="Saýlamak üçin basyň"
- error={errors.branch}
- />
-
-
-
-
- {/* ── Personal Data ──────────────────────────────────────────────────── */}
-
-
-
-
- set('firstName', v)}
- placeholder={t('Name') || 'Ady'}
- error={errors.firstName}
- />
-
-
- set('lastName', v)}
- placeholder={t('Surname') || 'Familiýasy'}
- error={errors.lastName}
- />
-
-
- set('patronicName', v)}
- placeholder={t('Patronic name') || 'Atasynyň ady'}
- />
-
-
-
-
-
- set('education', v)}
- options={EDUCATION_OPTIONS}
- placeholder="Saýlaň"
- error={errors.education}
- />
-
-
- set('marriageStatus', v)}
- options={MARRIAGE_OPTIONS}
- placeholder="Saýlaň"
- error={errors.marriageStatus}
- />
-
-
- set('dateOfBirth', v)}
- error={errors.dateOfBirth}
- />
-
-
-
-
-
- set('residence', v)}
- placeholder={t('Residence (passport)') || 'Ýazgy edilen salgyňyz'}
- error={errors.residence}
- />
-
-
- set('currentResidence', v)}
- placeholder={t('Current Residence') || 'Häzirki ýaşaýyş ýeri'}
- />
-
-
-
-
- set('loanHistory', v)}
- options={[]}
- placeholder="Saýlamak üçin basyň"
- />
-
-
-
-
- {/* ── Card ───────────────────────────────────────────────────────────── */}
-
-
-
- set('cardNumber', v)}
- placeholder="Kart belgisi"
- error={errors.cardNumber}
- />
-
-
- set('cardName', v)}
- placeholder="Kartdaky ady"
- error={errors.cardName}
- />
-
-
- set('cardExpMonth', v)}
- options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1).padStart(2, '0'), label: String(i + 1).padStart(2, '0') }))}
- placeholder="Saýlamak üçin basyň"
- error={errors.cardExpMonth}
- />
-
-
- set('cardExpYear', v)}
- options={Array.from({ length: 15 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))}
- placeholder="Saýlamak üçin basyň"
- error={errors.cardExpYear}
- />
-
-
-
-
- {/* ── Passport ───────────────────────────────────────────────────────── */}
-
-
-
-
- set('passportSerie', v)}
- options={PASSPORT_SERIES_OPTIONS}
- placeholder="Saýlamak üçin basyň"
- error={errors.passportSerie}
- />
-
-
- set('passportNumber', v)}
- placeholder={t('Passport number') || 'Pasport belgisi'}
- error={errors.passportNumber}
- />
-
-
- set('passportDateOfIssue', v)}
- error={errors.passportDateOfIssue}
- />
-
-
-
-
-
- set('passportGivenBy', v)}
- placeholder={t('Passport given by') || 'Kim tarapyndan berildi'}
- error={errors.passportGivenBy}
- />
-
-
- set('bornPlace', v)}
- placeholder={t('Born place (passport)') || 'Doglan ýeri (pasport)'}
- />
-
-
-
-
-
- {/* ── Contact ────────────────────────────────────────────────────────── */}
-
-
-
- set('email', v)}
- placeholder="E-poçta"
- />
-
-
- set('phone', v)}
- placeholder="61 097 651"
- error={errors.phone}
- />
-
-
- set('phoneAdditional', v)}
- placeholder="61 097 651"
- />
-
-
- set('homePhone', v)}
- placeholder="61 097 651"
- />
-
-
-
-
- {/* ── Job ────────────────────────────────────────────────────────────── */}
-
-
-
-
- set('workCompany', v)}
- placeholder={t('Work company name') || 'Işleýän edaranyň/kärhananyň ady'}
- error={errors.workCompany}
- />
-
-
- set('workHrPhone', v)}
- placeholder="61 097 651"
- />
-
-
-
-
-
- set('workRegion', v)}
- options={REGION_OPTIONS}
- placeholder="Saýlamak üçin basyň"
- />
-
-
- set('workProvince', v)}
- options={[]}
- placeholder="Saýlamak üçin basyň"
- />
-
-
-
-
-
- set('position', v)}
- placeholder={t('Position') || 'Wezipe'}
- error={errors.position}
- />
-
-
- set('salary', v)}
- placeholder={t('Salary') || 'Zähmet haky'}
- error={errors.salary}
- />
-
-
- set('workStartedAt', v)}
- error={errors.workStartedAt}
- />
-
-
-
-
-
- {/* ── Passport Files ─────────────────────────────────────────────────── */}
-
- {/* Edit modunda mevcut resimleri göster */}
- {mode === 'edit' && initialData && (
-
- {initialData.passportPage1Url && (
-
- )}
- {initialData.passportPage23Url && (
-
- )}
- {initialData.passportPage89Url && (
-
- )}
- {initialData.passportPage32Url && (
-
- )}
-
- )}
-
-
-
- set('passportPage1', f)}
- placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
- error={errors.passportPage1}
- />
-
-
- set('passportPage23', f)}
- placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
- error={errors.passportPage23}
- />
-
-
- set('passportPage89', f)}
- placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
- />
-
-
- set('passportPage32', f)}
- placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
- />
-
-
-
-
- {/* ── Zamun ──────────────────────────────────────────────────────────── */}
-
-
-
-
- set('guarantor1Name', v)}
- placeholder="Zamunyň ady"
- error={errors.guarantor1Name}
- />
-
-
- set('guarantor1Surname', v)}
- placeholder="Zamunyň familiýasy"
- error={errors.guarantor1Surname}
- />
-
-
- set('guarantor1Patronic', v)}
- placeholder="Zamunyň atasynyň ady"
- />
-
-
-
-
-
- set('guarantor1PassportSerie', v)}
- options={PASSPORT_SERIES_OPTIONS}
- placeholder="Saýlamak üçin basyň"
- error={errors.guarantor1PassportSerie}
- />
-
-
- set('guarantor1PassportNumber', v)}
- placeholder="Pasport belgisi"
- error={errors.guarantor1PassportNumber}
- />
-
-
-
-
-
- set('guarantor1CardNumber', v)}
- placeholder="Kart belgisi"
- error={errors.guarantor1CardNumber}
- />
-
-
- set('guarantor1CardName', v)}
- placeholder="Kartdaky ady"
- error={errors.guarantor1CardName}
- />
-
-
- set('guarantor1CardExpMonth', v)}
- options={Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1).padStart(2, '0'), label: String(i + 1).padStart(2, '0') }))}
- placeholder="Saýlamak üçin basyň"
- error={errors.guarantor1CardExpMonth}
- />
-
-
- set('guarantor1CardExpYear', v)}
- options={Array.from({ length: 15 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))}
- placeholder="Saýlamak üçin basyň"
- error={errors.guarantor1CardExpYear}
- />
-
-
-
-
-
- set('guarantor1Salary', v)}
- placeholder="Ortaca zähmet haky"
- error={errors.guarantor1Salary}
- />
-
-
-
-
-
- {/* ── Footer Actions ─────────────────────────────────────────────────── */}
-
-
-
+ {/* ── Step Bar ───────────────────────────────────────────────────────── */}
+
+
+
+ {/* ── Step 0: Karz & Lokasiýa ────────────────────────────────────────── */}
+ {currentStep === 0 && (
+ <>
+
+
+
+ set("loanType", v)}
+ options={LOAN_TYPE_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.loanType}
+ />
+
+
+ set("loanAmount", v)}
+ placeholder="Karz möçberi"
+ error={errors.loanAmount}
+ />
+
+
+
+
+
+
+
+ set("region", v)}
+ options={REGION_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.region}
+ />
+
+
+ set("branch", v)}
+ options={[]}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.branch}
+ />
+
+
+
+ >
+ )}
+
+ {/* ── Step 1: Şahsy maglumatlar & Pasport ───────────────────────────── */}
+ {currentStep === 1 && (
+ <>
+
+
+
+
+ set("firstName", v)}
+ placeholder={t("Name") || "Ady"}
+ error={errors.firstName}
+ />
+
+
+ set("lastName", v)}
+ placeholder={t("Surname") || "Familiýasy"}
+ error={errors.lastName}
+ />
+
+
+ set("patronicName", v)}
+ placeholder={t("Patronic name") || "Atasynyň ady"}
+ />
+
+
+
+
+
+ set("education", v)}
+ options={EDUCATION_OPTIONS}
+ placeholder="Saýlaň"
+ error={errors.education}
+ />
+
+
+ set("marriageStatus", v)}
+ options={MARRIAGE_OPTIONS}
+ placeholder="Saýlaň"
+ error={errors.marriageStatus}
+ />
+
+
+ set("dateOfBirth", v)}
+ error={errors.dateOfBirth}
+ />
+
+
+
+
+
+ set("residence", v)}
+ placeholder={t("Residence (passport)") || "Ýazgy edilen salgyňyz"}
+ error={errors.residence}
+ />
+
+
+ set("currentResidence", v)}
+ placeholder={t("Current Residence") || "Häzirki ýaşaýyş ýeri"}
+ />
+
+
+
+
+ set("loanHistory", v)}
+ options={[]}
+ placeholder="Saýlamak üçin basyň"
+ />
+
+
+
+
+
+
+
+
+ set("passportSerie", v)}
+ options={PASSPORT_SERIES_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.passportSerie}
+ />
+
+
+ set("passportNumber", v)}
+ placeholder={t("Passport number") || "Pasport belgisi"}
+ error={errors.passportNumber}
+ />
+
+
+ set("passportDateOfIssue", v)}
+ error={errors.passportDateOfIssue}
+ />
+
+
+
+
+
+ set("passportGivenBy", v)}
+ placeholder={t("Passport given by") || "Kim tarapyndan berildi"}
+ error={errors.passportGivenBy}
+ />
+
+
+ set("bornPlace", v)}
+ placeholder={t("Born place (passport)") || "Doglan ýeri (pasport)"}
+ />
+
+
+
+
+ >
+ )}
+
+ {/* ── Step 2: Habarlaşmak & Iş ──────────────────────────────────────── */}
+ {currentStep === 2 && (
+ <>
+
+
+
+ set("email", v)}
+ placeholder="E-poçta"
+ />
+
+
+ set("phone", v)}
+ placeholder="61 097 651"
+ error={errors.phone}
+ />
+
+
+ set("phoneAdditional", v)}
+ placeholder="61 097 651"
+ />
+
+
+ set("homePhone", v)}
+ placeholder="61 097 651"
+ />
+
+
+
+
+
+
+
+
+ set("workCompany", v)}
+ placeholder={t("Work company name") || "Işleýän edaranyň/kärhananyň ady"}
+ error={errors.workCompany}
+ />
+
+
+ set("workHrPhone", v)}
+ placeholder="61 097 651"
+ />
+
+
+
+
+
+ set("workRegion", v)}
+ options={REGION_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ />
+
+
+ set("workProvince", v)}
+ options={[]}
+ placeholder="Saýlamak üçin basyň"
+ />
+
+
+
+
+
+ set("position", v)}
+ placeholder={t("Position") || "Wezipe"}
+ error={errors.position}
+ />
+
+
+ set("salary", v)}
+ placeholder={t("Salary") || "Zähmet haky"}
+ error={errors.salary}
+ />
+
+
+ set("workStartedAt", v)}
+ error={errors.workStartedAt}
+ />
+
+
+
+
+ >
+ )}
+
+ {/* ── Step 3: Kart & Zamun ──────────────────────────────────────────── */}
+ {currentStep === 3 && (
+ <>
+
+
+
+ set("cardNumber", v)}
+ placeholder="Kart belgisi"
+ error={errors.cardNumber}
+ />
+
+
+ set("cardName", v)}
+ placeholder="Kartdaky ady"
+ error={errors.cardName}
+ />
+
+
+ set("cardExpMonth", v)}
+ options={Array.from({ length: 12 }, (_, i) => ({
+ value: String(i + 1).padStart(2, "0"),
+ label: String(i + 1).padStart(2, "0"),
+ }))}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.cardExpMonth}
+ />
+
+
+ set("cardExpYear", v)}
+ options={Array.from({ length: 15 }, (_, i) => ({
+ value: String(new Date().getFullYear() + i),
+ label: String(new Date().getFullYear() + i),
+ }))}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.cardExpYear}
+ />
+
+
+
+
+
+
+
+
+ set("guarantor1Name", v)}
+ placeholder="Zamunyň ady"
+ error={errors.guarantor1Name}
+ />
+
+
+ set("guarantor1Surname", v)}
+ placeholder="Zamunyň familiýasy"
+ error={errors.guarantor1Surname}
+ />
+
+
+ set("guarantor1Patronic", v)}
+ placeholder="Zamunyň atasynyň ady"
+ />
+
+
+
+
+
+ set("guarantor1PassportSerie", v)}
+ options={PASSPORT_SERIES_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.guarantor1PassportSerie}
+ />
+
+
+ set("guarantor1PassportNumber", v)}
+ placeholder="Pasport belgisi"
+ error={errors.guarantor1PassportNumber}
+ />
+
+
+
+
+
+ set("guarantor1CardNumber", v)}
+ placeholder="Kart belgisi"
+ error={errors.guarantor1CardNumber}
+ />
+
+
+ set("guarantor1CardName", v)}
+ placeholder="Kartdaky ady"
+ error={errors.guarantor1CardName}
+ />
+
+
+ set("guarantor1CardExpMonth", v)}
+ options={Array.from({ length: 12 }, (_, i) => ({
+ value: String(i + 1).padStart(2, "0"),
+ label: String(i + 1).padStart(2, "0"),
+ }))}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.guarantor1CardExpMonth}
+ />
+
+
+ set("guarantor1CardExpYear", v)}
+ options={Array.from({ length: 15 }, (_, i) => ({
+ value: String(new Date().getFullYear() + i),
+ label: String(new Date().getFullYear() + i),
+ }))}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.guarantor1CardExpYear}
+ />
+
+
+
+
+
+ set("guarantor1Salary", v)}
+ placeholder="Ortaca zähmet haky"
+ error={errors.guarantor1Salary}
+ />
+
+
+
+
+ >
+ )}
+
+ {/* ── Step 4: Faýllar & Status ──────────────────────────────────────── */}
+ {currentStep === 4 && (
+ <>
+
+
+
+ set("status", v)}
+ options={STATUS_OPTIONS}
+ error={errors.status}
+ placeholder="Saýlaň"
+ />
+
+
+ set("note", v)}
+ placeholder={t("Note") || "Bellik"}
+ />
+
+
+
+
+
+ {/* Edit modunda mevcut dosyaları göster */}
+ {mode === "edit" && initialData && (
+
+ {initialData.passportPage1Url && (
+
+ )}
+ {initialData.passportPage23Url && (
+
+ )}
+ {initialData.passportPage89Url && (
+
+ )}
+ {initialData.passportPage32Url && (
+
+ )}
+
+ )}
+
+
+
+ set("passportPage1", f)}
+ placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
+ error={errors.passportPage1}
+ />
+
+
+ set("passportPage23", f)}
+ placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
+ error={errors.passportPage23}
+ />
+
+
+ set("passportPage89", f)}
+ placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
+ />
+
+
+ set("passportPage32", f)}
+ placeholder="Faýl saýlaň ýa-da salmak üçin basyň"
+ />
+
+
+
+ >
+ )}
+
+ {/* ── Form Actions ───────────────────────────────────────────────────── */}
+
navigate(-1)}
+ cancelLabel={t("Cancel") || "Ýatyr"}
+ loadingLabel={t("Loading") || "Ýüklenilýär..."}
+ // Prev button: visible from step 1 onward
+ onPrev={!isFirstStep ? handlePrev : undefined}
+ prevLabel={t("common.prev") || "Yza"}
+ // Next button: visible on all steps except the last
+ onNext={!isLastStep ? handleNext : undefined}
+ nextLabel={t("common.next") || "Indiki"}
+ // Submit button: only on the last step
+ showSubmit={isLastStep}
+ onSubmit={handleSubmit}
+ submitLabel={
+ mode === "create"
+ ? t("loanOrderMobiles.createButton") || "Karz sargyt döredüň"
+ : t("loanOrders.saveButton") || "Ýatda sakla"
+ }
+ />
- )
+ );
}
\ No newline at end of file
diff --git a/src/features/loanOrders/components/loanOrderForm.tsx b/src/features/loanOrders/components/loanOrderForm.tsx
index 19e302b..0676b37 100644
--- a/src/features/loanOrders/components/loanOrderForm.tsx
+++ b/src/features/loanOrders/components/loanOrderForm.tsx
@@ -2,17 +2,18 @@ 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 } from 'lucide-react'
-import { FormInput } from '@/components/formInput'
-import { Button } from '@/components/ui/button'
-import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
-import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
-import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
import {
CircleDot, CreditCard, MapPin, User, Wallet,
- FileText, Phone, Briefcase, FolderOpen, ShieldCheck
+ FileText, Phone, Briefcase, FolderOpen, ShieldCheck,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
+
+import { FormInput } from '@/components/formInput'
+import { FormActions } from '@/components/formActions'
+import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
+import { useCreateLoanOrder, useUpdateLoanOrder } from '@/features/loanOrders/hooks/useLoanOrders'
+import type { LoanOrder, LoanOrderPayload } from '@/features/loanOrders/api/loanOrdersApi'
+
// ─── Static options ───────────────────────────────────────────────────────────
const REGION_OPTIONS = [
@@ -36,11 +37,11 @@ const EDUCATION_OPTIONS = [
]
const MARRIAGE_OPTIONS = [
- { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' },
- { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' },
- { value: 'DIVORCED', label: 'Aýrylşan' },
- { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' },
- { value: 'LEGAL', label: 'Raýat nika' },
+ { value: 'MARRIED', label: 'Öýlenen / Durmuşa çykan' },
+ { value: 'SINGLE', label: 'Öýlenmedik / Durmuşa çykmadyk' },
+ { value: 'DIVORCED', label: 'Aýrylşan' },
+ { value: 'WIDOW', label: 'Adamsy ýa-da aýaly aradan çykan' },
+ { value: 'LEGAL', label: 'Raýat nika' },
]
const STATUS_OPTIONS = [
@@ -73,7 +74,7 @@ const YEAR_OPTIONS = Array.from({ length: 15 }, (_, i) => ({
label: String(new Date().getFullYear() + i),
}))
-// ─── Form State ───────────────────────────────────────────────────────────────
+// ─── FormState ────────────────────────────────────────────────────────────────
interface FormState {
status: string
@@ -130,55 +131,20 @@ interface FormState {
type FormErrors = Partial>
const INITIAL_STATE: FormState = {
- status: 'GARAŞYLÝAR',
- loanType: '',
- region: 'Aşgabat',
- branch: '',
- firstName: '',
- lastName: '',
- patronicName: '',
- education: '',
- marriageStatus: '',
- dateOfBirth: '',
- residence: '',
- currentResidence: '',
- passportSerie: '',
- passportNumber: '',
- passportDateOfIssue: '',
- passportGivenBy: '',
- bornPlace: '',
- email: '',
- phone: '',
- phoneAdditional: '',
- homePhone: '',
- workCompany: '',
- workHrPhone: '',
- workRegion: 'Aşgabat',
- workProvince: '',
- position: '',
- salary: '',
- workStartedAt: '',
- passportPage1: null,
- passportPage23: null,
- passportPage89: null,
- passportPage32: null,
- note: '',
- loanAmount: '',
- loanHistory: '',
- cardNumber: '',
- cardName: '',
- cardExpMonth: '',
- cardExpYear: '',
- guarantor1Name: '',
- guarantor1Surname: '',
- guarantor1Patronic: '',
- guarantor1PassportSerie: '',
- guarantor1PassportNumber: '',
- guarantor1CardNumber: '',
- guarantor1CardName: '',
- guarantor1CardExpMonth: '',
- guarantor1CardExpYear: '',
- guarantor1Salary: '',
+ status: 'GARAŞYLÝAR', loanType: '', region: 'Aşgabat', branch: '',
+ firstName: '', lastName: '', patronicName: '', education: '',
+ marriageStatus: '', dateOfBirth: '', residence: '', currentResidence: '',
+ passportSerie: '', passportNumber: '', passportDateOfIssue: '',
+ passportGivenBy: '', bornPlace: '', email: '', phone: '',
+ phoneAdditional: '', homePhone: '', workCompany: '', workHrPhone: '',
+ workRegion: 'Aşgabat', workProvince: '', position: '', salary: '',
+ workStartedAt: '', passportPage1: null, passportPage23: null,
+ passportPage89: null, passportPage32: null, note: '', loanAmount: '',
+ loanHistory: '', cardNumber: '', cardName: '', cardExpMonth: '', cardExpYear: '',
+ guarantor1Name: '', guarantor1Surname: '', guarantor1Patronic: '',
+ guarantor1PassportSerie: '', guarantor1PassportNumber: '',
+ guarantor1CardNumber: '', guarantor1CardName: '',
+ guarantor1CardExpMonth: '', guarantor1CardExpYear: '', guarantor1Salary: '',
}
function mapToFormState(order: LoanOrder): FormState {
@@ -211,15 +177,13 @@ function mapToFormState(order: LoanOrder): FormState {
position: order.position ?? '',
salary: order.salary != null ? String(order.salary) : '',
workStartedAt: order.workStartedAt ?? '',
- passportPage1: null,
- passportPage23: null,
- passportPage89: null,
- passportPage32: null,
- note: order.note ?? '',
+ passportPage1: null, passportPage23: null,
+ passportPage89: null, passportPage32: null,
+ note: order.note ?? '',
loanAmount: order.loanAmount != null ? String(order.loanAmount) : '',
loanHistory: order.loanHistory ?? '',
- cardNumber: order.cardNumber ?? '',
- cardName: order.cardName ?? '',
+ cardNumber: order.cardNumber ?? '',
+ cardName: order.cardName ?? '',
cardExpMonth: order.cardExpMonth ?? '',
cardExpYear: order.cardExpYear ?? '',
guarantor1Name: order.guarantor1Name ?? '',
@@ -241,29 +205,20 @@ interface StepDef {
id: string
titleKey: string
titleFallback: string
- shortLabel: string
- icon: LucideIcon
subtitle: string
+ icon: LucideIcon
validate: (form: FormState, mode: 'create' | 'edit') => FormErrors
}
-// 3. STEPS dizisini güncelle
+
const STEPS: StepDef[] = [
{
- id: 'status',
- titleKey: 'Status',
- titleFallback: 'Status',
- shortLabel: 'Status',
- icon: CircleDot,
- subtitle: 'Ýagdaý we bellik',
+ id: 'status', titleKey: 'Status', titleFallback: 'Status',
+ subtitle: 'Ýagdaý we bellik', icon: CircleDot,
validate: () => ({}),
},
{
- id: 'loan',
- titleKey: 'Loan',
- titleFallback: 'Karz',
- shortLabel: 'Karz',
- icon: Wallet,
- subtitle: 'Görnüş we möçber',
+ id: 'loan', titleKey: 'Loan', titleFallback: 'Karz',
+ subtitle: 'Görnüş we möçber', icon: Wallet,
validate: (form) => {
const e: FormErrors = {}
if (!form.loanType) e.loanType = 'Karz görnüşi — hökmany'
@@ -272,12 +227,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'location',
- titleKey: 'Location',
- titleFallback: 'Lokasiýa',
- shortLabel: 'Lokasiýa',
- icon: MapPin,
- subtitle: 'Welaýat we şahamça',
+ id: 'location', titleKey: 'Location', titleFallback: 'Lokasiýa',
+ subtitle: 'Welaýat we şahamça', icon: MapPin,
validate: (form) => {
const e: FormErrors = {}
if (!form.region) e.region = 'Welaýat — hökmany'
@@ -286,12 +237,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'personal',
- titleKey: 'Personal data',
- titleFallback: 'Şahsy maglumatlar',
- shortLabel: 'Şahsy',
- icon: User,
- subtitle: 'At, bilim, maşgala',
+ id: 'personal', titleKey: 'Personal data', titleFallback: 'Şahsy maglumatlar',
+ subtitle: 'At, bilim, maşgala', icon: User,
validate: (form) => {
const e: FormErrors = {}
if (!form.firstName) e.firstName = 'Ady — hökmany'
@@ -304,12 +251,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'card',
- titleKey: 'Card (Salary)',
- titleFallback: 'Kart (Zähmet haky)',
- shortLabel: 'Kart',
- icon: CreditCard,
- subtitle: 'Zähmet haky karty',
+ id: 'card', titleKey: 'Card (Salary)', titleFallback: 'Kart (Zähmet haky)',
+ subtitle: 'Zähmet haky karty', icon: CreditCard,
validate: (form) => {
const e: FormErrors = {}
if (!form.cardNumber) e.cardNumber = 'Kart belgisi — hökmany'
@@ -320,12 +263,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'passport',
- titleKey: 'Passport',
- titleFallback: 'Pasport',
- shortLabel: 'Pasport',
- icon: FileText,
- subtitle: 'Seriýa, belgisi, senesi',
+ id: 'passport', titleKey: 'Passport', titleFallback: 'Pasport',
+ subtitle: 'Seriýa, belgisi, senesi', icon: FileText,
validate: (form) => {
const e: FormErrors = {}
if (!form.passportSerie) e.passportSerie = 'Pasport seriýasy — hökmany'
@@ -336,12 +275,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'contact',
- titleKey: 'Contact data',
- titleFallback: 'Habarlaşmak',
- shortLabel: 'Habarlaşmak',
- icon: Phone,
- subtitle: 'Telefon we e-poçta',
+ id: 'contact', titleKey: 'Contact data', titleFallback: 'Habarlaşmak',
+ subtitle: 'Telefon we e-poçta', icon: Phone,
validate: (form) => {
const e: FormErrors = {}
if (!form.phone) {
@@ -353,12 +288,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'job',
- titleKey: 'Job',
- titleFallback: 'Iş',
- shortLabel: 'Iş',
- icon: Briefcase,
- subtitle: 'Kärhana we wezipe',
+ id: 'job', titleKey: 'Job', titleFallback: 'Iş',
+ subtitle: 'Kärhana we wezipe', icon: Briefcase,
validate: (form) => {
const e: FormErrors = {}
if (!form.workCompany) e.workCompany = 'Kärhananyň ady — hökmany'
@@ -369,12 +300,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'files',
- titleKey: 'Passport files',
- titleFallback: 'Pasport faýllar',
- shortLabel: 'Faýllar',
- icon: FolderOpen,
- subtitle: 'Pasport suratlary',
+ id: 'files', titleKey: 'Passport files', titleFallback: 'Pasport faýllar',
+ subtitle: 'Pasport suratlary', icon: FolderOpen,
validate: (form, mode) => {
const e: FormErrors = {}
if (mode === 'create') {
@@ -385,12 +312,8 @@ const STEPS: StepDef[] = [
},
},
{
- id: 'guarantor',
- titleKey: '1. Guarantor',
- titleFallback: '1. Zamun',
- shortLabel: 'Zamun',
- icon: ShieldCheck,
- subtitle: 'Zamun maglumatlary',
+ id: 'guarantor', titleKey: '1. Guarantor', titleFallback: '1. Zamun',
+ subtitle: 'Zamun maglumatlary', icon: ShieldCheck,
validate: (form) => {
const e: FormErrors = {}
if (!form.guarantor1Name) e.guarantor1Name = 'Zamunyň ady — hökmany'
@@ -407,184 +330,408 @@ const STEPS: StepDef[] = [
},
]
-// ─── Step content renderers ───────────────────────────────────────────────────
+// ─── Bento primitives ─────────────────────────────────────────────────────────
+
+function BentoGrid({
+ cols = 2,
+ children,
+}: {
+ cols?: 1 | 2 | 3 | 4
+ children: React.ReactNode
+}) {
+ const colClass = {
+ 1: 'grid-cols-1',
+ 2: 'grid-cols-1 sm:grid-cols-2',
+ 3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
+ 4: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-4',
+ }[cols]
+ return {children}
+}
+
+function BentoCard({
+ title,
+ span,
+ children,
+}: {
+ title?: string
+ span?: 'full' | 2 | 3
+ children: React.ReactNode
+}) {
+ const spanClass =
+ span === 'full' ? 'sm:col-span-full' :
+ span === 2 ? 'sm:col-span-2' :
+ span === 3 ? 'sm:col-span-3' : ''
+
+ return (
+
+ {title && (
+
+ {title}
+
+ )}
+ {children}
+
+ )
+}
+
+// ─── Shared step content props ────────────────────────────────────────────────
+
+interface StepContentProps {
+ form: FormState
+ errors: FormErrors
+ set: (k: K, v: FormState[K]) => void
+}
+
+// ─── Step panels ──────────────────────────────────────────────────────────────
function StepStatus({ form, errors, set }: StepContentProps) {
return (
-
-
- set('status', v)} options={STATUS_OPTIONS} error={errors.status} placeholder="Saýlaň" />
-
-
set('note', v)} placeholder="Bellik" />
-
+
+
+ set('status', v)}
+ options={STATUS_OPTIONS}
+ error={errors.status}
+ placeholder="Saýlaň"
+ />
+
+
+
+ set('note', v)}
+ placeholder="Bellik..."
+ rows={3}
+ />
+
+
)
}
function StepLoan({ form, errors, set }: StepContentProps) {
return (
-
- set('loanType', v)} options={LOAN_TYPE_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.loanType} />
- set('loanAmount', v)} placeholder="Karz möçberi" error={errors.loanAmount} />
-
+
+
+ set('loanType', v)}
+ options={LOAN_TYPE_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.loanType}
+ />
+
+
+
+ set('loanAmount', v)}
+ placeholder="0.00"
+ error={errors.loanAmount}
+ />
+
+
)
}
function StepLocation({ form, errors, set }: StepContentProps) {
return (
-
- set('region', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.region} />
- set('branch', v)} options={[]} placeholder="Saýlamak üçin basyň" error={errors.branch} />
-
+
+
+ { set('region', v); set('branch', '') }}
+ options={REGION_OPTIONS}
+ placeholder="Saýlamak üçin basyň"
+ error={errors.region}
+ />
+
+ Welaýaty saýlasaňyz şahamçalar güncellenar.
+
+
+
+
+ set('branch', v)}
+ options={[]}
+ placeholder="Saýlamak üçin basyň"
+ disabled={!form.region}
+ error={errors.branch}
+ />
+
+
)
}
function StepPersonal({ form, errors, set }: StepContentProps) {
return (
-
-
- set('firstName', v)} placeholder="Ady" error={errors.firstName} />
- set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} />
- set('patronicName', v)} placeholder="Atasynyň ady" />
-
-
- set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} />
- set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} />
- set('dateOfBirth', v)} error={errors.dateOfBirth} />
-
-
- set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} />
- set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
-
-
- set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" />
-
+
+
+
+ set('firstName', v)} placeholder="Ady" error={errors.firstName} />
+
+
+ set('lastName', v)} placeholder="Familiýasy" error={errors.lastName} />
+
+
+ set('patronicName', v)} placeholder="Atasynyň ady" />
+
+
+
+
+
+ set('education', v)} options={EDUCATION_OPTIONS} placeholder="Saýlaň" error={errors.education} />
+
+
+ set('marriageStatus', v)} options={MARRIAGE_OPTIONS} placeholder="Saýlaň" error={errors.marriageStatus} />
+
+
+ set('dateOfBirth', v)} error={errors.dateOfBirth} />
+
+
+
+
+
+ set('residence', v)} placeholder="Ýazgy edilen salgy" error={errors.residence} />
+
+
+ set('currentResidence', v)} placeholder="Häzirki ýaşaýyş ýeri" />
+
+
+ set('loanHistory', v)} options={[]} placeholder="Saýlamak üçin basyň" />
+
+
)
}
function StepCard({ form, errors, set }: StepContentProps) {
return (
-
- set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} />
- set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} />
- set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} />
- set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} />
-
+
+
+ set('cardNumber', v)} placeholder="Kart belgisi" error={errors.cardNumber} />
+ set('cardName', v)} placeholder="Kartdaky ady" error={errors.cardName} />
+
+
+
+ set('cardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpMonth} />
+ set('cardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.cardExpYear} />
+
+
)
}
function StepPassport({ form, errors, set }: StepContentProps) {
return (
-
-
- set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} />
- set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} />
- set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
-
-
- set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} />
- set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" />
-
+
+
+
+ set('passportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.passportSerie} />
+
+
+ set('passportNumber', v)} placeholder="Pasport belgisi" error={errors.passportNumber} />
+
+
+ set('passportDateOfIssue', v)} error={errors.passportDateOfIssue} />
+
+
+
+
+
+ set('passportGivenBy', v)} placeholder="Kim tarapyndan berildi" error={errors.passportGivenBy} />
+
+
+ set('bornPlace', v)} placeholder="Doglan ýeri (pasport)" />
+
+
)
}
function StepContact({ form, errors, set }: StepContentProps) {
return (
-
- set('email', v)} placeholder="E-poçta" />
- set('phone', v)} placeholder="61 097 651" error={errors.phone} />
- set('phoneAdditional', v)} placeholder="61 097 651" />
- set('homePhone', v)} placeholder="61 097 651" />
-
+
+
+ set('phone', v)} placeholder="61 097 651" error={errors.phone} />
+ set('email', v)} placeholder="E-poçta" />
+
+
+
+ set('phoneAdditional', v)} placeholder="61 097 651" />
+ set('homePhone', v)} placeholder="61 097 651" />
+
+
)
}
function StepJob({ form, errors, set }: StepContentProps) {
return (
-
-
- set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} />
- set('workHrPhone', v)} placeholder="61 097 651" />
-
-
- set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" />
- set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
-
-
- set('position', v)} placeholder="Wezipe" error={errors.position} />
- set('salary', v)} placeholder="Zähmet haky" error={errors.salary} />
- set('workStartedAt', v)} error={errors.workStartedAt} />
-
+
+
+
+ set('workCompany', v)} placeholder="Kärhananyň ady" error={errors.workCompany} />
+ set('workHrPhone', v)} placeholder="61 097 651" />
+
+
+
+ set('workRegion', v)} options={REGION_OPTIONS} placeholder="Saýlamak üçin basyň" />
+ set('workProvince', v)} options={[]} placeholder="Saýlamak üçin basyň" />
+
+
+
+
+
+ set('position', v)} placeholder="Wezipe" error={errors.position} />
+
+
+ set('salary', v)} placeholder="Zähmet haky" error={errors.salary} />
+
+
+ set('workStartedAt', v)} error={errors.workStartedAt} />
+
+
)
}
-function StepFiles({ form, errors, set, mode, initialData }: StepContentProps & { mode: 'create' | 'edit'; initialData?: LoanOrder }) {
+function StepFiles({
+ form, errors, set, mode, initialData,
+}: StepContentProps & { mode: 'create' | 'edit'; initialData?: LoanOrder }) {
+ const existingFiles = mode === 'edit' && initialData
+ ? [
+ { url: initialData.passportPage1Url, label: 'Pasport (sahypa 1)' },
+ { url: initialData.passportPage23Url, label: 'Pasport (2-3-nji sahypa)' },
+ { url: initialData.passportPage89Url, label: 'Pasport (8-9 sahypa)' },
+ { url: initialData.passportPage32Url, label: 'Pasport (32-nji sahypa)' },
+ ].filter((f): f is { url: string; label: string } => !!f.url)
+ : []
+
return (
-
- {mode === 'edit' && initialData && (
-
- {(
- [
- { url: initialData.passportPage1Url, label: 'Pasport (sahypa 1)' },
- { url: initialData.passportPage23Url, label: 'Pasport (2-3-nji sahypa)' },
- { url: initialData.passportPage89Url, label: 'Pasport (8-9 sahypa)' },
- { url: initialData.passportPage32Url, label: 'Pasport (32-nji sahypa)' },
- ] as { url?: string; label: string }[]
- ).map(({ url, label }) =>
- url ? (
-
- ) : null
- )}
-
+
+ {existingFiles.length > 0 && (
+
+ {existingFiles.map(({ url, label }) => (
+
+
+ Faýly gör
+
+
+ ))}
+
)}
-
- set('passportPage1', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage1} />
- set('passportPage23', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" error={errors.passportPage23} />
- set('passportPage89', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" />
- set('passportPage32', f)} placeholder="Faýl saýlaň ýa-da salmak üçin basyň" />
-
+
+
+
+ set('passportPage1', f)}
+ error={errors.passportPage1}
+ />
+
+
+
+ set('passportPage23', f)}
+ error={errors.passportPage23}
+ />
+
+
+
+ set('passportPage89', f)}
+ />
+
+
+
+ set('passportPage32', f)}
+ />
+
+
)
}
function StepGuarantor({ form, errors, set }: StepContentProps) {
return (
-
-
- set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} />
- set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} />
- set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
-
-
- set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} />
- set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
-
-
- set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} />
- set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
- set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} />
- set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
-
-
- set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} />
-
+
+
+
+ set('guarantor1Name', v)} placeholder="Zamunyň ady" error={errors.guarantor1Name} />
+
+
+ set('guarantor1Surname', v)} placeholder="Zamunyň familiýasy" error={errors.guarantor1Surname} />
+
+
+ set('guarantor1Patronic', v)} placeholder="Zamunyň atasynyň ady" />
+
+
+
+
+
+ set('guarantor1PassportSerie', v)} options={PASSPORT_SERIES_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1PassportSerie} />
+
+
+ set('guarantor1PassportNumber', v)} placeholder="Pasport belgisi" error={errors.guarantor1PassportNumber} />
+
+
+
+
+
+ set('guarantor1CardNumber', v)} placeholder="Kart belgisi" error={errors.guarantor1CardNumber} />
+ set('guarantor1CardName', v)} placeholder="Kartdaky ady" error={errors.guarantor1CardName} />
+
+
+
+ set('guarantor1CardExpMonth', v)} options={MONTH_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpMonth} />
+ set('guarantor1CardExpYear', v)} options={YEAR_OPTIONS} placeholder="Saýlamak üçin basyň" error={errors.guarantor1CardExpYear} />
+ set('guarantor1Salary', v)} placeholder="Ortaca zähmet haky" error={errors.guarantor1Salary} />
+
+
)
}
-// ─── Shared step content prop type ───────────────────────────────────────────
-
-interface StepContentProps {
- form: FormState
- errors: FormErrors
- set:
(k: K, v: FormState[K]) => void
-}
-
// ─── Props ────────────────────────────────────────────────────────────────────
interface LoanOrderFormProps {
@@ -606,17 +753,10 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
const [form, setForm] = useState(() => initialData ? mapToFormState(initialData) : INITIAL_STATE)
const [errors, setErrors] = useState({})
const [currentStep, setCurrentStep] = useState(0)
-
- /**
- * `visited`: steps the user has explicitly moved away from (via Next or direct nav).
- * Used to mark steps as "done" or "error" in the step bar.
- * In edit mode all steps start visited so errors show immediately on submit.
- */
const [visited, setVisited] = useState>(
- () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set()
+ () => mode === 'edit' ? new Set(STEPS.map((_, i) => i)) : new Set(),
)
- /** Steps with at least one error (evaluated lazily — only after being visited). */
const stepsWithErrors = useMemo(() => {
const out = new Set()
visited.forEach((i) => {
@@ -671,7 +811,6 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
// ── Submit ──────────────────────────────────────────────────────────────────
const handleSubmit = () => {
- // Mark all steps visited so error states show in the bar
setVisited(new Set(STEPS.map((_, i) => i)))
const allErrors: FormErrors = {}
@@ -682,8 +821,7 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
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, mode)).length > 0) {
- setCurrentStep(i)
- break
+ setCurrentStep(i); break
}
}
return
@@ -696,35 +834,35 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
branch: form.branch,
firstName: form.firstName,
lastName: form.lastName,
- patronicName: form.patronicName || undefined,
+ patronicName: form.patronicName || undefined,
education: form.education,
marriageStatus: form.marriageStatus,
dateOfBirth: form.dateOfBirth,
residence: form.residence,
- currentResidence: form.currentResidence || undefined,
+ currentResidence: form.currentResidence || undefined,
passportSerie: form.passportSerie,
passportNumber: form.passportNumber,
passportDateOfIssue: form.passportDateOfIssue,
passportGivenBy: form.passportGivenBy,
- bornPlace: form.bornPlace || undefined,
- email: form.email || undefined,
+ bornPlace: form.bornPlace || undefined,
+ email: form.email || undefined,
phone: form.phone,
- phoneAdditional: form.phoneAdditional || undefined,
- homePhone: form.homePhone || undefined,
+ phoneAdditional: form.phoneAdditional || undefined,
+ homePhone: form.homePhone || undefined,
workCompany: form.workCompany,
- workHrPhone: form.workHrPhone || undefined,
- workRegion: form.workRegion || undefined,
- workProvince: form.workProvince || undefined,
+ workHrPhone: form.workHrPhone || undefined,
+ workRegion: form.workRegion || undefined,
+ workProvince: form.workProvince || undefined,
position: form.position,
salary: Number(form.salary),
workStartedAt: form.workStartedAt,
- note: form.note || undefined,
- loanAmount: Number(form.loanAmount) || undefined,
- loanHistory: form.loanHistory || undefined,
- cardNumber: form.cardNumber || undefined,
- cardName: form.cardName || undefined,
- cardExpMonth: form.cardExpMonth || undefined,
- cardExpYear: form.cardExpYear || undefined,
+ note: form.note || undefined,
+ loanAmount: Number(form.loanAmount) || undefined,
+ loanHistory: form.loanHistory || undefined,
+ cardNumber: form.cardNumber || undefined,
+ cardName: form.cardName || undefined,
+ cardExpMonth: form.cardExpMonth || undefined,
+ cardExpYear: form.cardExpYear || undefined,
guarantor1Name: form.guarantor1Name || undefined,
guarantor1Surname: form.guarantor1Surname || undefined,
guarantor1Patronic: form.guarantor1Patronic || undefined,
@@ -740,114 +878,91 @@ export function LoanOrderForm({ mode, initialData, loanOrderId }: LoanOrderFormP
if (mode === 'create') {
createMutation.mutate(payload, { onSuccess: () => navigate('/loan-orders') })
} else {
- updateMutation.mutate({ id: loanOrderId!, payload }, { onSuccess: () => navigate('/loan-orders') })
+ updateMutation.mutate(
+ { id: loanOrderId!, payload },
+ { onSuccess: () => navigate('/loan-orders') },
+ )
}
}
// ── StepBar items ───────────────────────────────────────────────────────────
- // 4. stepBarItems'i StepCardItem[] olarak oluştur
-const stepBarItems: StepCardItem[] = STEPS.map((s, i) => {
- const isActive = i === currentStep
- const hasErrors = stepsWithErrors.has(i)
- const isDone = visited.has(i) && !hasErrors
+ 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',
+ }
+ })
- 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
+ const isLastStep = currentStep === STEPS.length - 1
// ── Render ──────────────────────────────────────────────────────────────────
return (
{/* Page header */}
-
+
- {mode === 'create' ? (t('Loan order create') || 'Karz sargyt döredüň') : (t('Loan order edit') || 'Karz sargydy üýtget')}
+ {mode === 'create'
+ ? (t('Loan order create') || 'Karz sargyt döredüň')
+ : (t('Loan order edit') || 'Karz sargydy üýtget')}
-
+
{t('Fill in all sections step by step') || 'Ähli meýdanlary dolduryp, ädim-ädim öň geçiň.'}
- {/* Horizontal step bar — sits above the form card */}
-
-
- {/* Form card */}
-
- {/* Card header */}
-
-
- {currentStep + 1} / {STEPS.length}
-
-
- {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
-
-
-
- {/* Card body */}
-
- {currentStep === 0 && }
- {currentStep === 1 && }
- {currentStep === 2 && }
- {currentStep === 3 && }
- {currentStep === 4 && }
- {currentStep === 5 && }
- {currentStep === 6 && }
- {currentStep === 7 && }
- {currentStep === 8 && }
- {currentStep === 9 && }
-
-
- {/* Card footer */}
-
-
-
- {isLastStep ? (
-
- ) : (
-
- )}
-
+ {/* Step bar */}
+
+
+
+ {/* Step label */}
+
+
+ {currentStep + 1} / {STEPS.length}
+
+
+ {t(STEPS[currentStep].titleKey) || STEPS[currentStep].titleFallback}
+
+
+
+ {/* Step content */}
+ {currentStep === 0 &&
}
+ {currentStep === 1 &&
}
+ {currentStep === 2 &&
}
+ {currentStep === 3 &&
}
+ {currentStep === 4 &&
}
+ {currentStep === 5 &&
}
+ {currentStep === 6 &&
}
+ {currentStep === 7 &&
}
+ {currentStep === 8 &&
}
+ {currentStep === 9 &&
}
+
+ {/* Actions */}
+
navigate(-1) : undefined}
+ onPrev={currentStep > 0 ? handleBack : undefined}
+ onNext={!isLastStep ? handleNext : undefined}
+ showSubmit={isLastStep}
+ onSubmit={isLastStep ? handleSubmit : undefined}
+ submitLabel={
+ mode === 'create'
+ ? (t('loanOrderMobiles.createButton') || 'Karz sargyt döredüň')
+ : (t('loanOrders.saveButton') || 'Ýatda sakla')
+ }
+ loadingLabel={t('Loading') || 'Ýüklenilýär...'}
+ cancelLabel={t('Cancel') || 'Ýatyr'}
+ prevLabel={t('Back') || 'Yza'}
+ nextLabel={t('Next') || 'Indiki'}
+ />
)
}
\ No newline at end of file
diff --git a/src/features/loanRemaining/components/LoanRemainingForm.tsx b/src/features/loanRemaining/components/LoanRemainingForm.tsx
index 4de7572..3c297e6 100644
--- a/src/features/loanRemaining/components/LoanRemainingForm.tsx
+++ b/src/features/loanRemaining/components/LoanRemainingForm.tsx
@@ -1,11 +1,10 @@
import { useState, useEffect, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
-import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
-import { Button } from '@/components/ui/button'
import { FormInput } from '@/components/formInput'
+import { FormActions } from '@/components/formActions'
import {
useCreateLoanRemaining,
@@ -99,8 +98,8 @@ export function LoanRemainingForm({
return Object.keys(newErrors).length === 0
}
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault()
+ const handleSubmit = (e?: React.FormEvent) => {
+ e?.preventDefault()
setSubmitted(true)
if (!validate()) {
@@ -168,22 +167,14 @@ export function LoanRemainingForm({
-
-
-
-
+ navigate('/loan-remaining')}
+ submitLabel={mode === 'create'
+ ? t('common.create', 'Döret')
+ : t('common.save', 'Ýatda sakla')}
+ />
)
}
diff --git a/src/features/loanTypes/components/loanTypesForm.tsx b/src/features/loanTypes/components/loanTypesForm.tsx
index fbd3b19..5d8f313 100644
--- a/src/features/loanTypes/components/loanTypesForm.tsx
+++ b/src/features/loanTypes/components/loanTypesForm.tsx
@@ -4,8 +4,8 @@ import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
-import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
+import { FormActions } from '@/components/formActions'
import { Checkbox } from '@/components/ui/checkbox'
import { useCreateLoanType, useUpdateLoanType } from '../hooks/useLoanTypes'
import type { LoanType, CreateLoanTypePayload } from '../api/loanTypesApi'
@@ -241,28 +241,16 @@ export function LoanTypeForm({ mode, initialData, loanTypeId }: LoanTypeFormProp
- {/* Actions */}
-
-
-
-
+
)
}
\ No newline at end of file
diff --git a/src/features/operators/components/operatorForms.tsx b/src/features/operators/components/operatorForms.tsx
index 835e886..ef1d9c8 100644
--- a/src/features/operators/components/operatorForms.tsx
+++ b/src/features/operators/components/operatorForms.tsx
@@ -1,8 +1,8 @@
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 { FormActions } from '@/components/formActions'
import { FormInput } from '@/components/formInput'
import { useCreateOperator, useUpdateOperator } from '../hooks/useOperators'
import type { Operator, CreateOperatorPayload, UpdateOperatorPayload } from '../api/operatorsApi'
@@ -225,29 +225,16 @@ export function OperatorForm({ mode, initialData, operatorId }: OperatorFormProp
/>
- {/* Actions */}
-
-
-
-
+
navigate(-1)}
+ cancelVariant="ghost"
+ submitLabel={mode === 'create'
+ ? t('operators.createBtn', 'Operator döredin')
+ : t('operators.updateBtn', 'Üýtgetmeleri sakla')}
+ className="px-6 py-4 border-t border-border bg-muted/20"
+ />
)
}
\ No newline at end of file
diff --git a/src/features/orderNewCard/components/orderNewCardForm.tsx b/src/features/orderNewCard/components/orderNewCardForm.tsx
index 7b13dd9..6115608 100644
--- a/src/features/orderNewCard/components/orderNewCardForm.tsx
+++ b/src/features/orderNewCard/components/orderNewCardForm.tsx
@@ -1,7 +1,10 @@
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { CreditCard, User, FileText, Upload } from 'lucide-react'
import { FormInput } from '@/components/formInput'
-import { Button } from '@/components/ui/button'
+import { FormActions } from '@/components/formActions'
+import { StepBarCards, type StepCardItem } from '@/components/stepBarV2'
import type { SelectOption } from '@/components/formInput'
import type {
CardOrder,
@@ -31,12 +34,10 @@ interface FormState {
isPaid: boolean
status: CardOrderStatus | ''
note: string
-
issuanceReasonId: string
cardTypeId: string
provinceId: string
branchId: string
-
firstName: string
lastName: string
middleName: string
@@ -48,107 +49,135 @@ interface FormState {
registeredAddress: string
currentAddress: string
workplace: string
-
passportSeriesId: string
passportNumber: string
passportIssueDate: string
passportIssuedBy: string
passportBirthPlace: string
-
passportPage1: File | null
passportPage23: File | null
passportPage89: File | null
passportPage32: File | null
-
termsAccepted: boolean
}
type FormErrors = Partial>
+type StepStatus = 'idle' | 'active' | 'done' | 'error'
+
+// ─── Step field mapping ───────────────────────────────────────────────────────
+
+const STEP_FIELDS: Array> = [
+ // Step 0 — Kart & Lokasiýa
+ ['status', 'issuanceReasonId', 'cardTypeId', 'provinceId', 'branchId'],
+ // Step 1 — Şahsy maglumatlar
+ [
+ 'firstName', 'lastName', 'birthDate', 'phone',
+ 'citizenship', 'registeredAddress', 'currentAddress', 'workplace',
+ ],
+ // Step 2 — Pasport
+ [
+ 'passportSeriesId', 'passportNumber', 'passportIssueDate',
+ 'passportIssuedBy', 'passportBirthPlace',
+ ],
+ // Step 3 — Faýllar & Şertler
+ ['passportPage1', 'passportPage23', 'passportPage89', 'passportPage32', 'termsAccepted'],
+]
// ─── Initial state ────────────────────────────────────────────────────────────
function getInitialState(data?: CardOrder): FormState {
return {
- isPaid: data?.isPaid ?? false,
- status: data?.status ?? '',
- note: data?.note ?? '',
-
- issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '',
- cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '',
- provinceId: data?.provinceId ? String(data.provinceId) : '',
- branchId: data?.branchId ? String(data.branchId) : '',
-
- firstName: data?.firstName ?? '',
- lastName: data?.lastName ?? '',
- middleName: data?.middleName ?? '',
- formerLastName: data?.formerLastName ?? '',
- birthDate: data?.birthDate ?? '',
- phone: data?.phone ?? '',
- phoneExtra: data?.phoneExtra ?? '',
- citizenship: data?.citizenship ?? 'Turkmenistan',
- registeredAddress: data?.registeredAddress ?? '',
- currentAddress: data?.currentAddress ?? '',
- workplace: data?.workplace ?? '',
-
- passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '',
- passportNumber: data?.passportNumber ?? '',
- passportIssueDate: data?.passportIssueDate ?? '',
- passportIssuedBy: data?.passportIssuedBy ?? '',
- passportBirthPlace:data?.passportBirthPlace?? '',
-
+ isPaid: data?.isPaid ?? false,
+ status: data?.status ?? '',
+ note: data?.note ?? '',
+ issuanceReasonId: data?.issuanceReasonId ? String(data.issuanceReasonId) : '',
+ cardTypeId: data?.cardTypeId ? String(data.cardTypeId) : '',
+ provinceId: data?.provinceId ? String(data.provinceId) : '',
+ branchId: data?.branchId ? String(data.branchId) : '',
+ firstName: data?.firstName ?? '',
+ lastName: data?.lastName ?? '',
+ middleName: data?.middleName ?? '',
+ formerLastName: data?.formerLastName ?? '',
+ birthDate: data?.birthDate ?? '',
+ phone: data?.phone ?? '',
+ phoneExtra: data?.phoneExtra ?? '',
+ citizenship: data?.citizenship ?? 'Turkmenistan',
+ registeredAddress: data?.registeredAddress ?? '',
+ currentAddress: data?.currentAddress ?? '',
+ workplace: data?.workplace ?? '',
+ passportSeriesId: data?.passportSeriesId ? String(data.passportSeriesId) : '',
+ passportNumber: data?.passportNumber ?? '',
+ passportIssueDate: data?.passportIssueDate ?? '',
+ passportIssuedBy: data?.passportIssuedBy ?? '',
+ passportBirthPlace: data?.passportBirthPlace ?? '',
passportPage1: null,
passportPage23: null,
passportPage89: null,
passportPage32: null,
-
termsAccepted: false,
}
}
// ─── Validation ───────────────────────────────────────────────────────────────
-function validate(form: FormState, mode: 'create' | 'edit', t: (k: string, fb: string) => string): FormErrors {
- const errors: FormErrors = {}
+function validate(
+ form: FormState,
+ mode: 'create' | 'edit',
+ t: (k: string, fb: string) => string,
+ stepIndex?: number,
+): FormErrors {
+ const allErrors: FormErrors = {}
const req = (field: keyof FormState, msg: string) => {
const v = form[field]
- if (!v || (typeof v === 'string' && !v.trim())) errors[field] = msg
+ if (!v || (typeof v === 'string' && !v.trim())) allErrors[field] = msg
}
- req('status', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('issuanceReasonId', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('cardTypeId', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('provinceId', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('branchId', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('firstName', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('lastName', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('birthDate', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('phone', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('citizenship', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('registeredAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('currentAddress', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('workplace', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('passportSeriesId', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('passportNumber', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('passportIssueDate', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('passportIssuedBy', t('validation.required', 'Bu meýdan hökmanydyr'))
- req('passportBirthPlace',t('validation.required', 'Bu meýdan hökmanydyr'))
+ const R = t('validation.required', 'Bu meýdan hökmanydyr')
+
+ req('status', R)
+ req('issuanceReasonId', R)
+ req('cardTypeId', R)
+ req('provinceId', R)
+ req('branchId', R)
+ req('firstName', R)
+ req('lastName', R)
+ req('birthDate', R)
+ req('phone', R)
+ req('citizenship', R)
+ req('registeredAddress', R)
+ req('currentAddress', R)
+ req('workplace', R)
+ req('passportSeriesId', R)
+ req('passportNumber', R)
+ req('passportIssueDate', R)
+ req('passportIssuedBy', R)
+ req('passportBirthPlace', R)
if (mode === 'create') {
- if (!form.passportPage1) errors.passportPage1 = t('validation.required', 'Bu meýdan hökmanydyr')
- if (!form.passportPage23) errors.passportPage23 = t('validation.required', 'Bu meýdan hökmanydyr')
- if (!form.passportPage89) errors.passportPage89 = t('validation.required', 'Bu meýdan hökmanydyr')
- if (!form.passportPage32) errors.passportPage32 = t('validation.required', 'Bu meýdan hökmanydyr')
- if (!form.termsAccepted) errors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly')
+ if (!form.passportPage1) allErrors.passportPage1 = R
+ if (!form.passportPage23) allErrors.passportPage23 = R
+ if (!form.passportPage89) allErrors.passportPage89 = R
+ if (!form.passportPage32) allErrors.passportPage32 = R
+ if (!form.termsAccepted) allErrors.termsAccepted = t('validation.terms', 'Şertnama bilen razylaşmaly')
}
- return errors
+ if (stepIndex !== undefined) {
+ const stepKeys = STEP_FIELDS[stepIndex]
+ const stepErrors: FormErrors = {}
+ for (const key of stepKeys) {
+ if (allErrors[key]) stepErrors[key] = allErrors[key]
+ }
+ return stepErrors
+ }
+
+ return allErrors
}
// ─── Section wrapper ──────────────────────────────────────────────────────────
function FormSection({ title, children }: { title?: string; children: React.ReactNode }) {
return (
-
+
{title && (
{title}
)}
@@ -171,20 +200,22 @@ export function CardOrderForm({
const { t } = useTranslation()
const isEdit = mode === 'edit'
- const [form, setForm] = useState
(() => getInitialState(initialData))
- const [errors, setErrors] = useState({})
- const [touched, setTouched] = useState(false)
+ const [form, setForm] = useState(() => getInitialState(initialData))
+ const [errors, setErrors] = useState({})
+ const [currentStep, setCurrentStep] = useState(0)
+ const [stepStatuses, setStepStatuses] = useState([
+ 'active', 'idle', 'idle', 'idle',
+ ])
- // Reset form when initialData loads (edit mode)
useEffect(() => {
if (initialData) setForm(getInitialState(initialData))
}, [initialData])
// Lookup data
- const { data: reasons = [] } = useCardIssuanceReasons()
- const { data: cardTypes = [] } = useCardTypes()
- const { data: provinces = [] } = useProvinces()
- const { data: branches = [] } = useBranches(
+ const { data: reasons = [] } = useCardIssuanceReasons()
+ const { data: cardTypes = [] } = useCardTypes()
+ const { data: provinces = [] } = useProvinces()
+ const { data: branches = [] } = useBranches(
form.provinceId ? Number(form.provinceId) : undefined,
)
@@ -195,26 +226,77 @@ export function CardOrderForm({
// Helpers
const set = (key: keyof FormState) => (value: string) =>
- setForm((f) => ({ ...f, [key]: value }))
+ setForm((f) => {
+ const next = { ...f, [key]: value }
+ setErrors((prev) => ({ ...prev, [key]: undefined }))
+ return next
+ })
- const setFile = (key: keyof FormState) => (file: File | null) =>
+ const setFile = (key: keyof FormState) => (file: File | null) => {
setForm((f) => ({ ...f, [key]: file }))
+ setErrors((prev) => ({ ...prev, [key]: undefined }))
+ }
const toOptions = (arr: { id: number; name: string }[]): SelectOption[] =>
arr.map((x) => ({ value: String(x.id), label: x.name }))
- // Validate on every change if user has already submitted once
- useEffect(() => {
- if (touched) setErrors(validate(form, mode, t))
- }, [form, touched, mode])
+ // ── Step navigation ────────────────────────────────────────────────────────
+
+ const updateStatus = (index: number, status: StepStatus) => {
+ setStepStatuses((prev) => {
+ const next = [...prev]
+ next[index] = status
+ return next
+ })
+ }
+
+ const goToStep = (index: number) => {
+ updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'done')
+ updateStatus(index, 'active')
+ setCurrentStep(index)
+ window.scrollTo({ top: 0, behavior: 'smooth' })
+ }
+
+ const handleNext = () => {
+ const stepErrors = validate(form, mode, t, currentStep)
+ if (Object.keys(stepErrors).length > 0) {
+ setErrors((prev) => ({ ...prev, ...stepErrors }))
+ updateStatus(currentStep, 'error')
+ toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
+ const firstKey = Object.keys(stepErrors)[0]
+ document.getElementById(`field-${firstKey}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ return
+ }
+ updateStatus(currentStep, 'done')
+ const next = currentStep + 1
+ updateStatus(next, 'active')
+ setCurrentStep(next)
+ window.scrollTo({ top: 0, behavior: 'smooth' })
+ }
+
+ const handlePrev = () => {
+ const prev = currentStep - 1
+ updateStatus(currentStep, stepStatuses[currentStep] === 'error' ? 'error' : 'idle')
+ updateStatus(prev, 'active')
+ setCurrentStep(prev)
+ window.scrollTo({ top: 0, behavior: 'smooth' })
+ }
// ── Submit ─────────────────────────────────────────────────────────────────
const handleSubmit = async () => {
- setTouched(true)
- const errs = validate(form, mode, t)
- if (Object.keys(errs).length > 0) {
- setErrors(errs)
+ const allErrors = validate(form, mode, t)
+ if (Object.keys(allErrors).length > 0) {
+ setErrors(allErrors)
+ const newStatuses = stepStatuses.map((s, i) => {
+ const stepKeys = STEP_FIELDS[i]
+ const hasError = stepKeys.some((k) => allErrors[k])
+ if (i === currentStep) return hasError ? 'error' : 'active'
+ if (hasError) return 'error'
+ return s === 'idle' ? 'idle' : 'done'
+ }) as StepStatus[]
+ setStepStatuses(newStatuses)
+ toast.error(t('validation.fixErrors', 'Dogry maglumat girizmegiňizi haýyş edýäris.'))
return
}
@@ -228,7 +310,7 @@ export function CardOrderForm({
branchId: Number(form.branchId),
firstName: form.firstName,
lastName: form.lastName,
- middleName: form.middleName || null,
+ middleName: form.middleName || null,
formerLastName: form.formerLastName || null,
birthDate: form.birthDate,
phone: form.phone,
@@ -260,7 +342,7 @@ export function CardOrderForm({
}
}
- // ── Status options ─────────────────────────────────────────────────────────
+ // ── Options ────────────────────────────────────────────────────────────────
const statusOptions: SelectOption[] = [
{ value: 'PENDING', label: t('cardOrder.status.pending', 'Garaşylýar') },
@@ -269,351 +351,457 @@ export function CardOrderForm({
]
const citizenshipOptions: SelectOption[] = [
- { value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') },
- { value: 'Russia', label: t('citizenship.ru', 'Russiýa') },
+ { value: 'Turkmenistan', label: t('citizenship.tm', 'Turkmenistan') },
+ { value: 'Russia', label: t('citizenship.ru', 'Russiýa') },
{ value: 'Other', label: t('citizenship.other', 'Beýlekiler') },
]
+ // ── Step bar items ─────────────────────────────────────────────────────────
+
+ const stepDefs = [
+ {
+ id: 'card',
+ title: t('cardOrder.step.card', 'Kart'),
+ subtitle: t('cardOrder.step.cardSub', 'Görnüş & lokasiýa'),
+ icon: CreditCard,
+ },
+ {
+ id: 'personal',
+ title: t('cardOrder.step.personal', 'Şahsy'),
+ subtitle: t('cardOrder.step.personalSub', 'Maglumatlar'),
+ icon: User,
+ },
+ {
+ id: 'passport',
+ title: t('cardOrder.step.passport', 'Pasport'),
+ subtitle: t('cardOrder.step.passportSub', 'Resmi maglumat'),
+ icon: FileText,
+ },
+ {
+ id: 'files',
+ title: t('cardOrder.step.files', 'Faýllar'),
+ subtitle: t('cardOrder.step.filesSub', 'Ýüklemek & Tassyklamak'),
+ icon: Upload,
+ },
+ ]
+
+ const stepItems: StepCardItem[] = stepDefs.map((def, i) => ({
+ ...def,
+ status: stepStatuses[i],
+ }))
+
+ const isFirstStep = currentStep === 0
+ const isLastStep = currentStep === stepDefs.length - 1
+
// ── Render ────────────────────────────────────────────────────────────────
return (
-
+
- {/* ── Status section ── */}
-
-
- setForm((f) => ({ ...f, isPaid: e.target.checked }))}
- className="w-4 h-4 accent-primary cursor-pointer"
- />
-
-
+ {/* ── Step Bar ─────────────────────────────────────────────────────── */}
+
+
+
-
-
-
-
-
+ {/* ── Step 0: Kart & Lokasiýa ──────────────────────────────────────── */}
+ {currentStep === 0 && (
+ <>
+
+ {/* isPaid toggle */}
+
+ setForm((f) => ({ ...f, isPaid: e.target.checked }))}
+ className="w-4 h-4 accent-primary cursor-pointer"
+ />
+
+
- {/* ── Kart ── */}
-
-
-
-
-
-
+
+
- {/* ── Lokasiýa ── */}
-
-
- {
- setForm((f) => ({ ...f, provinceId: v, branchId: '' }))
- }}
- options={toOptions(provinces)}
- error={errors.provinceId}
- />
-
-
-
+
+
+
- {/* ── Şahsy maglumatlar ── */}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {/* ── Pasport ── */}
-
-
-
-
-
-
-
-
-
-
-
-
-
- {/* ── Pasport faýýlar ── */}
-
-
-
-
-
-
-
-
-
- {/* ── Terms ── */}
- {!isEdit && (
-
setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))}
- >
-
- {form.termsAccepted && (
-
- )}
-
-
- {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')}
-
-
+
+
+
+ {
+ setForm((f) => ({ ...f, provinceId: v, branchId: '' }))
+ setErrors((prev) => ({ ...prev, provinceId: undefined, branchId: undefined }))
+ }}
+ options={toOptions(provinces)}
+ error={errors.provinceId}
+ />
+
+
+
+
+
+
+ >
)}
- {/* ── Actions ── */}
-
- {onCancel && (
-
- )}
-
-
+ {/* ── Step 1: Şahsy maglumatlar ─────────────────────────────────────── */}
+ {currentStep === 1 && (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+ {/* ── Step 2: Pasport ───────────────────────────────────────────────── */}
+ {currentStep === 2 && (
+
+
+
+
+
+ )}
+
+ {/* ── Step 3: Faýllar & Şertler ─────────────────────────────────────── */}
+ {currentStep === 3 && (
+ <>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* Terms — only in create mode */}
+ {!isEdit && (
+
{
+ setForm((f) => ({ ...f, termsAccepted: !f.termsAccepted }))
+ setErrors((prev) => ({ ...prev, termsAccepted: undefined }))
+ }}
+ >
+
+ {form.termsAccepted && (
+
+ )}
+
+
+ {t('cardOrder.terms', 'Şertnama bilen razylaşýaryn (Okamak üçin bas)')}
+
+
+ )}
+ >
+ )}
+
+ {/* ── Form Actions ──────────────────────────────────────────────────── */}
+
)
}
\ No newline at end of file
diff --git a/src/features/permissions/components/permissionsForm.tsx b/src/features/permissions/components/permissionsForm.tsx
index f07a4a5..5845314 100644
--- a/src/features/permissions/components/permissionsForm.tsx
+++ b/src/features/permissions/components/permissionsForm.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { FormInput } from '@/components/formInput'
-import { Button } from '@/components/ui/button'
+import { FormActions } from '@/components/formActions'
import { useCreatePermission, useUpdatePermission } from '../hooks/usePermissions'
import type { Permission, PermissionPayload } from '../api/permissionsApi'
@@ -175,28 +175,15 @@ export function PermissionForm({ mode, initialData, permissionId }: PermissionFo
/>
- {/* Actions */}
-
-
-
-
+ navigate('/settings/users/permissions')}
+ submitLabel={mode === 'create'
+ ? t('permissions.actions.create', 'Rugsat dörediň')
+ : t('permissions.actions.save', 'Ýatda sakla')}
+ className="px-5 py-4 border-t border-border bg-muted/20"
+ />
)
}
\ No newline at end of file
diff --git a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx
index a3bd53d..8185fa4 100644
--- a/src/features/requiredDocuments/components/requiredDocumentsForm.tsx
+++ b/src/features/requiredDocuments/components/requiredDocumentsForm.tsx
@@ -21,7 +21,7 @@ import {
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { FormInput } from '@/components/formInput'
-import { Button } from '@/components/ui/button'
+import { FormActions } from '@/components/formActions'
import { useCreateRequiredDocument, useUpdateRequiredDocument } from '../hooks/useRequiredDocuments'
import type { LoanDocument, LoanDocumentPayload, LoanDocumentTranslation } from '../api/requiredDocumentsApi'
@@ -222,8 +222,8 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
// ── Submit ──────────────────────────────────────────────────────────────────
- const handleSubmit = async (e: React.FormEvent) => {
- e.preventDefault()
+ const handleSubmit = async (e?: React.FormEvent) => {
+ e?.preventDefault()
if (!validate()) return
const payload: LoanDocumentPayload = { name, description }
@@ -292,20 +292,15 @@ export function RequiredDocumentForm({ mode, initialData, requiredDocumentId }:
- {/* ── Actions ──────────────────────────────────────────────────────────── */}
-