[Client Portal] Cleanup Corporate

This commit is contained in:
Muhammad Fajar
2024-01-12 02:39:03 +07:00
parent e58290dbb7
commit 627b038e23
4 changed files with 94 additions and 421 deletions

View File

@@ -58,7 +58,7 @@ export type Status = {
export type TableListProps<DataType> = { export type TableListProps<DataType> = {
headCells?: HeadCell<DataType>[]; headCells?: HeadCell<DataType>[];
rows?: Array<DataType>; rows?: Array<DataType>;
paginations: { paginations?: {
page: number; page: number;
setPage: Dispatch<SetStateAction<number>>; setPage: Dispatch<SetStateAction<number>>;
rowsPerPage: number; rowsPerPage: number;
@@ -66,7 +66,7 @@ export type TableListProps<DataType> = {
paginationTable: PaginationTableProps; paginationTable: PaginationTableProps;
setPaginationTable: Dispatch<SetStateAction<PaginationTableProps>>; setPaginationTable: Dispatch<SetStateAction<PaginationTableProps>>;
}; };
orders: { orders?: {
order: Order; order: Order;
setOrder: Dispatch<SetStateAction<Order>>; setOrder: Dispatch<SetStateAction<Order>>;
orderBy: string; orderBy: string;
@@ -76,7 +76,7 @@ export type TableListProps<DataType> = {
isLoading: boolean; isLoading: boolean;
setIsLoading: Dispatch<SetStateAction<boolean>>; setIsLoading: Dispatch<SetStateAction<boolean>>;
}; };
params: { params?: {
searchParams: URLSearchParams; searchParams: URLSearchParams;
setSearchParams: any; setSearchParams: any;
appliedParams: {}; appliedParams: {};

View File

@@ -50,11 +50,11 @@ export default function Table<T>({
orders?.setOrder(isAsc ? 'desc' : 'asc'); orders?.setOrder(isAsc ? 'desc' : 'asc');
orders?.setOrderBy(property); orders?.setOrderBy(property);
const parameters = Object.fromEntries([ const parameters = Object.fromEntries([
...params.searchParams.entries(), ...(params?.searchParams.entries() as IterableIterator<[string, string]>),
['order', isAsc ? 'desc' : 'asc'], ['order', isAsc ? 'desc' : 'asc'],
['orderBy', property], ['orderBy', property],
]); ]);
params.setAppliedParams(parameters); params?.setAppliedParams(parameters);
}; };
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
@@ -107,28 +107,28 @@ export default function Table<T>({
newPage: number newPage: number
) => { ) => {
const parameters = Object.fromEntries([ const parameters = Object.fromEntries([
...params.searchParams.entries(), ...(params?.searchParams.entries() as IterableIterator<[string, string]>),
['page', newPage + 1], ['page', newPage + 1],
['per_page', paginations.rowsPerPage], ['per_page', paginations?.rowsPerPage],
]); ]);
paginations.setPage(newPage); paginations?.setPage(newPage);
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
params.setAppliedParams(parameters); params?.setAppliedParams(parameters);
}; };
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
/* --------------------------- row page per limit --------------------------- */ /* --------------------------- row page per limit --------------------------- */
const onRowsPerPageChangeHandle = async (event: React.ChangeEvent<HTMLInputElement>) => { const onRowsPerPageChangeHandle = async (event: React.ChangeEvent<HTMLInputElement>) => {
params.searchParams.delete('page'); params?.searchParams.delete('page');
const parameters = Object.fromEntries([ const parameters = Object.fromEntries([
...params.searchParams.entries(), ...(params?.searchParams.entries() as IterableIterator<[string, string]>),
['per_page', parseInt(event.target.value, 10)], ['per_page', parseInt(event.target.value, 10)],
]); ]);
paginations.setPage(0); paginations?.setPage(0);
paginations.setRowsPerPage(parseInt(event.target.value, 10)); paginations?.setRowsPerPage(parseInt(event.target.value, 10));
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
params.setAppliedParams(parameters); params?.setAppliedParams(parameters);
}; };
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
@@ -353,13 +353,15 @@ export default function Table<T>({
{/* End Table */} {/* End Table */}
{/* Pagination */} {/* Pagination */}
<BaseTablePagination {paginations && (
count={paginations.paginationTable.total} <BaseTablePagination
onPageChange={onPageChangeHandle} count={paginations.paginationTable.total}
page={paginations.page} onPageChange={onPageChangeHandle}
rowsPerPage={paginations.rowsPerPage} page={paginations.page}
onRowsPerPageChange={onRowsPerPageChangeHandle} rowsPerPage={paginations.rowsPerPage}
/> onRowsPerPageChange={onRowsPerPageChangeHandle}
/>
)}
{/* End Pagination */} {/* End Pagination */}
</Grid> </Grid>
{/* End Field 2 */} {/* End Field 2 */}

View File

@@ -1,139 +1,31 @@
/* ---------------------------------- react --------------------------------- */
import { useState, SyntheticEvent } from 'react';
/* ---------------------------------- @mui ---------------------------------- */ /* ---------------------------------- @mui ---------------------------------- */
import { Box, Tabs, Tab, Container, Grid, Card } from '@mui/material'; import { Container, Grid } from '@mui/material';
import { styled } from '@mui/material/styles';
/* ------------------------------- components ------------------------------- */ /* ------------------------------- components ------------------------------- */
import Page from '../../components/Page'; import Page from '../../components/Page';
/* ---------------------------------- hooks --------------------------------- */ /* ---------------------------------- hooks --------------------------------- */
import useSettings from '../../hooks/useSettings'; import useSettings from '../../hooks/useSettings';
import List from './List'; import List from './List';
import ServiceMonitoring from './ServiceMonitoring';
import UserProfile from './UserProfile';
import HeaderBreadcrumbs from '../../components/HeaderBreadcrumbs'; import HeaderBreadcrumbs from '../../components/HeaderBreadcrumbs';
import TableMoreMenu from '../../components/table/TableMoreMenu';
/* ------------------------------ tabs setting ------------------------------ */
/* ---------------------------------- types --------------------------------- */
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
interface StyledTabsProps {
children?: React.ReactNode;
value: number;
onChange: (event: React.SyntheticEvent, newValue: number) => void;
}
interface StyledTabProps {
label: string;
icon?: string | React.ReactElement;
}
/* -------------------------------- tab style ------------------------------- */
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && <Box>{children}</Box>}
</div>
);
}
function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
const StyledTabs = styled((props: StyledTabsProps) => <Tabs {...props} />)({
backgroundColor: '#F4F6F8',
padding: '0 24px',
'& .MuiTabs-indicator': {
display: 'flex',
justifyContent: 'space-between',
backgroundColor: 'transparent',
},
'& .MuiTabs-indicatorSpan': {
maxWidth: 40,
backgroundColor: '#635ee7',
},
});
const StyledTab = styled((props: StyledTabProps) => <Tab disableRipple {...props} />)(
({ theme }) => ({
textTransform: 'none',
fontWeight: 600,
color: theme.palette.grey[600],
marginRight: '5rem',
'&.Mui-selected': {
color: '#212B36',
borderBottom: '2px solid ' + theme.palette.primary.main,
},
'&:hover': {
color: '#212B36',
opacity: 1,
borderBottom: '2px solid ' + theme.palette.primary.main,
},
})
);
/* -------------------------------------------------------------------------- */
export default function Drugs() { export default function Drugs() {
const { themeStretch } = useSettings(); const { themeStretch } = useSettings();
const [value, setValue] = useState(0);
const handleChange = (event: SyntheticEvent, newValue: number) => {
setValue(newValue);
};
return ( return (
<Page title="Corporate"> <Page title="Corporate">
<Container maxWidth={themeStretch ? false : 'xl'}> <Container maxWidth={themeStretch ? false : 'xl'}>
<HeaderBreadcrumbs <HeaderBreadcrumbs
heading={'Corporate'} heading={'Corporate'}
links={[ links={[
{ name: 'Dashboard', href: '/dashboard' }, { name: 'Dashboard', href: '/dashboard' },
{ {
name: 'Corporates', name: 'Corporates',
href: '/corporates', href: '/corporates',
}, },
]} ]}
/> />
<Grid container> <Grid container>
<Grid item xs={12} lg={12} md={12}> <Grid item xs={12} lg={12} md={12}>
{/* <Card> */} <List />
{/* <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<StyledTabs value={value} onChange={handleChange} aria-label="basic tabs example">
<StyledTab label="All Data" {...a11yProps(0)} />
<StyledTab label="Ongoing" {...a11yProps(1)} />
<StyledTab label="Done" {...a11yProps(2)} />
</StyledTabs>
</Box> */}
{/* <TabPanel value={value} index={0}> */}
<List />
{/* </TabPanel> */}
{/* <TabPanel value={value} index={1}>
<ServiceMonitoring/>
</TabPanel>
<TabPanel value={value} index={2}>
<UserProfile />
</TabPanel> */}
{/* </Card> */}
</Grid> </Grid>
</Grid> </Grid>
</Container> </Container>

View File

@@ -1,21 +1,5 @@
/* ---------------------------------- @mui ---------------------------------- */ /* ---------------------------------- @mui ---------------------------------- */
import { import { Stack, Button, Typography, MenuItem } from '@mui/material';
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Stack,
Button,
TableSortLabel,
Typography,
Box,
MenuItem,
} from '@mui/material';
import { visuallyHidden } from '@mui/utils';
/* ---------------------------------- axios --------------------------------- */ /* ---------------------------------- axios --------------------------------- */
// import axios from 'axios'; // import axios from 'axios';
import axios from '../../utils/axios'; import axios from '../../utils/axios';
@@ -23,129 +7,19 @@ import axios from '../../utils/axios';
import { useContext, useEffect, useState } from 'react'; import { useContext, useEffect, useState } from 'react';
/* -------------------------------- component ------------------------------- */ /* -------------------------------- component ------------------------------- */
import Iconify from '../../components/Iconify';
import BaseTablePagination from '../../components/BaseTablePagination';
import TableComponent from '../../components/Table'; import TableComponent from '../../components/Table';
/* ---------------------------------- hooks --------------------------------- */
import useMap from '../../hooks/useMap';
/* ---------------------------------- theme --------------------------------- */ /* ---------------------------------- theme --------------------------------- */
import palette from '../../theme/palette';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate'; import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table'; import { HeadCell } from '../../@types/table';
import { useSearchParams, useNavigate, Link } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import TableMoreMenu from '../../components/table/TableMoreMenu'; import TableMoreMenu from '../../components/table/TableMoreMenu';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined'; import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined'; import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
/* ---------------------------------- types --------------------------------- */
// type PaginationTableProps = {
// current_page: number;
// from: number;
// last_page: number;
// links: [];
// path: string;
// per_page: number;
// to: number;
// total: number;
// };
// type DataTableProps = {
// fullName: string;
// memberId: string;
// service: string;
// start_date: string;
// end_date: string;
// status: boolean | number;
// };
// /* -------------------------------------------------------------------------- */
// /* -------------------------- enchanced table head -------------------------- */
// type Order = 'asc' | 'desc';
// interface HeadCell {
// id: string;
// label: string;
// }
// const headCells: readonly HeadCell[] = [
// {
// id: 'name',
// label: 'Name',
// },
// {
// id: 'member_id',
// label: 'Member ID',
// },
// {
// id: 'service',
// label: 'Service',
// },
// {
// id: 'start_date',
// label: 'Start Date',
// },
// {
// id: 'end_date',
// label: 'End Date',
// },
// {
// id: 'status',
// label: 'Status',
// },
// ];
// interface EnhancedTableProps {
// onRequestSort: (event: React.MouseEvent<unknown>, property: string) => void;
// order: Order;
// orderBy: string;
// }
// function EnhancedTableHead(props: EnhancedTableProps) {
// const { order, orderBy, onRequestSort } = props;
// const createSortHandler = (property: string) => (event: React.MouseEvent<unknown>) => {
// onRequestSort(event, property);
// };
// return (
// <TableHead>
// <TableRow>
// <TableCell align="center">No</TableCell>
// {headCells.map((headCell) => (
// <TableCell
// key={headCell.id}
// sortDirection={orderBy === headCell.id ? order : false}
// align="center"
// >
// <TableSortLabel
// active={orderBy === headCell.id}
// direction={orderBy === headCell.id ? order : 'asc'}
// onClick={createSortHandler(headCell.id)}
// >
// {headCell.label}
// {orderBy === headCell.id ? (
// <Box component="span" sx={visuallyHidden}>
// {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
// </Box>
// ) : null}
// </TableSortLabel>
// </TableCell>
// ))}
// </TableRow>
// </TableHead>
// );
// }
/* -------------------------------------------------------------------------- */
export default function List() { export default function List() {
const navigate = useNavigate(); const navigate = useNavigate();
const { corporateValue } = useContext(UserCurrentCorporateContext); const { corporateValue } = useContext(UserCurrentCorporateContext);
const controller = new AbortController();
const [data, setData] = useState([]); const [data, setData] = useState([]);
@@ -159,196 +33,101 @@ export default function List() {
setIsLoading: setIsLoading, setIsLoading: setIsLoading,
}; };
/* ------------------------------ handle params ----------------------------- */
const [searchParams, setSearchParams] = useSearchParams();
const [appliedParams, setAppliedParams] = useState({});
const params = {
searchParams: searchParams,
setSearchParams: setSearchParams,
appliedParams: appliedParams,
setAppliedParams: setAppliedParams,
};
/* -------------------------------------------------------------------------- */
/* ------------------------------ handle order ------------------------------ */
const [order, setOrder] = useState<Order>('asc');
const [orderBy, setOrderBy] = useState('fullName');
const orders = {
order: order,
setOrder: setOrder,
orderBy: orderBy,
setOrderBy: setOrderBy,
};
/* -------------------------------------------------------------------------- */
/* ---------------------------- handle pagination --------------------------- */
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [paginationTable, setPaginationTable] = useState<PaginationTableProps>({
current_page: 0,
from: 0,
last_page: 0,
links: [],
path: '',
per_page: 0,
to: 0,
total: 0,
});
const paginations = {
page: page,
setPage: setPage,
rowsPerPage: rowsPerPage,
setRowsPerPage: setRowsPerPage,
paginationTable: paginationTable,
setPaginationTable: setPaginationTable,
};
/* -------------------------------------------------------------------------- */
/* ------------------------------ handle search ----------------------------- */
const [searchText, setSearchText] = useState('');
const handleSearchSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (searchText === '') {
searchParams.delete('search');
const params = Object.fromEntries([...searchParams.entries()]);
setAppliedParams(params);
} else {
const params = Object.fromEntries([...searchParams.entries(), ['search', searchText]]);
setAppliedParams(params);
}
};
const searchs = {
useSearchs: false,
searchText: searchText,
setSearchText: setSearchText,
handleSearchSubmit: handleSearchSubmit,
};
/* -------------------------------- headCell -------------------------------- */ /* -------------------------------- headCell -------------------------------- */
const headCells: HeadCell<never>[] = [ const headCells: HeadCell<never>[] = [
{ {
id: 'code', id: 'code',
align: 'left', align: 'left',
label: 'Code', label: 'Code',
isSort: true, isSort: false,
}, },
{ {
id: 'name', id: 'name',
align: 'left', align: 'left',
label: 'Name', label: 'Name',
isSort: true, isSort: false,
}, },
{ {
id: 'active', id: 'active',
align: 'center', align: 'center',
label: 'Status', label: 'Status',
isSort: true, isSort: false,
}, },
{ {
id: 'action', id: 'action',
align: 'center', align: 'center',
label: '', label: '',
isSort: true, isSort: false,
}, },
]; ];
/* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */
useEffect(() => { useEffect(() => {
(async () => { (async () => {
setIsLoading(true); try {
setIsLoading(true);
await new Promise((resolve) => setTimeout(resolve, 250)); const [response] = await Promise.all([
axios.get(`${corporateValue}/corporate`, { signal: controller.signal }),
]);
const parameters = setData(
Object.keys(appliedParams).length !== 0 response.data.data.map((obj: any) => ({
? appliedParams
: Object.fromEntries([...searchParams.entries(), ['order', order], ['orderBy', orderBy]]);
const response = await axios.get(`${corporateValue}/corporate`, {
params: { ...parameters },
});
setData(
response.data.data.map((obj: any) => {
return {
...obj, ...obj,
active: active:
obj.active === 1 ? ( obj.active === 1 ? (
<Typography variant="overline" <Typography
sx={{ variant="overline"
backgroundColor: 'rgba(84, 214, 44, 0.16)', sx={{
color: '#229A16', backgroundColor: 'rgba(84, 214, 44, 0.16)',
paddingX: 1.5, color: '#229A16',
paddingY: 1, paddingX: 1.5,
display: 'inline-flex', // Mengatur elemen menjadi inline-flex paddingY: 1,
alignItems: 'center', // Untuk align vertical display: 'inline-flex',
borderRadius: '10px' alignItems: 'center',
, borderRadius: '10px',
}} }}
> >
Active Active
</Typography> </Typography>
) : ( ) : (
<Button variant="outlined" color="error"> <Button variant="outlined" color="error">
Inactive Inactive
</Button> </Button>
),
action: (
<TableMoreMenu
actions={
<>
<MenuItem onClick={() => navigate(`/corporate/edit`)}>
<EditOutlinedIcon />
Edit
</MenuItem>
<MenuItem onClick={() => navigate(`/corporate/view`)}>
<VisibilityOutlinedIcon />
View
</MenuItem>
</>
}
/>
), ),
action: }))
<TableMoreMenu actions={ );
<>
<MenuItem onClick={() => navigate(`/corporate/edit`)}>
<EditOutlinedIcon />
Edit
</MenuItem>
<MenuItem onClick={() => navigate(`/corporate/view`)}>
<VisibilityOutlinedIcon />
View
</MenuItem>
</>
} />
,
};
})
);
setPaginationTable(response.data); setIsLoading(false);
setRowsPerPage(response.data.per_page); } catch (error: any) {
console.error('Error fetching data:', error.message);
if (searchParams.get('page')) {
//@ts-ignore
const currentPage = parseInt(searchParams.get('page')) - 1;
paginationTable.current_page = currentPage;
setPage(currentPage);
} }
setIsLoading(false); return () => {
controller.abort();
};
})(); })();
}, [appliedParams, searchParams, order, orderBy, setSearchParams, corporateValue]); }, [corporateValue]);
return ( return (
<Stack> <Stack>
<TableComponent <TableComponent headCells={headCells} rows={data} loadings={loadings} />
headCells={headCells}
rows={data}
orders={orders}
paginations={paginations}
loadings={loadings}
params={params}
searchs={searchs}
// filters={filters}
/>
</Stack> </Stack>
); );
} }