add button search postoadms

This commit is contained in:
Wikzyy
2025-02-28 18:36:32 +07:00
parent 126a7b2ba6
commit f13496a262
4 changed files with 246 additions and 31 deletions

View File

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

View File

@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
const { handleAddDialog } = useManageMunicipiosContext();
const { handleAddDialog, handleSearchDialog } = useManageMunicipiosContext();
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
@ -17,9 +17,7 @@ const ListToolbar = () => {
type="text"
placeholder="Search Municipios"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
onChange={(event) =>
table.getColumn('name')?.setFilterValue(event.target.value)
}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
/>
</label>
<DefaultTooltip title={'Filter'} placement={'top'}>
@ -33,6 +31,13 @@ const ListToolbar = () => {
<KeenIcon icon="filter" />
</Button>
</DefaultTooltip>
<Button
variant="outline"
className="h-7.5 text-[0.8rem]"
onClick={() => handleSearchDialog(true)}
>
Search Postu Administrativo
</Button>
</div>
<div className="flex gap-3 items-center">
<Button

View File

@ -0,0 +1,177 @@
import { useRef, useState } from 'react';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon } from '@/components';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import { apiConfig } from '@/config/api.config';
import axios from 'axios';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
interface PostoAdms {
id: number;
name: string;
}
const API_URL = apiConfig.service_master_data;
const SearchDialog = () => {
const parentRef = useRef<any | null>(null);
const { showSearchDialog, handleSearchDialog, municipios } = useManageMunicipiosContext();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
id: 0,
name: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
};
const [postoadms, setPostoadms] = useState<PostoAdms[]>([]);
const [isFound, setIsFound] = useState(false);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const id = Number(formField.id);
if (formField.id === 0) {
setAlert({ show: true, message: 'Please fill name field.' });
return;
}
try {
const response = await axios.get(`${API_URL}/municipios/postoadms/${id}`);
if (response.data.status) {
setPostoadms(response.data.data);
setIsFound(true);
console.log('Found postoadms: ', response.data.data);
} else {
setPostoadms([]);
setIsFound(false);
setAlert({ show: true, message: 'No postoadms found.' });
}
} catch (error) {
console.error('Error fetching postoadms', error);
setAlert({ show: true, message: 'Failed to fetch postoadms. Please try again.' });
}
setAlert({ show: false, message: '' });
};
const handleReset = () => {
setFormField(initialState);
setIsFound(false);
setPostoadms([]);
};
// console.log(municipios);
return (
<Dialog open={showSearchDialog} onOpenChange={(open) => handleSearchDialog(open)}>
<DialogContent className="container-fixed max-w-96 flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<DialogHeader className="p-2 border-0">
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">
Search Postu Administravo
</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => {
handleSearchDialog(false);
resetForm();
}}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
{alert.show && (
<Alert variant="danger" className="mb-5">
{alert.message}
</Alert>
)}
<form action="" onSubmit={handleSubmit}>
<div className="card-body grid-cols-6 gap-5 p-0">
<div className="grid grid-cols-8 gap-2 w-full items-center">
<label className="form-label flex items-center gap-1 col-span-2">
Name<span className="text-red-500">*</span>
</label>
<Select
value={formField.id.toString()}
onValueChange={(target) => {
const selectedMunicipio = municipios.find((m) => m.id.toString() === target);
if (selectedMunicipio) {
setFormField({
...formField,
id: selectedMunicipio.id,
name: selectedMunicipio.name
});
}
}}
>
<SelectTrigger className="col-span-6">
<SelectValue placeholder="Select Municipios" />
</SelectTrigger>
<SelectContent>
{municipios.map((municipio) => (
<SelectItem key={municipio.id} value={municipio.id.toString()}>
{municipio.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{isFound && postoadms.length > 0 && (
<div className="mt-4 border-t pt-4">
<h2 className="text-md font-semibold">Postu Administravo: </h2>
<br />
<div className="flex flex-col">
<span className="text-sm form-hint">
{postoadms.map((posto) => posto.name).join(', ')}
</span>
</div>
</div>
)}
<div className="flex justify-end pt-2.5 gap-5 col-span-6">
<Button variant={'outline'} type="reset" onClick={handleReset}>
Reset
</Button>
<Button variant={'default'} type="submit">
Search
</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default SearchDialog;

View File

@ -6,6 +6,8 @@ import axios from 'axios';
import React, { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import { useCallApi } from '@/hooks';
import ListToolbar from '../blocks/ListToolbar';
import { Button } from '@/components/ui/button';
import { useNavigate } from 'react-router';
interface MunicipiosProps {
id: number;
@ -13,6 +15,9 @@ interface MunicipiosProps {
}
interface ContextProps {
municipios: MunicipiosProps[];
showSearchDialog: boolean;
handleSearchDialog: (show: boolean) => void;
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_user: string | null) => void;
showAddDialog: boolean;
@ -30,42 +35,51 @@ interface ContextProps {
}
const initialProps: ContextProps = {
municipios: [],
showSearchDialog: false,
handleSearchDialog: (show: boolean) => {},
showEditDialog: false,
handleEditDialog: () => {},
handleEditDialog: (show: boolean, selected_user: string | null) => {},
showAddDialog: false,
handleAddDialog: () => {},
handleAddDialog: (show: boolean) => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
handleDeleteDialog: (show: boolean, selected_user: string | null) => {},
selectedMunicipios: null,
getMunicipiosLists: async () => ({ data: [], totalCount: 0 })
};
interface MunicipiosContext {
municipios: MunicipiosProps[];
getMunicipiosLists: (
limit: number,
page: number,
with_deleted: boolean,
order_field: any,
order_direction: any
) => Promise<void>;
getMunicipiosByName: (name: string) => Promise<void>;
createMunicipios: (data: Partial<MunicipiosProps>) => Promise<void>;
updateMunicipios: (id: number, data: Partial<MunicipiosProps>) => Promise<void>;
deleteMunicipios: (id: number, hardDelete?: boolean) => Promise<void>;
restoreMunicipios: (id: number) => Promise<void>;
}
// interface MunicipiosContext {
// municipios: MunicipiosProps[];
// getMunicipiosLists: (
// limit: number,
// page: number,
// with_deleted: boolean,
// order_field: any,
// order_direction: any
// ) => Promise<void>;
// getMunicipiosByName: (name: string) => Promise<void>;
// createMunicipios: (data: Partial<MunicipiosProps>) => Promise<void>;
// updateMunicipios: (id: number, data: Partial<MunicipiosProps>) => Promise<void>;
// deleteMunicipios: (id: number, hardDelete?: boolean) => Promise<void>;
// restoreMunicipios: (id: number) => Promise<void>;
// }
const ManageMunicipiosContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_master_data;
const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) => {
const [showSearchDialog, setShowSearchDialog] = useState(false);
const [showEditDialog, setShowEditDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedMunicipios, setSelectedMunicipios] = useState<string | null>(null);
const [municipios, setMunicipios] = useState<MunicipiosProps[]>([]);
const { GetData } = useCallApi();
const navigate = useNavigate();
const handleSearchDialog = useCallback((show: boolean) => {
setShowSearchDialog(show);
}, []);
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
@ -81,6 +95,11 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
setShowDeleteDialog(show);
}, []);
const handleNavigate = (path: string) => {
const url = navigate(`${API_URL}/municipios/postoadms/${path}`);
console.log(url);
};
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
@ -100,18 +119,26 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[250px]'
headerClassName: 'w-[1000px]'
}
},
{
accessorFn: (row) => row.postoadms,
id: 'postoadms',
header: ({ column }) => <DataGridColumnHeader title="Postoadms" column={column} />,
enableSorting: true,
id: 'actions',
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
enableSorting: false,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
}
headerClassName: 'w-[100px], text-center',
cellClassName: 'text-center'
},
cell: (info) => (
<Button
variant={'outline'}
onClick={() => navigate(`/master-data/municipios/postoadms/${info.row.original.id}`)}
>
Details
</Button>
)
}
],
[handleEditDialog, handleDeleteDialog]
@ -131,6 +158,7 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
}
});
console.log(response.data);
setMunicipios(response.data.data.list);
return { data: response?.data.data.list, totalCount: response?.data.data.total_count };
} catch (error) {
console.error('Error fetching municipios', error);
@ -182,10 +210,13 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
console.error('Error restoring municipios', error);
}
};
console.log(municipios);
return (
<ManageMunicipiosContext.Provider
value={{
municipios,
showSearchDialog,
handleSearchDialog,
showAddDialog,
handleAddDialog,
showDeleteDialog,
@ -200,7 +231,7 @@ const ManageMunicipiosProvider = ({ children }: { children: React.ReactNode }) =
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
pagination={{ size: 25 }}
toolbar={<ListToolbar />}
layout={{ card: true }}
sorting={[{ id: 'id', desc: false }]}