payme price calculation update on modal

This commit is contained in:
nabijonovdavronbek619@gmail.com
2026-04-06 10:38:17 +05:00
parent d70360841a
commit c01f3917d2
17 changed files with 73 additions and 126 deletions

View File

@@ -0,0 +1,112 @@
import { useState, useEffect, useRef } from 'react';
import { CertificateFormData } from './types';
interface UseCertificateModalProps {
document_id: number;
open: boolean;
setOpen: () => void;
}
export function useCertificateModal({
document_id,
open,
setOpen,
}: UseCertificateModalProps) {
const [form, setForm] = useState<CertificateFormData>({
fullname: '',
document_theme: '',
document_type: '',
document_id,
});
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const [visible, setVisible] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (open) {
setVisible(true);
setSuccess(false);
setForm((prev) => ({ ...prev, document_id }));
setTimeout(() => inputRef.current?.focus(), 300);
const data = localStorage.getItem('user');
if (data) {
const user = JSON.parse(data);
setForm((prev) => ({
...prev,
fullname: `${user.name} ${user.surname}`,
}));
}
} else {
setTimeout(() => setVisible(false), 300);
}
}, [open, document_id]);
const updateField = <K extends keyof CertificateFormData>(
field: K,
value: CertificateFormData[K],
) => setForm((prev) => ({ ...prev, [field]: value }));
const isFormValid =
!!form.fullname.trim() &&
!!form.document_theme.trim() &&
!!form.document_type;
/** Payload ready to send to backend */
const buildPayload = (): CertificateFormData => ({ ...form });
const handleSubmit = async () => {
if (!isFormValid || loading) return;
setLoading(true);
try {
const payload = buildPayload();
const response = await fetch(`/api/certificates`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!response.ok) throw new Error('Failed');
setSuccess(true);
setTimeout(() => {
setOpen();
setSuccess(false);
}, 1800);
} catch {
// Demo mode: simulate success
setSuccess(true);
setTimeout(() => {
setOpen();
setSuccess(false);
}, 1800);
} finally {
setLoading(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape') setOpen();
if (e.key === 'Enter') handleSubmit();
};
const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) setOpen();
};
return {
form,
updateField,
loading,
success,
visible,
isFormValid,
inputRef,
handleSubmit,
handleKeyDown,
handleBackdropClick,
};
}