add crud municipio

This commit is contained in:
Wikzyy
2025-03-03 11:59:32 +07:00
parent 84408ac869
commit e6cf8106c8
7 changed files with 338 additions and 22 deletions

View File

@ -2,6 +2,8 @@ import { Container, DataGridInner } from '@/components';
import { ManageMunicipiosProvider } from './hooks/ManageMunicipiosContext';
import AddDialog from './blocks/AddDialog';
import SearchDialog from './blocks/SearchDialog';
import EditDialog from './blocks/EditDialog';
import DeleteDialog from './blocks/DeleteDialog';
const Municipios = () => {
return (
@ -12,6 +14,8 @@ const Municipios = () => {
<DataGridInner />
</div>
<AddDialog />
<EditDialog />
<DeleteDialog />
<SearchDialog />
</Container>
</ManageMunicipiosProvider>

View File

@ -1,4 +1,4 @@
import React, { useRef, useState } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import {
Dialog,
@ -8,19 +8,32 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon } from '@/components';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import axios from 'axios';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import { getAuth, useAuthContext } from '@/auth';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
const AddDialog = () => {
const parentRef = useRef<any | null>(null);
const { showAddDialog, handleAddDialog } = useManageMunicipiosContext();
const { reload } = useDataGrid();
const { PostData } = useCallApi();
const parsedUser = getAuth()?.user;
const { showAddDialog, handleAddDialog, selectedMunicipios } = useManageMunicipiosContext();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
name: ''
name: '',
created_by: '',
created_at: ''
};
const [formField, setFormField] = useState(initialState);
@ -28,6 +41,31 @@ const AddDialog = () => {
setFormField(initialState);
};
const doCreateMunicipio = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PostData(`${API_URL}/municipios/create`, formField);
if (response?.status) {
handleAddDialog(false);
resetForm();
toast.success('Municipio created successfully!');
reload();
// const createActivity = {
// module: 'Manage Municipio',
// description: `Create Municipio => ${selectedMunicipios}`,
// action: 'C'
// };
// doSaveLogActivity(createActivity);
} else {
toast.error('Failed to create municipio.');
setAlert({ show: true, message: 'Failed to create municipio. Please try again.' });
}
},
[formField]
);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
@ -36,6 +74,14 @@ const AddDialog = () => {
return;
}
// setFormField({
// name: formField.name,
// created_by: parsedUser.email,
// created_at: formattedTime
// });
// doCreateMunicipio(e);
console.log(parsedUser.email);
console.log(formField);
setAlert({ show: false, message: '' });
};
@ -44,6 +90,18 @@ const AddDialog = () => {
setFormField(initialState);
};
useEffect(() => {
const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
if (showAddDialog) {
setFormField({
name: formField.name,
created_by: parsedUser.email,
created_at: formattedTime
});
}
}, [showAddDialog]);
return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<DialogContent className="container-fixed max-w-96 flex flex-col p-5 overflow-hidden [&>button]:hidden">
@ -96,7 +154,7 @@ const AddDialog = () => {
Reset
</Button>
<Button variant={'default'} type="submit">
Save Changes
Create
</Button>
</div>
</div>

View File

@ -0,0 +1,87 @@
import { Alert, useDataGrid } from '@/components';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import { ChangeEvent, useCallback, useState } from 'react';
import axios from 'axios';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import { Dialog, DialogContent, DialogFooter, DialogHeader } from '@/components/ui/dialog';
import { EnforceSwitch } from '@/components/switch';
import { Button } from '@/components/ui/button';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
const DeleteDialog = () => {
const { showDeleteDialog, handleDeleteDialog, selectedMunicipios, municipios } =
useManageMunicipiosContext();
const { reload } = useDataGrid();
const { DeleteData } = useCallApi();
const [enforce, setEnforce] = useState(false);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const doDeleteMunicipio = useCallback(async () => {
const response = await DeleteData(
`${API_URL}/municipios/delete/${selectedMunicipios}/${enforce}`,
{
id: selectedMunicipios
}
);
if (response?.status) {
setAlert((prev) => ({ ...prev, show: false, message: '' }));
handleDeleteDialog(false, null);
toast.success('Success Delete Municipio');
reload();
// const createActivity = {
// module: 'Manage Municipio',
// description: `Delete Municipio => ${selectedMunicipios}`,
// action: 'D'
// };
// doSaveLogActivity(createActivity);
} else {
setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
}
}, [selectedMunicipios, enforce]);
return (
<Dialog open={showDeleteDialog} onOpenChange={(open) => handleDeleteDialog(open, null)}>
<DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0 block">
<Alert variant="warning">
<h3 className="text-lg">Are you sure?</h3>
<span className="text-sm">you will delete this data!</span>
<div className="mt-2 flex items-center gap-x-2">
<label className="form-label max-w-56">Hard Delete</label>
<EnforceSwitch
enforce={enforce}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setEnforce(e.target.checked);
}}
/>
</div>
</Alert>
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
</DialogHeader>
<DialogFooter className="flex justify-end items-center gap-4 mt-3">
<Button variant={'outline'} onClick={() => handleDeleteDialog(false, null)}>
Cancel
</Button>
<Button variant={'destructive'} onClick={() => doDeleteMunicipio()}>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default DeleteDialog;

View File

@ -0,0 +1,152 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import { Alert, useDataGrid } from '@/components';
import axios from 'axios';
import { apiConfig } from '@/config/api.config';
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 { getAuth, useAuthContext } from '@/auth';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
const API_URL = apiConfig.service_master_data;
const EditDialog = () => {
const parentRef = useRef<any | null>(null);
const { showEditDialog, handleEditDialog, selectedMunicipios, municipios } =
useManageMunicipiosContext();
const { reload } = useDataGrid();
const { PutData } = useCallApi();
const parsedUser = getAuth()?.user;
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
name: '',
updated_by: '',
updated_at: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
};
const doUpdateMunicipios = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PutData(
`${API_URL}/municipios/update/${selectedMunicipios}`,
formField
);
if (response?.status) {
handleEditDialog(false, null);
resetForm();
toast.success('Success update municipio');
reload();
// const createActivity = {
// module: 'Manage Municipio',
// description: `Edit Municipio => ${selectedMunicipios}`,
// action: 'U'
// };
// doSaveLogActivity(createActivity);
} else {
toast.error('Failed update user');
setAlert({ show: true, message: 'Failed to update municipio. Please try again.' });
}
},
[selectedMunicipios, formField]
);
const handleUpdate = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (formField.name === '') {
setAlert({ show: true, message: 'Please fill name field.' });
return;
}
// setFormField({
// name: formField.name,
// created_by: parsedUser.email,
// created_at: formattedTime
// });
doUpdateMunicipios(e);
console.log(formField);
setAlert({ show: false, message: '' });
};
// const doFetchMunicipios = useCallback(async (id: string) => {
// const response = await axios.get(`${API_URL}/municipios/${id}`);
// }, []);
useEffect(() => {
const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
if (selectedMunicipios) {
setFormField({
name: formField.name,
updated_by: parsedUser.email,
updated_at: formattedTime
});
}
}, [selectedMunicipios]);
// console.log(selectedMunicipios);
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>Municipios - Update</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<DialogBody>
<div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<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">Name</label>
<Input
className="input"
type="text"
value={formField.name}
onChange={(e) => setFormField({ ...formField, name: e.target.value })}
/>
</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;

View File

@ -21,7 +21,7 @@ import {
SelectValue
} from '@/components/ui/select';
interface PostoAdms {
interface PostoAdmsProps {
id: number;
name: string;
}
@ -44,7 +44,7 @@ const SearchDialog = () => {
const resetForm = () => {
setFormField(initialState);
};
const [postoadms, setPostoadms] = useState<PostoAdms[]>([]);
const [postoadms, setPostoadms] = useState<PostoAdmsProps[]>([]);
const [isFound, setIsFound] = useState(false);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
@ -62,7 +62,7 @@ const SearchDialog = () => {
if (response.data.status) {
setPostoadms(response.data.data);
setIsFound(true);
console.log('Found postoadms: ', response.data.data);
// console.log('Found postoadms: ', response.data.data);
} else {
setPostoadms([]);
setIsFound(false);
@ -147,7 +147,7 @@ const SearchDialog = () => {
{isFound && postoadms.length > 0 && (
<div className="mt-4 border-t pt-4">
<h2 className="text-md font-semibold">Postu Administravo: </h2>
<h2 className="text-md font-semibold">Sucos: </h2>
<br />
<div className="flex flex-col">
<span className="text-sm form-hint">

View File

@ -1,4 +1,4 @@
import { DataGridColumnHeader, DataGridProvider } from '@/components';
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
@ -127,18 +127,29 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[100px], text-center',
cellClassName: 'text-center'
cell: (data) => {
const row = data.row.original;
return (
<>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleEditDialog(true, row.id)}
>
<KeenIcon icon="notepad-edit" />
</button>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDeleteDialog(true, row.id)}
>
<KeenIcon icon="trash" />
</button>
</>
);
},
cell: (info) => (
<Button
variant={'outline'}
onClick={() => navigate(`/master-data/municipios/postoadms/${info.row.original.id}`)}
>
Details
</Button>
)
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
}
}
],
[handleEditDialog, handleDeleteDialog]
@ -158,6 +169,11 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
}
});
console.log(response.data);
// const sortedList = response.data.data.list.sort((a: MunicipiosProps, b: MunicipiosProps) => {
// if (a.name < b.name) return -1;
// if (a.name > b.name) return 1;
// return 0;
// });
setMunicipios(response.data.data.list);
return { data: response?.data.data.list, totalCount: response?.data.data.total_count };
} catch (error) {
@ -210,7 +226,6 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
console.error('Error restoring municipios', error);
}
};
console.log(municipios);
return (
<ManageMunicipiosContext.Provider
value={{