274 lines
9.0 KiB
TypeScript
274 lines
9.0 KiB
TypeScript
import { apiConfig } from '@/config/api.config';
|
|
import { useManageAldeiasContext } from '../hooks/useManageAldeiasContext';
|
|
import { Alert, useDataGrid } from '@/components';
|
|
import { useCallApi } from '@/hooks';
|
|
import { getAuth } from '@/auth';
|
|
import React, { useCallback, useEffect, useState } from 'react';
|
|
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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
|
import {
|
|
Command,
|
|
CommandEmpty,
|
|
CommandGroup,
|
|
CommandInput,
|
|
CommandItem,
|
|
CommandList
|
|
} from '@/components/ui/command';
|
|
import { doSaveLogActivity } from '@/actions/GlobalActions';
|
|
|
|
interface SucosProps {
|
|
id: number;
|
|
name: string;
|
|
}
|
|
|
|
const API_URL = apiConfig.service_master_data;
|
|
|
|
const EditDialog = () => {
|
|
const { showEditDialog, handleEditDialog, selectedAldeias, aldeias } = useManageAldeiasContext();
|
|
const { reload } = useDataGrid();
|
|
const { PutData, GetData } = useCallApi();
|
|
const parsedUser = getAuth()?.user;
|
|
const [sucos, setSucos] = useState<SucosProps[]>([]);
|
|
const [open, setOpen] = useState(false);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [alert, setAlert] = useState({
|
|
show: false,
|
|
message: ''
|
|
});
|
|
const initialState = {
|
|
name: '',
|
|
sucosId: 0,
|
|
updated_by: '',
|
|
updated_at: ''
|
|
};
|
|
const [formField, setFormField] = useState(initialState);
|
|
const created_time = new Date();
|
|
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
|
|
|
|
const resetForm = () => {
|
|
setFormField(initialState);
|
|
setAlert({ show: false, message: '' });
|
|
};
|
|
|
|
const doUpdateAldeias = useCallback(
|
|
async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
|
|
const response = await PutData(`${API_URL}/aldeias/update/${selectedAldeias}`, formField);
|
|
|
|
if (response?.status) {
|
|
resetForm();
|
|
handleEditDialog(false, null);
|
|
toast.success('Success Update Aldeia');
|
|
reload();
|
|
const createActivity = {
|
|
module: 'Manage Aldeia',
|
|
description: `Edit Aldeia => ${selectedAldeias}`,
|
|
action: 'U'
|
|
};
|
|
|
|
doSaveLogActivity(createActivity);
|
|
} else {
|
|
toast.error('Error Update Aldeia');
|
|
setAlert({ show: true, message: 'Error Update Aldeia' });
|
|
}
|
|
},
|
|
[selectedAldeias, formField]
|
|
);
|
|
|
|
const doFetchSucos = async (sorting: any) => {
|
|
try {
|
|
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
|
|
const response = await GetData(`${API_URL}/sucos/list`, {
|
|
limit: 1000,
|
|
page: 1,
|
|
with_deleted: false,
|
|
order_field: sorting[0].id,
|
|
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
|
|
});
|
|
|
|
setSucos(response?.data.list);
|
|
// console.log(sucos);
|
|
} catch (error) {
|
|
console.error('Error fetching Sucos', error);
|
|
setAlert({ show: true, message: 'Failed to get Sucos. Please try again.' });
|
|
}
|
|
};
|
|
|
|
const doFetchData = useCallback(async (id: string) => {
|
|
setIsLoading(true);
|
|
|
|
const minDelay = new Promise((resolve) => setTimeout(resolve, 300));
|
|
const fetchData = GetData(`${API_URL}/aldeias/getdata/${id}`, { id });
|
|
const [response] = await Promise.all([fetchData, minDelay]);
|
|
|
|
if (response?.status) {
|
|
setFormField((prev) => ({
|
|
...prev,
|
|
name: response.data.name,
|
|
sucosId: response.data.sucos.id
|
|
}));
|
|
} else {
|
|
setFormField((prev) => ({
|
|
...prev,
|
|
name: '',
|
|
sucosId: 0
|
|
}));
|
|
}
|
|
setIsLoading(false);
|
|
}, []);
|
|
|
|
const handleUpdate = (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
|
|
if (formField.name === '' || formField.sucosId === 0) {
|
|
setAlert({ show: true, message: 'Please fill in all required fields.' });
|
|
return;
|
|
}
|
|
|
|
doUpdateAldeias(e);
|
|
console.log(formField);
|
|
setAlert({ show: false, message: '' });
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (selectedAldeias) {
|
|
doFetchData(selectedAldeias);
|
|
}
|
|
}, [selectedAldeias]);
|
|
|
|
useEffect(() => {
|
|
if (showEditDialog === false) {
|
|
resetForm();
|
|
}
|
|
}, [showEditDialog]);
|
|
|
|
useEffect(() => {
|
|
if (showEditDialog) {
|
|
setFormField({
|
|
...formField,
|
|
updated_by: parsedUser?.username,
|
|
updated_at: formattedTime
|
|
});
|
|
}
|
|
}, [formattedTime]);
|
|
|
|
useEffect(() => {
|
|
doFetchSucos([{ id: 'name', desc: false }]);
|
|
}, []);
|
|
|
|
return (
|
|
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
|
|
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
|
|
<DialogHeader>
|
|
<DialogTitle>Aldeia - Update</DialogTitle>
|
|
<DialogDescription></DialogDescription>
|
|
</DialogHeader>
|
|
<DialogBody>
|
|
<div className="flex flex-col">
|
|
{alert.show && (
|
|
<Alert variant="danger">
|
|
<h3>{alert.message}</h3>
|
|
</Alert>
|
|
)}
|
|
|
|
{isLoading ? (
|
|
<div className="flex flex-col items-center justify-center p-8">
|
|
<div className="animate-pulse flex space-x-4 w-full">
|
|
<div className="flex-1 space-y-4 py-1">
|
|
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
|
|
<div className="space-y-2">
|
|
<div className="h-4 bg-gray-200 rounded"></div>
|
|
<div className="h-4 bg-gray-200 rounded w-5/6"></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<p className="mt-4 text-gray-500">Loading Aldeia Details...</p>
|
|
</div>
|
|
) : (
|
|
<form onSubmit={handleUpdate}>
|
|
<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">
|
|
Aldeia Name<span className="text-red-500">*</span>
|
|
</label>
|
|
<Input
|
|
className="input"
|
|
type="text"
|
|
value={formField.name}
|
|
onChange={(e) => setFormField({ ...formField, name: e.target.value })}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<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">
|
|
Sucos ID<span className="text-red-500">*</span>
|
|
</label>
|
|
<Popover open={open} onOpenChange={setOpen}>
|
|
<PopoverTrigger asChild>
|
|
<button
|
|
type="button"
|
|
className="input col-span-5 text-left"
|
|
style={{ color: 'inherit' }}
|
|
>
|
|
{sucos.find((suco) => suco.id === formField.sucosId)?.name ||
|
|
'Select Sucos'}
|
|
</button>
|
|
</PopoverTrigger>
|
|
<PopoverContent className="w-[400px] p-0">
|
|
<Command>
|
|
<CommandInput placeholder="Search Sucos..." />
|
|
<CommandList>
|
|
<CommandEmpty>No Sucos found.</CommandEmpty>
|
|
<CommandGroup>
|
|
{sucos.map((suco) => (
|
|
<CommandItem
|
|
key={suco.id}
|
|
value={suco.name}
|
|
onSelect={() => {
|
|
setFormField({
|
|
...formField,
|
|
sucosId: suco.id
|
|
});
|
|
setOpen(false);
|
|
}}
|
|
>
|
|
{suco.name}
|
|
</CommandItem>
|
|
))}
|
|
</CommandGroup>
|
|
</CommandList>
|
|
</Command>
|
|
</PopoverContent>
|
|
</Popover>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex justify-end">
|
|
<Button className="btn btn-primary">Save Changes</Button>
|
|
</div>
|
|
</div>
|
|
</form>
|
|
)}
|
|
</div>
|
|
</DialogBody>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
};
|
|
|
|
export default EditDialog;
|