Merge remote-tracking branch 'origin/staging' into origin/production

This commit is contained in:
Linksehat Staging Server
2024-06-20 16:10:13 +07:00
309 changed files with 1622 additions and 1651 deletions

View File

@@ -32,18 +32,16 @@ export default function NavSectionVertical({
<Box {...other}>
{navConfig.map((group, index) => (
<List key={index} disablePadding sx={{ px: 2 }}>
{group.subheader && (
<ListSubheaderStyle
key={index}
sx={{
...(isCollapse && {
opacity: 0,
}),
}}
>
{group.subheader}
</ListSubheaderStyle>
)}
<ListSubheaderStyle
key={index}
sx={{
...(isCollapse && {
opacity: 0,
}),
}}
>
{group.subheader}
</ListSubheaderStyle>
{group.items.map((list) => (
<NavListRoot key={list.title} list={list} isCollapse={isCollapse} />

View File

@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
// @mui
import { styled, useTheme } from '@mui/material/styles';
@@ -15,9 +15,11 @@ import Logo from '../../../components/Logo';
import Scrollbar from '../../../components/Scrollbar';
import { NavSectionVertical } from '../../../components/nav-section';
//
import navConfig from './NavConfig';
// import navConfig from './NavConfig';
import NavbarAccount from './NavbarAccount';
import CollapseButton from './CollapseButton';
import useAuth from '@/hooks/useAuth';
import axios from '@/utils/axios';
// ----------------------------------------------------------------------
@@ -42,10 +44,54 @@ export default function NavbarVertical({ isOpenSidebar, onCloseSidebar }: Props)
const { pathname } = useLocation();
const {user} = useAuth()
const isDesktop = useResponsive('up', 'lg');
const { isCollapse, collapseClick, collapseHover, onToggleCollapse, onHoverEnter, onHoverLeave } =
useCollapseDrawer();
const [navConfig, setNavConfig] = useState([]);
useEffect(() => {
const fetchNavConfig = async () => {
try {
const response = await axios.get('/navigations');
const data = response.data.items;
// Pastikan user dan user.permissions terdefinisi dan merupakan array
const userPermissions = user.user?.permissions?.map(permission => permission.name) || [];
// Fungsi untuk memeriksa apakah pengguna memiliki izin untuk item tertentu
const hasPermission = (permission) => {
return userPermissions.includes(permission);
};
// Filter data berdasarkan izin pengguna
const filteredNavConfig = data.map(section => {
if (section.children && section.children.length > 0) {
// Cek apakah ada satu atau lebih children yang memiliki izin
const filteredChildren = section.children.filter(child => hasPermission(child.permission));
if (filteredChildren.length > 0) {
return {
...section,
children: filteredChildren
};
} else {
return null; // Lewati bagian yang tidak memiliki children dengan izin
}
}
// Jika tidak ada children, cek izin untuk section itu sendiri
return hasPermission(section.permission) ? section : null;
}).filter(section => section !== null);
setNavConfig([{ items: filteredNavConfig }]);
} catch (error) {
console.error('Gagal mengambil konfigurasi navigasi:', error);
}
};
fetchNavConfig();
}, [user]);
useEffect(() => {
if (isOpenSidebar) {

View File

@@ -20,11 +20,14 @@ import {
ListItemText,
ListItemButton,
Divider,
CardContent,
LinearProgress
} from '@mui/material';
import { styled } from '@mui/material/styles';
import { Download as DownloadIcon, Circle as CircleIcon, TableView } from '@mui/icons-material';
// components
import Page from '../../components/Page';
import { fCurrency } from '../../utils/formatNumber';
// utils
import { useState, SyntheticEvent, useContext, useEffect } from 'react';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
@@ -45,6 +48,8 @@ import TableMoreMenu from '../../components/table/TableMoreMenu';
import Label from '../../components/Label';
import { fSplit } from '../../utils/formatNumber';
import useAuth from '../../hooks/useAuth';
interface TabPanelProps {
children?: React.ReactNode;
index: number;
@@ -208,6 +213,13 @@ type ServiceMonitoringProps = {
};
export default function ServiceMonitoring() {
const {user} = useAuth();
const checkIfNameExists = (name) => {
return user.user.permissions.some(item => item.name === name);
};
const nameToCheck = 'service-monitoring-limit-client-portal';
const doesNameExist = checkIfNameExists(nameToCheck);
const navigate = useNavigate();
const controller = new AbortController();
@@ -221,7 +233,7 @@ export default function ServiceMonitoring() {
const { corporateValue } = useContext(UserCurrentCorporateContext);
const { memberId, requestLogId } = useParams();
const [depositData, setDepositData] = useState({ deposit: 0, limit: 0, usage: 0 });
useEffect(() => {
(async () => {
try {
@@ -236,6 +248,18 @@ export default function ServiceMonitoring() {
if (response.data.data.serviceCode !== 'IP') {
setValue(1);
}
var member_id = response.data.data.member_id;
const fetchDepositData = async () => {
try {
const response = await axios.get(`${corporateValue}/get-limits/${member_id}`);
setDepositData(response.data);
} catch (error) {
console.error('Failed to fetch deposit data:', error);
}
};
fetchDepositData();
} catch (error: any) {
console.error('Error fetching data:', error.message);
} finally {
@@ -248,7 +272,7 @@ export default function ServiceMonitoring() {
};
}, [corporateValue]);
const renderHTML = (data:string) => {
return (
<div style={{marginLeft: 20}}
@@ -256,7 +280,32 @@ export default function ServiceMonitoring() {
/>
);
}
const formatNumber = (number) => {
return new Intl.NumberFormat('id-ID').format(number);
};
const LimitPlanCard = ({ title, current, total }) => (
<Card variant="outlined" sx={{ minWidth: 200, m: 1 }}>
<CardContent>
<Typography variant="h6" component="div">
{title}
</Typography>
<Typography variant="subtitle2" color="text.secondary">
Yearly Limits
</Typography>
<Typography variant="subtitle1">
{formatNumber(current)} / {formatNumber(total)}
</Typography>
<LinearProgress variant="determinate" value={(current / total) * 100} />
</CardContent>
</Card>
);
const plans = [
{ title: 'Outpatient', current: 200000, total: 1000000 },
{ title: 'Inpatient', current: 1000000, total: 5000000 },
{ title: 'Dental', current: 250000, total: 1000000 },
{ title: 'Maternity', current: 0, total: 3000000 },
];
return (
<Page title="Service Monitoring">
@@ -277,14 +326,14 @@ export default function ServiceMonitoring() {
<Grid item xs={12}>
<Card sx={{ borderRadius: 2, padding: 3 }}>
<Grid container spacing={5}>
<Grid item xs={12}>
<Typography component={'h6'} fontWeight={700} fontSize={18}>
{loading ? <Skeleton animation="wave" width={175} /> : 'Employee Profile'}
</Typography>
</Grid>
<Grid item xs={12} container spacing={3}>
<Grid item container spacing={3}>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Grid item xs={12}>
<Typography component={'h6'} fontWeight={700} fontSize={18}>
{loading ? <Skeleton animation="wave" width={175} /> : 'Employee Profile'}
</Typography>
</Grid>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Company Name'}
</Typography>
@@ -300,8 +349,6 @@ export default function ServiceMonitoring() {
)}
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Member ID'}
@@ -318,8 +365,6 @@ export default function ServiceMonitoring() {
)}
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Full Name'}
@@ -336,8 +381,6 @@ export default function ServiceMonitoring() {
)}
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Date of Birth'}
@@ -354,8 +397,6 @@ export default function ServiceMonitoring() {
)}
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Phone Number'}
@@ -372,8 +413,6 @@ export default function ServiceMonitoring() {
)}
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
<Grid item xs={12}>
<Typography variant="subtitle2" color={'grey.600'}>
{loading ? <Skeleton animation={'wave'} width={200} /> : 'Email'}
@@ -391,6 +430,43 @@ export default function ServiceMonitoring() {
</Typography>
</Grid>
</Grid>
<Grid item container xs={12} md={6} spacing={1.5}>
{doesNameExist ? (
<Stack direction="column" style={{width:'100%'}}>
<Box flexWrap="wrap" justifyContent="left">
<Card variant="outlined" sx={{ minWidth: 200, marginBottom: 1, borderRadius: 2, padding: 0 }}>
<CardContent>
<Typography variant="h6" component="div">
Total Limit
</Typography>
<Typography variant="subtitle2" color="text.secondary">
Yearly Limits
</Typography>
<Typography variant="subtitle1">
{formatNumber(depositData.usage)} / {formatNumber(depositData.deposit)}
</Typography>
<LinearProgress variant="determinate" value={(depositData.usage / depositData.deposit) * 100} />
</CardContent>
</Card>
</Box>
<Card sx={{ borderRadius: 2, padding: 3 }}>
<Typography component={'h6'} fontWeight={700} fontSize={18}>
Limit Plan
</Typography>
<Box display="flex" flexWrap="wrap" justifyContent="left">
{depositData.services?.map((plan) => (
<LimitPlanCard
key={plan.title}
title={plan.title}
current={plan.current}
total={plan.total}
/>
))}
</Box>
</Card>
</Stack>
) : ''}
</Grid>
</Grid>
<Grid item xs={12} paddingY={2}>
<Typography component={'h6'} fontWeight={700} fontSize={18}>
@@ -400,7 +476,7 @@ export default function ServiceMonitoring() {
</Grid>
</Card>
</Grid>
<Grid item container xs={12} spacing={5}>
<Grid item container xs={12} md={6}>
@@ -501,9 +577,9 @@ export default function ServiceMonitoring() {
<Grid item>
{loading ? (
<Skeleton animation="wave" width={300} />
) : data && data.files && data.files.result.length > 0 ?
) : data && data.files && data.files.result.length > 0 ?
(
data.files.result.map((file, index) =>
data.files.result.map((file, index) =>
(
(
<Stack direction="column" spacing={2} key={index}>
@@ -539,9 +615,9 @@ export default function ServiceMonitoring() {
<Grid item>
{loading ? (
<Skeleton animation="wave" width={300} />
) : data && data.files && data.files.diagnosis.length > 0 ?
) : data && data.files && data.files.diagnosis.length > 0 ?
(
data.files.diagnosis.map((file, index) =>
data.files.diagnosis.map((file, index) =>
(
(
<Stack direction="column" spacing={2} key={index}>
@@ -577,9 +653,9 @@ export default function ServiceMonitoring() {
{/* <Grid item>
{loading ? (
<Skeleton animation="wave" width={300} />
) : data && data.files && data.files.kondisi.length > 0 ?
) : data && data.files && data.files.kondisi.length > 0 ?
(
data.files.kondisi.map((file, index) =>
data.files.kondisi.map((file, index) =>
(
(
<Stack direction="column" spacing={2} key={index}>
@@ -1180,7 +1256,7 @@ export default function ServiceMonitoring() {
{file.original_name}
</a>
</li>
)
)
)
) : (
<li>-</li>
@@ -1259,7 +1335,7 @@ export default function ServiceMonitoring() {
{file.original_name}
</a>
</li>
)
)
)
) : (
<li>-</li>

View File

@@ -1,278 +1,174 @@
// @mui
import { Typography, Container, Grid, Button, SelectChangeEvent } from '@mui/material';
import { Box,CardContent,Button, Container, Grid, styled, Typography, Card, Stack } from '@mui/material';
// hooks
import useSettings from '../../hooks/useSettings';
// components
import Page from '../../components/Page';
// theme
import { useContext, useEffect, useState } from 'react';
import axios from '../../utils/axios';
import { Stack } from '@mui/system';
import useAuth from '../../hooks/useAuth';
import SomethingUsage from '../../sections/dashboard/SomethingUsage';
import { fCurrency } from '../../utils/formatNumber';
import AccountBalanceWalletIcon from '@mui/icons-material/AccountBalanceWallet';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import MonetizationOnIcon from '@mui/icons-material/MonetizationOn';
import { useContext, useEffect, useState } from 'react';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import Table from '../../components/Table';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams } from 'react-router-dom';
import palette from '../../theme/palette';
export default function Index() {
import { useNavigate, useParams } from 'react-router-dom';
// ----------------------------------------------------------------------
export default function Dashboard() {
const navigate = useNavigate();
const { themeStretch } = useSettings();
const { corporateValue } = useContext(UserCurrentCorporateContext);
const controller = new AbortController();
const [memberData, setMemberData] = useState([]);
const { user } = useAuth();
/* -------------------------------------------------------------------------- */
/* setting up for the table */
/* -------------------------------------------------------------------------- */
const [isLoading, setIsLoading] = useState(true);
const loadings = {
isLoading: isLoading,
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,
};
/* -------------------------------------------------------------------------- */
/* ------------------------------ handle filter ----------------------------- */
const [divisionValue, setDivisionValue] = useState('all');
const [divisionData, setDivisionData] = useState([]);
const handleDivisionChange = (event: SelectChangeEvent) => {
setDivisionValue(event.target.value as string);
if (event.target.value === 'all') {
searchParams.delete('division');
const params = Object.fromEntries([...searchParams.entries()]);
setAppliedParams(params);
} else {
const params = Object.fromEntries([
...searchParams.entries(),
['division', event.target.value as string],
]);
setAppliedParams(params);
}
};
const filters = {
useFilter: true,
config: {
label: 'Division',
divisionValue: divisionValue,
divisionData: divisionData,
handleDivisionChange: handleDivisionChange,
},
};
/* -------------------------------------------------------------------------- */
/* -------------------------------- headCell -------------------------------- */
const headCells: HeadCell<never>[] = [
{
id: 'memberId',
align: 'left',
label: 'Member ID',
isSort: true,
},
{
id: 'fullName',
align: 'center',
label: 'Name',
isSort: true,
},
{
id: 'division',
align: 'center',
label: 'Divisi',
isSort: true,
},
{
id: 'status',
align: 'center',
label: 'Status',
isSort: true,
},
{
id: 'action',
align: 'right',
label: '',
isSort: false,
},
];
/* -------------------------------------------------------------------------- */
useEffect(() => {
(async () => {
try {
setIsLoading(true);
const parameters =
Object.keys(appliedParams).length !== 0
? appliedParams
: Object.fromEntries([
...searchParams.entries(),
['order', order],
['orderBy', orderBy],
]);
const [divisionResponse, membersResponse] = await Promise.all([
axios.get(`${corporateValue}/division`, { signal: controller.signal }),
axios.get(`${corporateValue}/members`, {
params: { ...parameters },
signal: controller.signal,
}),
]);
setSearchParams(parameters);
setDivisionData(divisionResponse.data);
setMemberData(
membersResponse.data.data.map((obj: any) => ({
...obj,
status:
obj.status === 1 ? (
<Button
sx={{
backgroundColor: 'rgba(84, 214, 44, 0.16)',
color: palette.dark.success.dark,
paddingY: 0,
'&:hover': {
backgroundColor: 'rgba(84, 214, 44, 0.32)',
color: palette.dark.success.darker,
},
}}
>
Active
</Button>
) : (
<Button
sx={{
backgroundColor: 'rgba(255, 72, 66, 0.16)',
color: palette.dark.error.dark,
paddingY: 0,
'&:hover': {
backgroundColor: 'rgba(255, 72, 66, 0.32)',
color: palette.dark.error.darker,
},
}}
>
Inactive
</Button>
),
}))
);
setPaginationTable(membersResponse.data);
setRowsPerPage(membersResponse.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);
}
})();
return () => {
controller.abort();
const checkIfNameExists = (name) => {
return user.user.permissions.some(item => item.name === name);
};
}, [appliedParams, searchParams, order, orderBy, setSearchParams, corporateValue]);
const nameToCheck = 'dashboard-list-client-portal';
const doesNameExist = checkIfNameExists(nameToCheck);
useEffect(() => {
const doesNameExist = checkIfNameExists(nameToCheck);
if (!doesNameExist) {
navigate('/corporate');
}
}, [nameToCheck, user, navigate]);
// const loadSomething = () => {
// axios.get('/user')
// };
const Wallet = styled(AccountBalanceWalletIcon)(({ theme }) => ({
color: 'orange',
marginRight: theme.spacing(1),
}));
const TrendUp = styled(TrendingUpIcon)(({ theme }) => ({
color: 'blue',
marginRight: theme.spacing(1),
}));
const Monet = styled(MonetizationOnIcon)(({ theme }) => ({
color: 'orange',
marginRight: theme.spacing(1),
}));
const DangerCard = styled(Card)(({ theme }) => ({
boxShadow: 'none',
padding: theme.spacing(3),
color: theme.palette.error.main,
backgroundColor: theme.palette.error.lighter,
}));
const SuccessCard = styled(Card)(({ theme }) => ({
boxShadow: 'none',
padding: theme.spacing(3),
color: theme.palette.success.darker,
backgroundColor: theme.palette.success.lighter,
}));
const DefaultCard = styled(Card)(({ theme }) => ({
boxShadow: theme.shadows[3], // Menggunakan bayangan standar dari tema
padding: theme.spacing(3),
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper, // Latar belakang putih
}));
const { corporateValue } = useContext(UserCurrentCorporateContext);
const [depositData, setDepositData] = useState({ deposit: 0, limit: 0, usage: 0 });
useEffect(() => {
const fetchDepositData = async () => {
try {
const response = await axios.get(`${corporateValue}/get-deposits`);
setDepositData(response.data);
} catch (error) {
console.error('Failed to fetch deposit data:', error);
}
};
fetchDepositData();
}, [corporateValue]);
const handleGoBack = () => {
// Logic untuk kembali ke halaman sebelumnya atau halaman utama
navigate('/corporate')
};
return (
<Page title="Dashboard">
<Container maxWidth={themeStretch ? false : 'xl'}>
<Stack direction="row" justifyContent="space-between">
<Typography variant="h3" component="h1" paragraph>
Dashboard
</Typography>
</Stack>
<Typography variant="h3" component="h1" paragraph>
Dashboard
</Typography>
{doesNameExist ? (
<Grid container spacing={2}>
<Grid item xs={4}>
{/* <SomethingUsage /> */}
<DefaultCard>
<CardContent>
<Stack direction="column" alignItems="flex-start" justifyContent="space-between" sx={{ mb: 0.6 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ width: '100%' }}>
<Typography variant='h4'>{fCurrency(depositData.deposit)}</Typography>
<Wallet />
</Stack>
<Typography variant='h6'>Deposit</Typography>
</Stack>
</CardContent>
</DefaultCard>
</Grid>
<Grid item xs={4}>
<DefaultCard>
<CardContent>
<Stack direction="column" alignItems="flex-start" justifyContent="space-between" sx={{ mb: 0.6 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ width: '100%' }}>
<Typography variant='h4'>{fCurrency(depositData.limit)}</Typography>
<TrendUp />
</Stack>
<Typography variant='h6'>Limit</Typography>
</Stack>
</CardContent>
</DefaultCard>
</Grid>
<Grid item xs={4}>
<DefaultCard>
<CardContent>
<Stack direction="column" alignItems="flex-start" justifyContent="space-between" sx={{ mb: 0.6 }}>
<Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ width: '100%' }}>
<Typography variant='h4'>{fCurrency(depositData.usage)}</Typography>
<Monet />
</Stack>
<Typography variant='h6'>This Year Usage</Typography>
</Stack>
</CardContent>
</DefaultCard>
</Grid>
</Grid>
):(
<Box
display="flex"
flexDirection="column"
alignItems="center"
justifyContent="center"
minHeight="55vh"
textAlign="center"
padding={2}
>
<Typography variant="body1" color="textSecondary" paragraph>
Maaf, halaman ini tidak bisa diakses atau tidak ada.
</Typography>
<Button variant="contained" color="primary" onClick={handleGoBack}>
Kembali
</Button>
</Box>
)}
<Grid container spacing={2}>
<Grid item xs={12} lg={12} md={12}>
<Table
headCells={headCells}
rows={memberData}
orders={orders}
paginations={paginations}
loadings={loadings}
params={params}
searchs={searchs}
filters={filters}
/>
</Grid>
</Grid>
</Container>
</Page>
);

View File

@@ -0,0 +1,279 @@
// @mui
import { Typography, Container, Grid, Button, SelectChangeEvent } from '@mui/material';
// hooks
import useSettings from '../../hooks/useSettings';
// components
import Page from '../../components/Page';
// theme
import { useContext, useEffect, useState } from 'react';
import axios from '../../utils/axios';
import { Stack } from '@mui/system';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import Table from '../../components/Table';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams } from 'react-router-dom';
import palette from '../../theme/palette';
export default function Index_() {
const { themeStretch } = useSettings();
const { corporateValue } = useContext(UserCurrentCorporateContext);
const controller = new AbortController();
const [memberData, setMemberData] = useState([]);
/* -------------------------------------------------------------------------- */
/* setting up for the table */
/* -------------------------------------------------------------------------- */
const [isLoading, setIsLoading] = useState(true);
const loadings = {
isLoading: isLoading,
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,
};
/* -------------------------------------------------------------------------- */
/* ------------------------------ handle filter ----------------------------- */
const [divisionValue, setDivisionValue] = useState('all');
const [divisionData, setDivisionData] = useState([]);
const handleDivisionChange = (event: SelectChangeEvent) => {
setDivisionValue(event.target.value as string);
if (event.target.value === 'all') {
searchParams.delete('division');
const params = Object.fromEntries([...searchParams.entries()]);
setAppliedParams(params);
} else {
const params = Object.fromEntries([
...searchParams.entries(),
['division', event.target.value as string],
]);
setAppliedParams(params);
}
};
const filters = {
useFilter: true,
config: {
label: 'Division',
divisionValue: divisionValue,
divisionData: divisionData,
handleDivisionChange: handleDivisionChange,
},
};
/* -------------------------------------------------------------------------- */
/* -------------------------------- headCell -------------------------------- */
const headCells: HeadCell<never>[] = [
{
id: 'memberId',
align: 'left',
label: 'Member ID',
isSort: true,
},
{
id: 'fullName',
align: 'center',
label: 'Name',
isSort: true,
},
{
id: 'division',
align: 'center',
label: 'Divisi',
isSort: true,
},
{
id: 'status',
align: 'center',
label: 'Status',
isSort: true,
},
{
id: 'action',
align: 'right',
label: '',
isSort: false,
},
];
/* -------------------------------------------------------------------------- */
useEffect(() => {
(async () => {
try {
setIsLoading(true);
const parameters =
Object.keys(appliedParams).length !== 0
? appliedParams
: Object.fromEntries([
...searchParams.entries(),
['order', order],
['orderBy', orderBy],
]);
const [divisionResponse, membersResponse] = await Promise.all([
axios.get(`${corporateValue}/division`, { signal: controller.signal }),
axios.get(`${corporateValue}/members`, {
params: { ...parameters },
signal: controller.signal,
}),
]);
setSearchParams(parameters);
setDivisionData(divisionResponse.data);
setMemberData(
membersResponse.data.data.map((obj: any) => ({
...obj,
status:
obj.status === 1 ? (
<Button
sx={{
backgroundColor: 'rgba(84, 214, 44, 0.16)',
color: palette.dark.success.dark,
paddingY: 0,
'&:hover': {
backgroundColor: 'rgba(84, 214, 44, 0.32)',
color: palette.dark.success.darker,
},
}}
>
Active
</Button>
) : (
<Button
sx={{
backgroundColor: 'rgba(255, 72, 66, 0.16)',
color: palette.dark.error.dark,
paddingY: 0,
'&:hover': {
backgroundColor: 'rgba(255, 72, 66, 0.32)',
color: palette.dark.error.darker,
},
}}
>
Inactive
</Button>
),
}))
);
setPaginationTable(membersResponse.data);
setRowsPerPage(membersResponse.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);
}
})();
return () => {
controller.abort();
};
}, [appliedParams, searchParams, order, orderBy, setSearchParams, corporateValue]);
return (
<Page title="Dashboard">
<Container maxWidth={themeStretch ? false : 'xl'}>
<Stack direction="row" justifyContent="space-between">
<Typography variant="h3" component="h1" paragraph>
Dashboard
</Typography>
</Stack>
<Grid container spacing={2}>
<Grid item xs={12} lg={12} md={12}>
<Table
headCells={headCells}
rows={memberData}
orders={orders}
paginations={paginations}
loadings={loadings}
params={params}
searchs={searchs}
filters={filters}
/>
</Grid>
</Grid>
</Container>
</Page>
);
}

View File

@@ -9,7 +9,10 @@ import Iconify from '../../components/Iconify';
import useLocalStorage from '../../hooks/useLocalStorage';
/* -------------------------------- sections -------------------------------- */
import { LoginEmailForm, LoginPhoneForm, VerifyCodeForm } from '../../sections/auth/login';
import React, { useState, useEffect } from 'react';
import axios from '../../utils/axios';
import { enqueueSnackbar } from 'notistack';
/* --------------------------------- styled --------------------------------- */
const RootStyle = styled('div')(({ theme }) => ({
@@ -36,6 +39,46 @@ export default function Login() {
const [emailOrPhoneForm, setEmailOrPhoneForm] = useLocalStorage('emailOrPhoneForm', false);
const [loginOrVerifyCode, setLoginOrVerifyCode] = useLocalStorage('loginOrVerifyCode', false);
const [lastSentTime, setLastSentTime] = useState(null);
const [canSendOTP, setCanSendOTP] = useState(true);
useEffect(() => {
let timer;
if (lastSentTime) {
timer = setInterval(() => {
const timeDiff = Math.floor((new Date() - lastSentTime) / 1000);
if (timeDiff >= 60) {
setCanSendOTP(true);
clearInterval(timer);
}
}, 1000);
}
return () => clearInterval(timer);
}, [lastSentTime]);
const sendOTP = (phoneOrEmail: string) => {
if (canSendOTP) {
// Logic untuk mengirim OTP
axios
.post('/login', { phoneOrEmail })
.then(() => {
enqueueSnackbar('Kode OTP telah dikirim, silahkan cek email dan spam folder', {
variant: 'success',
autoHideDuration: 5000,
});
})
.catch((error) => {
if (error.response.status !== 404) throw error.response;
if (error.response.status !== 422) throw error.response;
});
setLastSentTime(new Date());
setCanSendOTP(false);
} else {
alert('You can only send OTP once every minute.');
}
}
return (
<Page title="Login">
<RootStyle>
@@ -87,7 +130,12 @@ export default function Login() {
<Stack sx={{ marginTop: 5 }} spacing={1} alignItems="center">
<Typography>Tidak mendapatkan kode?</Typography>
<Link sx={{ cursor: 'pointer' }}>Kirim Ulang Kode OTP</Link>
<Link
sx={{ cursor: 'pointer' }}
onClick={() => {
sendOTP(emailOrPhone);
}}
>Kirim Ulang Kode OTP</Link>
</Stack>
</>
) : (
@@ -118,7 +166,7 @@ export default function Login() {
</>
)}
<Divider sx={{ marginTop: 5 }}>Atau</Divider>
{/* <Divider sx={{ marginTop: 5 }}>Atau</Divider>
<Stack sx={{ marginTop: 5 }}>
{emailOrPhoneForm ? (
@@ -148,7 +196,7 @@ export default function Login() {
Masuk menggunakan nomor handphone
</Link>
)}
</Stack>
</Stack> */}
</Grid>
</Grid>
</ContentStyle>

View File

@@ -57,9 +57,9 @@ export default function LoginForm({ setEmailOrPhone, setLoginOrVerifyCode }: Log
setEmailOrPhone(data.email);
setLoginOrVerifyCode(true);
reset();
enqueueSnackbar('Kode OTP telah dikirim, silahkan cek email yang login', {
enqueueSnackbar('Kode OTP telah dikirim, silahkan cek email dan spam folder', {
variant: 'success',
autoHideDuration: 2000,
autoHideDuration: 5000,
});
} catch (error: any) {
reset();

View File

@@ -0,0 +1,80 @@
import merge from 'lodash/merge';
import ReactApexChart from 'react-apexcharts';
// @mui
import { styled } from '@mui/material/styles';
import { Card, Typography, Stack } from '@mui/material';
// utils
import { fCurrency, fPercent } from '../../utils/formatNumber';
// components
import Iconify from '../../components/Iconify';
import BaseOptionChart from '../../components/chart/BaseOptionChart';
// ----------------------------------------------------------------------
const RootStyle = styled(Card)(({ theme }) => ({
boxShadow: 'none',
padding: theme.spacing(3),
color: theme.palette.primary.darker,
backgroundColor: theme.palette.primary.lighter,
}));
// ----------------------------------------------------------------------
const INITIAL = 500000000
const TOTAL = 257907000;
const PERCENT = -3;
const CHART_DATA = [{ data: [100, 99, 99, 85, 74, 57, 54, 51] }];
export default function SomethingUsage() {
const chartOptions = merge(BaseOptionChart(), {
chart: { sparkline: { enabled: true } },
xaxis: { labels: { show: true } },
yaxis: { labels: { show: false } },
stroke: { width: 4 },
legend: { show: false },
grid: { show: false },
tooltip: {
marker: { show: false },
y: {
formatter: (seriesName: string) => (seriesName) + "%",
title: {
formatter: () => '',
},
},
},
fill: { gradient: { opacityFrom: 0, opacityTo: 0 } },
});
return (
<RootStyle>
<Stack direction="row" justifyContent="space-between" sx={{ mb: 3 }}>
<div>
<Typography variant="body2" component="span" sx={{ opacity: 0.72 }}>
{fCurrency(INITIAL)}
</Typography>
<Typography sx={{ typography: 'subtitle2' }}>Remaining Balance</Typography>
<Typography sx={{ typography: 'h3' }}>{fCurrency(TOTAL)}</Typography>
</div>
<div>
<Stack direction="row" alignItems="center" justifyContent="flex-end" sx={{ mb: 0.6 }}>
<Iconify
width={20}
height={20}
icon={PERCENT >= 0 ? 'eva:trending-up-fill' : 'eva:trending-down-fill'}
/>
<Typography variant="subtitle2" component="span" sx={{ ml: 0.5 }}>
{PERCENT > 0 && '+'}
{fPercent(PERCENT)}
</Typography>
</Stack>
<Typography variant="body2" component="span" sx={{ opacity: 0.72 }}>
&nbsp;than last month
</Typography>
</div>
</Stack>
<ReactApexChart type="area" series={CHART_DATA} options={chartOptions} height={100} />
</RootStyle>
);
}

View File

@@ -37,6 +37,17 @@ export default function PlanCreate() {
axios.get('/user/role/'+id)
.then((res) => {
setCurrentUserRole(res.data);
axios.get('/permission_list?guard_name='+res.data.guard_name)
.then((res) => {
setPermissions(res.data);
})
.catch((err) => {
if (err.response && err.response.status === 404) {
navigate('/404');
} else {
console.error('Error fetching permissions:', err);
}
});
})
.catch((err) => {
if (err.response.status === 404) {
@@ -44,17 +55,7 @@ export default function PlanCreate() {
}
})
}
axios.get('/permission_list')
.then((res) => {
setPermissions(res.data);
})
.catch((err) => {
if (err.response && err.response.status === 404) {
navigate('/404');
} else {
console.error('Error fetching permissions:', err);
}
});
}, [corporate_id, id]);

View File

@@ -27,6 +27,8 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
const { enqueueSnackbar } = useSnackbar();
const navigate = useNavigate();
const { corporate_id } = useParams();
const [guardName, setGuardName] = useState(currentUserRole?.guard_name || '');
const [filteredPermissions, setFilteredPermissions] = useState(permissions);
const NewUserRoleSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
@@ -37,7 +39,7 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
name: currentUserRole?.name || '',
guard_name: currentUserRole?.guard_name || '',
permission_check: currentUserRole?.permissions?.map(permission => permission.id) || []
}),
[currentUserRole, permissions]
);
@@ -55,7 +57,7 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
resolver: yupResolver(NewUserRoleSchema),
defaultValues,
});
const {
reset,
watch,
@@ -122,6 +124,27 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
}
};
useEffect(() => {
// Fetch permissions based on guard_name
if (guardName) {
axios.get(`/permission_list?guard_name=${guardName}`)
.then((res) => {
setFilteredPermissions(res.data);
})
.catch((err) => {
console.error('Error fetching permissions:', err);
});
} else {
setFilteredPermissions(permissions);
}
}, [guardName,permissions]);
const handleGuardNameChange = (event) => {
console.log("ivan")
setGuardName(event.target.value);
setValue('guard_name', event.target.value);
};
return (
<FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
<Box sx={{ px: 2 }}>
@@ -131,7 +154,7 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
<Stack spacing={2}>
<Typography variant="h6" color={palette.light.primary.main}>User Role</Typography>
<RHFTextField name="name" label="Name" />
<RHFSelect name="guard_name" label="Guard Name">
<RHFSelect name="guard_name" label="Guard Name" onChange={handleGuardNameChange}>
{guard_name_options.map((option, index) => (
<option key={index} value={option.value}>
{option.label}
@@ -140,7 +163,7 @@ export default function UserRoleForm({ isEdit, currentUserRole, permissions }: P
</RHFSelect>
<Typography variant="h6" color={palette.light.primary.main}>Permission</Typography>
<Grid container spacing={2}>
{permissions?.map((permission, index) => (
{filteredPermissions?.map((permission, index) => (
<Grid item xs={4} key={permission.id}>
<FormControlLabel
control={