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

View File

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

View File

@@ -1,139 +1,31 @@
/* ---------------------------------- react --------------------------------- */
import { useState, SyntheticEvent } from 'react';
/* ---------------------------------- @mui ---------------------------------- */
import { Box, Tabs, Tab, Container, Grid, Card } from '@mui/material';
import { styled } from '@mui/material/styles';
import { Container, Grid } from '@mui/material';
/* ------------------------------- components ------------------------------- */
import Page from '../../components/Page';
/* ---------------------------------- hooks --------------------------------- */
import useSettings from '../../hooks/useSettings';
import List from './List';
import ServiceMonitoring from './ServiceMonitoring';
import UserProfile from './UserProfile';
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() {
const { themeStretch } = useSettings();
const [value, setValue] = useState(0);
const handleChange = (event: SyntheticEvent, newValue: number) => {
setValue(newValue);
};
return (
<Page title="Corporate">
<Container maxWidth={themeStretch ? false : 'xl'}>
<HeaderBreadcrumbs
heading={'Corporate'}
links={[
{ name: 'Dashboard', href: '/dashboard' },
{
name: 'Corporates',
href: '/corporates',
},
]}
/>
heading={'Corporate'}
links={[
{ name: 'Dashboard', href: '/dashboard' },
{
name: 'Corporates',
href: '/corporates',
},
]}
/>
<Grid container>
<Grid item xs={12} lg={12} md={12}>
{/* <Card> */}
{/* <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> */}
<List />
</Grid>
</Grid>
</Container>

View File

@@ -1,21 +1,5 @@
/* ---------------------------------- @mui ---------------------------------- */
import {
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Stack,
Button,
TableSortLabel,
Typography,
Box,
MenuItem,
} from '@mui/material';
import { visuallyHidden } from '@mui/utils';
import { Stack, Button, Typography, MenuItem } from '@mui/material';
/* ---------------------------------- axios --------------------------------- */
// import axios from 'axios';
import axios from '../../utils/axios';
@@ -23,129 +7,19 @@ import axios from '../../utils/axios';
import { useContext, useEffect, useState } from 'react';
/* -------------------------------- component ------------------------------- */
import Iconify from '../../components/Iconify';
import BaseTablePagination from '../../components/BaseTablePagination';
import TableComponent from '../../components/Table';
/* ---------------------------------- hooks --------------------------------- */
import useMap from '../../hooks/useMap';
/* ---------------------------------- theme --------------------------------- */
import palette from '../../theme/palette';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams, useNavigate, Link } from 'react-router-dom';
import { HeadCell } from '../../@types/table';
import { useNavigate } from 'react-router-dom';
import TableMoreMenu from '../../components/table/TableMoreMenu';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
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() {
const navigate = useNavigate();
const { corporateValue } = useContext(UserCurrentCorporateContext);
const controller = new AbortController();
const [data, setData] = useState([]);
@@ -159,196 +33,101 @@ export default function List() {
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 -------------------------------- */
const headCells: HeadCell<never>[] = [
{
id: 'code',
align: 'left',
label: 'Code',
isSort: true,
isSort: false,
},
{
id: 'name',
align: 'left',
label: 'Name',
isSort: true,
isSort: false,
},
{
id: 'active',
align: 'center',
label: 'Status',
isSort: true,
isSort: false,
},
{
id: 'action',
align: 'center',
label: '',
isSort: true,
isSort: false,
},
];
/* -------------------------------------------------------------------------- */
useEffect(() => {
(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 =
Object.keys(appliedParams).length !== 0
? 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 {
setData(
response.data.data.map((obj: any) => ({
...obj,
active:
obj.active === 1 ? (
<Typography variant="overline"
sx={{
backgroundColor: 'rgba(84, 214, 44, 0.16)',
color: '#229A16',
paddingX: 1.5,
paddingY: 1,
display: 'inline-flex', // Mengatur elemen menjadi inline-flex
alignItems: 'center', // Untuk align vertical
borderRadius: '10px'
,
}}
>
Active
</Typography>
) : (
<Button variant="outlined" color="error">
Inactive
</Button>
obj.active === 1 ? (
<Typography
variant="overline"
sx={{
backgroundColor: 'rgba(84, 214, 44, 0.16)',
color: '#229A16',
paddingX: 1.5,
paddingY: 1,
display: 'inline-flex',
alignItems: 'center',
borderRadius: '10px',
}}
>
Active
</Typography>
) : (
<Button variant="outlined" color="error">
Inactive
</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);
setRowsPerPage(response.data.per_page);
if (searchParams.get('page')) {
//@ts-ignore
const currentPage = parseInt(searchParams.get('page')) - 1;
paginationTable.current_page = currentPage;
setPage(currentPage);
setIsLoading(false);
} catch (error: any) {
console.error('Error fetching data:', error.message);
}
setIsLoading(false);
return () => {
controller.abort();
};
})();
}, [appliedParams, searchParams, order, orderBy, setSearchParams, corporateValue]);
}, [corporateValue]);
return (
<Stack>
<TableComponent
headCells={headCells}
rows={data}
orders={orders}
paginations={paginations}
loadings={loadings}
params={params}
searchs={searchs}
// filters={filters}
/>
<TableComponent headCells={headCells} rows={data} loadings={loadings} />
</Stack>
);
}