193 lines
6.0 KiB
TypeScript
193 lines
6.0 KiB
TypeScript
import { getAuth } from '@/auth';
|
|
import { Alert, useDataGrid } from '@/components';
|
|
import { apiConfig } from '@/config/api.config';
|
|
import { useCallApi } from '@/hooks';
|
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
import { useManageProfessionContext } from '../hooks/useManageProfessionContext';
|
|
import { toast } from 'sonner';
|
|
import {
|
|
Dialog,
|
|
DialogBody,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogHeader,
|
|
DialogTitle
|
|
} from '@/components/ui/dialog';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Button } from '@/components/ui/button';
|
|
import { doSaveLogActivity } from '@/actions/GlobalActions';
|
|
import { RefreshCw } from 'lucide-react';
|
|
|
|
const API_URL = apiConfig.service_master_data;
|
|
const AddDialog = () => {
|
|
const parentRef = useRef<any | null>(null);
|
|
const { reload } = useDataGrid();
|
|
const { PostData } = useCallApi();
|
|
const { showAddDialog, handleAddDialog, selectedProfession } = useManageProfessionContext();
|
|
const parsedUser = getAuth()?.user;
|
|
const [alert, setAlert] = useState({
|
|
show: false,
|
|
message: ''
|
|
});
|
|
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
const initialState = {
|
|
name: '',
|
|
created_by: '',
|
|
created_at: ''
|
|
};
|
|
const [formField, setFormField] = useState(initialState);
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const created_time = new Date();
|
|
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
|
|
|
|
|
|
const validateForm = () => {
|
|
const requiredFields = [{ key: 'name', label: 'Profession Name' }];
|
|
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;
|
|
};
|
|
|
|
const resetForm = () => {
|
|
setFormField(initialState);
|
|
setErrors({});
|
|
};
|
|
|
|
const doCreateProfession = useCallback(
|
|
async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
setIsSubmitting(true);
|
|
|
|
try {
|
|
const response = await PostData(`${API_URL}/profession/create`, formField);
|
|
|
|
if (response?.status) {
|
|
resetForm();
|
|
handleAddDialog(false);
|
|
toast.success('Success Create Profession');
|
|
reload();
|
|
|
|
const createActivity = {
|
|
module: 'Manage Profession',
|
|
description: `Create Profession => ${formField.name}`,
|
|
action: 'C'
|
|
};
|
|
|
|
doSaveLogActivity(createActivity);
|
|
} else {
|
|
toast.error('Failed Create Profession');
|
|
setAlert({ show: true, message: response?.message });
|
|
}
|
|
} catch (error) {
|
|
toast.error('Something went wrong, please try again.');
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
},
|
|
[formField]
|
|
);
|
|
|
|
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
setIsSubmitting(true);
|
|
if (!validateForm()) {
|
|
setIsSubmitting(false);
|
|
return;
|
|
}
|
|
|
|
doCreateProfession(e);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (showAddDialog) {
|
|
setFormField({
|
|
...formField,
|
|
created_by: parsedUser.username,
|
|
created_at: formattedTime
|
|
});
|
|
}
|
|
}, [formattedTime, parsedUser.username, showAddDialog]);
|
|
|
|
useEffect(() => {
|
|
if (showAddDialog === false) {
|
|
resetForm();
|
|
}
|
|
}, [showAddDialog]);
|
|
|
|
return (
|
|
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
|
|
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
|
|
<DialogHeader>
|
|
<DialogTitle>Profession - Create</DialogTitle>
|
|
<DialogDescription></DialogDescription>
|
|
</DialogHeader>
|
|
<DialogBody ref={parentRef}>
|
|
<div className="flex flex-col">
|
|
{alert.show && (
|
|
<Alert variant="danger">
|
|
<h3>{alert.message}</h3>
|
|
</Alert>
|
|
)}
|
|
|
|
<form onSubmit={handleSubmit}>
|
|
<div className="card-body grid gap-5">
|
|
<div className="w-full">
|
|
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
|
|
<label className="form-label flex items-center gap-1 max-w-56">
|
|
Name<span className="text-red-500">*</span>
|
|
</label>
|
|
<div className='grow flex flex-col'>
|
|
|
|
<Input
|
|
className={`input ${errors.name ? 'border-red-500' : ''}`}
|
|
type="text"
|
|
autoComplete='off'
|
|
value={formField.name}
|
|
onChange={({ target }) => {
|
|
setFormField((prev) => ({ ...prev, name: target.value }));
|
|
if (target.value) {
|
|
setErrors((prev) => ({ ...prev, name: '' }));
|
|
}
|
|
}} />
|
|
{errors.name && <span className="text-red-500 text-sm">{errors.name}</span>}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex justify-end gap-5">
|
|
<Button type="button" variant="outline" onClick={resetForm}>
|
|
Reset
|
|
</Button>
|
|
<Button variant="default" type="submit" disabled={isSubmitting}>
|
|
{isSubmitting ? (
|
|
<RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
|
|
) : (
|
|
'Create'
|
|
)}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</DialogBody>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
};
|
|
|
|
export default AddDialog;
|