search aldeias sucos master

This commit is contained in:
Raja Oktafrianto
2025-03-17 06:18:43 +07:00
parent 125e4441a1
commit bd2a4ff233
6 changed files with 536 additions and 126 deletions

View File

@ -3,6 +3,7 @@ import { ManageSucosContextProvider } from './hooks/ManageSucosContext';
import AddDialog from './blocks/AddDialog';
import EditDialog from './blocks/EditDialog';
import DeleteDialog from './blocks/DeleteDialog';
import SearchDialog from './blocks/SearchDialog';
const SucosMaster = () => {
return (
@ -15,6 +16,7 @@ const SucosMaster = () => {
<AddDialog />
<EditDialog />
<DeleteDialog />
<SearchDialog />
</Container>
</ManageSucosContextProvider>
);

View File

@ -38,7 +38,7 @@ const ListToolbar = () => {
className="h-7.5 text-[0.8rem]"
onClick={() => handleSearchDialog(true)}
>
Search Sucos
Search Aldeias
</Button>
</div>
<div className="flex gap-3 items-center">

View File

@ -0,0 +1,183 @@
import { useContext, useEffect, 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 { apiConfig } from '@/config/api.config';
import axios from 'axios';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { useManageSucosContext } from '../hooks/useManageSucosContext';
interface AldeiasProps {
id: number;
name: string;
}
const API_URL = apiConfig.service_master_data;
const SearchDialog = () => {
const parentRef = useRef<any | null>(null);
const { showSearchDialog, handleSearchDialog, sucos } = useManageSucosContext();
console.log('Sucos:', sucos);
// const { sucos, getSucosLists } = useContext(ManageSucosContext);
// useEffect(() => {
// getSucosLists(1, 1000, [], []); // Memuat semua sucos
// }, []);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
id: 0,
name: ''
};
const [formField, setFormField] = useState(initialState);
const resetForm = () => {
setFormField(initialState);
};
const [aldeias, setAldeias] = useState<AldeiasProps[]>([]);
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}/sucos/aldeias/${id}`);
if (response.data.status) {
setAldeias(response.data.data);
setIsFound(true);
console.log('Found aldeias: ', response.data.data);
} else {
setAldeias([]);
setIsFound(false);
setAlert({ show: true, message: 'No aldeias found.' });
}
} catch (error) {
console.error('Error fetching aldeias', error);
setAlert({ show: true, message: 'Failed to fetch aldeias. Please try again.' });
}
setAlert({ show: false, message: '' });
};
const handleReset = () => {
setFormField(initialState);
setIsFound(false);
setAldeias([]);
};
// console.log(aldeias);
return (
<Dialog open={showSearchDialog} onOpenChange={(open) => handleSearchDialog(open)}>
<DialogContent className="container-fixed max-w-[700px] 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 Aldeias</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">
Sucos Name<span className="text-red-500">*</span>
</label>
<Select
value={formField.id?.toString() ?? ''}
onValueChange={(target) => {
const selectedSuco = sucos.find((m) => m.id.toString() === target);
if (selectedSuco) {
setFormField({
...formField,
id: selectedSuco.id,
name: selectedSuco.name
});
}
}}
>
<SelectTrigger className="col-span-6">
<SelectValue placeholder="Select Sucos" />
</SelectTrigger>
<SelectContent>
{sucos?.map((suco) => (
<SelectItem key={suco.id} value={suco.id}>
{suco.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{isFound && aldeias.length > 0 && (
<div className="mt-4 border-t pt-4">
<h2 className="text-md font-semibold">Aldeias: </h2>
<br />
<div className="flex flex-col">
<span className="text-sm form-hint">
{aldeias.map((aldeiasID) => aldeiasID.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

@ -5,6 +5,8 @@ import { useCallApi } from '@/hooks';
import { ColumnDef } from '@tanstack/react-table';
import React, { createContext, useCallback, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolbar';
import { useNavigate } from 'react-router';
import axios from 'axios';
interface SucosProps {
id: number;
@ -34,15 +36,15 @@ interface ContextProps {
const initialProps: ContextProps = {
sucos: [],
showSearchDialog: false,
handleSearchDialog: () => {},
handleSearchDialog: (show: boolean) => {},
showEditDialog: false,
handleEditDialog: () => {},
handleEditDialog: (show: boolean, selected_sucos: string | null) => {},
showAddDialog: false,
handleAddDialog: () => {},
handleAddDialog: (show: boolean) => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
handleDeleteDialog: (show: boolean, selected_sucos: string | null) => {},
selectedSucos: null,
getSucosLists: async () => undefined
getSucosLists: async () => ({ data: [], totalCount: 0 })
};
const ManageSucosContext = createContext<ContextProps>(initialProps);
@ -56,6 +58,7 @@ const ManageSucosContextProvider = ({ children }: { children: React.ReactNode })
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedSucos, setSelectedSucos] = useState<string | null>(null);
const { GetData } = useCallApi();
const navigate = useNavigate();
const handleSearchDialog = useCallback((show: boolean) => {
setShowSearchDialog(show);
@ -75,6 +78,10 @@ const ManageSucosContextProvider = ({ children }: { children: React.ReactNode })
setShowDeleteDialog(show);
}, []);
const handleNavigate = (path: string) => {
const url = navigate(`${API_URL}/sucos/aldeias/${path}`);
};
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
@ -145,22 +152,67 @@ const ManageSucosContextProvider = ({ children }: { children: React.ReactNode })
sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
const response = await GetData(`${API_URL}/sucos/list`, {
limit,
limit: limit,
page: page + 1,
with_deleted: true,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
filter: JSON.stringify(filter)
});
console.log(response?.data);
setSucos(response?.data.list);
// console.log(sucos);
console.log('Sucos List Response:', response?.data);
setSucos(response?.data.list || []); // Pastikan default value adalah array kosong
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
console.error('Error fetching Sucos', error);
}
};
const getAldeiasBySucos = async (name: string) => {
try {
const response = await axios.get(`${API_URL}/sucos/aldeias/${name}`);
const data = response.data;
console.log(data);
} catch (error) {
console.log(`Error fetching sucos by ${name}`, error);
}
};
const createSucos = async (data: Partial<SucosProps>) => {
try {
await axios.post(`${API_URL}/sucos/create`, data);
// getMunicipiosLists(10, 1, false, 'name', 'ASC');
} catch (error) {
console.error('Error creating municipios', error);
}
};
const updateSucos = async (id: number, data: Partial<SucosProps>) => {
try {
await axios.put(`${API_URL}/sucos/update/${id}`, data);
// getSucosLists(10, 1, false, 'name', 'ASC');
} catch (error) {
console.error('Error updating sucos', error);
}
};
const deleteSucos = async (id: number, hardDelete?: boolean) => {
try {
await axios.delete(`${API_URL}/sucos/delete/${id}/${hardDelete}`);
// getSucosLists(10, 1, false, 'name', 'ASC');
} catch (error) {
console.error('Error deleting sucos', error);
}
};
const restoreSucos = async (id: number) => {
try {
await axios.put(`${API_URL}/sucos/restore/${id}`);
// getSucosLists(10, 1, false, 'name', 'ASC');
} catch (error) {
console.error('Error restoring sucos', error);
}
};
return (
<ManageSucosContext.Provider
value={{

View File

@ -4,7 +4,8 @@ import { ManageSucosContext } from './ManageSucosContext';
const useManageSucosContext = () => {
const context = useContext(ManageSucosContext);
if (!context) throw new Error('useManageSucosContext must be used within AuthProvider');
if (!context)
throw new Error('useManageSucosContext must be used within ManageSucosContextProvider');
return context;
};