fix alert empty validation on conversion module

This commit is contained in:
Wikzyy
2025-05-08 10:49:40 +07:00
parent 95fae23120
commit 3ab53271d1
4 changed files with 135 additions and 85 deletions

View File

@ -118,7 +118,7 @@ const DetailTransaction = () => {
</div> </div>
</div> </div>
</div> </div>
<p className="mt-4 text-gray-500">Loading Provider Details...</p> <p className="mt-4 text-gray-500">Loading Logs Details...</p>
</div> </div>
) : ( ) : (
<table className="min-w-full table-auto"> <table className="min-w-full table-auto">

View File

@ -35,6 +35,7 @@ import {
import { useManageConversionContext } from '../hooks/useManageConversionContext'; import { useManageConversionContext } from '../hooks/useManageConversionContext';
import { doSaveLogActivity } from '@/actions/GlobalActions'; import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react'; import { RefreshCw } from 'lucide-react';
import { initialState, validateForm } from './Types';
interface CurrencyProps { interface CurrencyProps {
ID: string; ID: string;
name: string; name: string;
@ -50,19 +51,7 @@ const AddDialog = () => {
const parsedUser = getAuth()?.user; const parsedUser = getAuth()?.user;
const [currencies, setCurrencies] = useState<CurrencyProps[]>([]); const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [alert, setAlert] = useState({ const [errors, setErrors] = useState<Record<string, string>>({});
show: false,
message: ''
});
const initialState = {
status: '',
id_currency_origin: '',
id_currency_destination: '',
buy: 0,
sell: 0,
created_by: '',
created_at: ''
};
const [formField, setFormField] = useState(initialState); const [formField, setFormField] = useState(initialState);
const created_time = new Date(); const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' '); const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
@ -70,7 +59,7 @@ const AddDialog = () => {
const resetForm = () => { const resetForm = () => {
setFormField(initialState); setFormField(initialState);
setAlert({ show: false, message: '' }); setErrors({});
}; };
const doCreateConversion = useCallback( const doCreateConversion = useCallback(
@ -94,8 +83,7 @@ const AddDialog = () => {
doSaveLogActivity(createActivity); doSaveLogActivity(createActivity);
reload(); reload();
} else { } else {
toast.error('Error Create Conversion'); toast.error(response?.message);
setAlert({ show: true, message: response?.message });
} }
} catch (error) { } catch (error) {
toast.error('Something Went Wrong'); toast.error('Something Went Wrong');
@ -126,20 +114,11 @@ const AddDialog = () => {
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
if ( if (!validateForm(formField, setErrors)) {
formField.id_currency_origin === '' ||
formField.id_currency_destination === '' ||
formField.buy === 0 ||
formField.sell === 0 ||
formField.status === ''
) {
setAlert({ show: true, message: 'Please fill in all required fields.' });
return; return;
} }
doCreateConversion(e); doCreateConversion(e);
// console.log(formField);
setAlert({ show: false, message: '' });
}; };
useEffect(() => { useEffect(() => {
@ -171,12 +150,6 @@ const AddDialog = () => {
</DialogHeader> </DialogHeader>
<DialogBody ref={parentRef}> <DialogBody ref={parentRef}>
<div className="flex flex-col"> <div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<div className="card-body grid gap-5"> <div className="card-body grid gap-5">
<div className="w-full"> <div className="w-full">
@ -185,11 +158,14 @@ const AddDialog = () => {
</label> </label>
<Select <Select
value={formField.id_currency_origin} value={formField.id_currency_origin}
onValueChange={(id_currency_origin) => onValueChange={(id_currency_origin) => {
setFormField((prev) => ({ ...prev, id_currency_origin })) setFormField((prev) => ({ ...prev, id_currency_origin }));
} setErrors((prev) => ({ ...prev, id_currency_destination: '' }));
}}
> >
<SelectTrigger> <SelectTrigger
className={errors.id_currency_destination ? 'border-red-500' : ''}
>
<SelectValue placeholder="Select Currency" /> <SelectValue placeholder="Select Currency" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -200,6 +176,11 @@ const AddDialog = () => {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
{errors.id_currency_destination && (
<span className="text-red-500 text-xs mt-1">
{errors.id_currency_destination}
</span>
)}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -207,11 +188,12 @@ const AddDialog = () => {
</label> </label>
<Select <Select
value={formField.id_currency_destination} value={formField.id_currency_destination}
onValueChange={(id_currency_destination) => onValueChange={(id_currency_destination) => {
setFormField((prev) => ({ ...prev, id_currency_destination })) setFormField((prev) => ({ ...prev, id_currency_destination }));
} setErrors((prev) => ({ ...prev, id_currency_origin: '' }));
}}
> >
<SelectTrigger> <SelectTrigger className={errors.id_currency_origin ? 'border-red-500' : ''}>
<SelectValue placeholder="Select Currency" /> <SelectValue placeholder="Select Currency" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -222,13 +204,16 @@ const AddDialog = () => {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
{errors.id_currency_origin && (
<span className="text-red-500 text-xs mt-1">{errors.id_currency_origin}</span>
)}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
Buy<span className="text-red-500">*</span> Buy<span className="text-red-500">*</span>
</label> </label>
<NumericFormat <NumericFormat
className="input" className={`input ${errors.buy ? 'border-red-500' : ''}`}
value={formField.buy} value={formField.buy}
thousandSeparator="." thousandSeparator="."
decimalSeparator="," decimalSeparator=","
@ -236,11 +221,13 @@ const AddDialog = () => {
onValueChange={(values) => { onValueChange={(values) => {
setFormField((prev) => ({ setFormField((prev) => ({
...prev, ...prev,
buy: values.floatValue || 0 buy: values.floatValue ?? null
})); }));
setErrors((prev) => ({ ...prev, buy: '' }));
}} }}
placeholder="Enter Buy" placeholder="Enter Buy"
/> />
{errors.buy && <span className="text-red-500 text-xs mt-1">{errors.buy}</span>}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -248,7 +235,7 @@ const AddDialog = () => {
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</label> </label>
<NumericFormat <NumericFormat
className="input" className={`input ${errors.sell ? 'border-red-500' : ''}`}
value={formField.sell} value={formField.sell}
thousandSeparator="." thousandSeparator="."
decimalSeparator="," decimalSeparator=","
@ -256,11 +243,13 @@ const AddDialog = () => {
onValueChange={(values) => { onValueChange={(values) => {
setFormField((prev) => ({ setFormField((prev) => ({
...prev, ...prev,
sell: values.floatValue || 0 sell: values.floatValue ?? null
})); }));
setErrors((prev) => ({ ...prev, sell: '' }));
}} }}
placeholder="Enter Sell" placeholder="Enter Sell"
/> />
{errors.sell && <span className="text-red-500 text-xs mt-1">{errors.sell}</span>}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -271,11 +260,12 @@ const AddDialog = () => {
<div className="grow"> <div className="grow">
<Select <Select
value={formField.status} value={formField.status}
onValueChange={(value) => onValueChange={(value) => {
setFormField((prev) => ({ ...prev, status: value })) setFormField((prev) => ({ ...prev, status: value }));
} setErrors((prev) => ({ ...prev, status: '' }));
}}
> >
<SelectTrigger> <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
<SelectValue placeholder="Select" /> <SelectValue placeholder="Select" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -283,6 +273,9 @@ const AddDialog = () => {
<SelectItem value="N">Inactive</SelectItem> <SelectItem value="N">Inactive</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
{errors.status && (
<span className="text-red-500 text-xs mt-1">{errors.status}</span>
)}
</div> </div>
</div> </div>
<div className="flex justify-end gap-5"> <div className="flex justify-end gap-5">

View File

@ -35,6 +35,7 @@ import {
import { useManageConversionContext } from '../hooks/useManageConversionContext'; import { useManageConversionContext } from '../hooks/useManageConversionContext';
import { doSaveLogActivity } from '@/actions/GlobalActions'; import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react'; import { RefreshCw } from 'lucide-react';
import { initialState, validateForm } from './Types';
interface CurrencyProps { interface CurrencyProps {
ID: string; ID: string;
name: string; name: string;
@ -52,26 +53,15 @@ const EditDialog = () => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [alert, setAlert] = useState({ const [errors, setErrors] = useState<Record<string, string>>({});
show: false,
message: ''
});
const initialState = {
status: '',
id_currency_origin: '',
id_currency_destination: '',
buy: 0,
sell: 0,
created_by: '',
created_at: ''
};
const [formField, setFormField] = useState(initialState); const [formField, setFormField] = useState(initialState);
const updated_time = new Date(); const updated_time = new Date();
const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' '); const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');
const resetForm = () => { const resetForm = () => {
setFormField(initialState); setFormField(initialState);
setAlert({ show: false, message: '' }); setErrors({});
}; };
const doUpdateConversion = useCallback( const doUpdateConversion = useCallback(
@ -79,6 +69,11 @@ const EditDialog = () => {
e.preventDefault(); e.preventDefault();
setIsSubmitting(true); setIsSubmitting(true);
if (!validateForm(formField, setErrors)) {
setIsSubmitting(false);
return;
}
try { try {
const response = await PutData(`${API_URL}/dashboard/conversion/${selectedConversion}`, { const response = await PutData(`${API_URL}/dashboard/conversion/${selectedConversion}`, {
...formField ...formField
@ -97,8 +92,7 @@ const EditDialog = () => {
doSaveLogActivity(createActivity); doSaveLogActivity(createActivity);
reload(); reload();
} else { } else {
toast.error('Error Create Conversion'); toast.error(response?.message);
setAlert({ show: true, message: response?.message });
} }
} catch (error) { } catch (error) {
toast.error('Something went wrong'); toast.error('Something went wrong');
@ -185,12 +179,6 @@ const EditDialog = () => {
</DialogHeader> </DialogHeader>
<DialogBody ref={parentRef}> <DialogBody ref={parentRef}>
<div className="flex flex-col"> <div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
{isLoading ? ( {isLoading ? (
<div className="flex flex-col items-center justify-center p-8"> <div className="flex flex-col items-center justify-center p-8">
<div className="animate-pulse flex space-x-4 w-full"> <div className="animate-pulse flex space-x-4 w-full">
@ -213,11 +201,12 @@ const EditDialog = () => {
</label> </label>
<Select <Select
value={formField.id_currency_origin} value={formField.id_currency_origin}
onValueChange={(id_currency_origin) => onValueChange={(id_currency_origin) => {
setFormField((prev) => ({ ...prev, id_currency_origin })) setFormField((prev) => ({ ...prev, id_currency_origin }));
} setErrors((prev) => ({ ...prev, id_currency_origin: '' }));
}}
> >
<SelectTrigger> <SelectTrigger className={errors.id_currency_origin ? 'border-red-500' : ''}>
<SelectValue placeholder="Select Currency" /> <SelectValue placeholder="Select Currency" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -228,6 +217,9 @@ const EditDialog = () => {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
{errors.id_currency_origin && (
<span className="text-red-500 text-xs mt-1">{errors.id_currency_origin}</span>
)}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -235,11 +227,14 @@ const EditDialog = () => {
</label> </label>
<Select <Select
value={formField.id_currency_destination} value={formField.id_currency_destination}
onValueChange={(id_currency_destination) => onValueChange={(id_currency_destination) => {
setFormField((prev) => ({ ...prev, id_currency_destination })) setFormField((prev) => ({ ...prev, id_currency_destination }));
} setErrors((prev) => ({ ...prev, id_currency_destination: '' }));
}}
> >
<SelectTrigger> <SelectTrigger
className={errors.id_currency_destination ? 'border-red-500' : ''}
>
<SelectValue placeholder="Select Currency" /> <SelectValue placeholder="Select Currency" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -250,6 +245,11 @@ const EditDialog = () => {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
{errors.id_currency_destination && (
<span className="text-red-500 text-xs mt-1">
{errors.id_currency_destination}
</span>
)}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -264,11 +264,13 @@ const EditDialog = () => {
onValueChange={(values) => { onValueChange={(values) => {
setFormField((prev) => ({ setFormField((prev) => ({
...prev, ...prev,
buy: values.floatValue || 0 buy: values.floatValue ?? null
})); }));
setErrors((prev) => ({ ...prev, buy: '' }));
}} }}
placeholder="Enter Buy" placeholder="Enter Buy"
/> />
{errors.buy && <span className="text-red-500 text-xs mt-1">{errors.buy}</span>}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -284,11 +286,15 @@ const EditDialog = () => {
onValueChange={(values) => { onValueChange={(values) => {
setFormField((prev) => ({ setFormField((prev) => ({
...prev, ...prev,
sell: values.floatValue || 0 sell: values.floatValue ?? null
})); }));
setErrors((prev) => ({ ...prev, sell: '' }));
}} }}
placeholder="Enter Sell" placeholder="Enter Sell"
/> />
{errors.sell && (
<span className="text-red-500 text-xs mt-1">{errors.sell}</span>
)}
</div> </div>
<div className="w-full"> <div className="w-full">
<label className="form-label"> <label className="form-label">
@ -299,11 +305,12 @@ const EditDialog = () => {
<div className="grow"> <div className="grow">
<Select <Select
value={formField.status} value={formField.status}
onValueChange={(value) => onValueChange={(value) => {
setFormField((prev) => ({ ...prev, status: value })) setFormField((prev) => ({ ...prev, status: value }));
} setErrors((prev) => ({ ...prev, status: '' }));
}}
> >
<SelectTrigger> <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
<SelectValue placeholder="Select" /> <SelectValue placeholder="Select" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@ -311,6 +318,9 @@ const EditDialog = () => {
<SelectItem value="N">Inactive</SelectItem> <SelectItem value="N">Inactive</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
{errors.status && (
<span className="text-red-500 text-xs mt-1">{errors.status}</span>
)}
</div> </div>
</div> </div>
<div className="flex justify-end gap-5"> <div className="flex justify-end gap-5">

View File

@ -0,0 +1,47 @@
import { toast } from 'sonner';
export const validateForm = (formField: any, setErrors: any) => {
const requiredFields = [
{ key: 'id_currency_origin', label: 'Currency Origin' },
{ key: 'id_currency_destination', label: 'Currency Destination' },
{ key: 'buy', label: 'Buy' },
{ key: 'sell', label: 'Sell' },
{ key: 'status', label: 'Status' }
];
const newErrors: Record<string, string> = {};
let isValid = true;
requiredFields.forEach(({ key, label }) => {
if (
formField[key as keyof typeof formField] === '' ||
formField[key as keyof typeof formField] === null ||
formField[key as keyof typeof formField] === undefined
) {
newErrors[key] = `${label} is required`;
toast.error(`${label} is required`);
isValid = false;
}
});
setErrors(newErrors);
return isValid;
};
export const initialState: {
status: string;
id_currency_origin: string;
id_currency_destination: string;
buy: number | null;
sell: number | null;
created_by: string;
created_at: string;
} = {
status: '',
id_currency_origin: '',
id_currency_destination: '',
buy: null,
sell: null,
created_by: '',
created_at: ''
};