import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { Button, Grid, makeStyles, Menu, MenuItem, Paper, withStyles } from '@material-ui/core';
import { KeyboardDatePicker } from '@material-ui/pickers';
import moment from 'moment-timezone';
import SearchIcon from '@material-ui/icons/Search';
import GetAppIcon from '@material-ui/icons/GetApp';
// import { Link } from 'react-router-dom';
import axios from 'axios';
import TextField from '../common/TextField';
import IconButton from '../common/IconButton';
import AdminLayout from '../AdminLayout';
import SEO from '../common/SEO';
import { dateFormat } from '../../config/common.constants';
import {
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TablePagination,
TableRow,
} from '../common/Table';
import CustomerSelectDialog from '../CustomerSelectDialog';
import { Customer } from '../../types';
// import { getFullName } from '../../utils/customer';
import {
getBillingCodesByEmail,
getBusinessUsageReport,
GetBusinessUsageReportPayload,
} from '../../services/B2BUsageReport.service';
import { useToast } from '../../context/ToastContext';
import Select from '../common/Select';
import { B2BUsageReport } from '../../types/B2BUsageReport.type';
import { ROW_PER_PAGE_OPTIONS } from '../../config/pagination';
// import { productAction } from '../../lib/snowplow';
// import SnowPlowUtil from '../../utils/snowplow.util';
import END_POINT from '../../config/endpoints.constants';
import { getErrorMessage } from '../../lib/error-handling';
import PageTitle from '../common/PageTitle';
const StyledB2BUsageReport = styled.div`
.search-area {
display: flex;
justify-content: space-between;
}
.search-by-email {
display: flex;
flex-direction: column;
width: 50%;
}
.box-width {
width: 100%;
align-items: baseline;
}
.half-box-width {
width: 50%;
align-items: baseline;
}
.date-picker-style {
font-size: 20px;
}
.billing-code-div {
width: 50%;
font-size: 18px;
font-weight: bold;
text-align: center;
}
.label-box {
width: 40px;
}
.wrapper {
position: relative;
width: 20px;
height: 150px;
margin-left: 10px;
}
.line {
position: absolute;
left: 49%;
top: 0;
bottom: 0;
width: 1px;
background: #ccc;
z-index: 1;
}
.wordwrapper {
text-align: center;
height: 12px;
position: absolute;
left: 0;
right: 0;
top: 50%;
margin-top: -12px;
z-index: 2;
}
.label-text {
color: black;
font-weight: 600;
margin-bottom: 0;
font-size: 16px;
}
.word {
color: #ccc;
text-transform: uppercase;
letter-spacing: 1px;
padding: 3px;
font: bold 12px arial, sans-serif;
background: #fff;
}
`;
const useStyles = makeStyles(() => ({
tableContainer: {
marginTop: '30px',
},
datePicker: {
width: '138px',
},
exportButton: {
float: 'right',
backgroundColor: 'green',
color: 'white',
marginRight: '5px',
'&.Mui-disabled': {
color: 'white',
backgroundColor: 'grey',
},
},
}));
const StyledButton = withStyles({
root: {
background: 'green',
borderRadius: 3,
border: 0,
color: 'white',
height: 30,
marginTop: '15px',
// padding: '0 30px',
width: '2px',
},
label: {
textTransform: 'capitalize',
},
// '&:hover': {
// backgroundColor: 'green',
// },
})(Button);
const B2BUsageReports = () => {
const toast = useToast();
const classes = useStyles();
const [openCustomerDialog, setOpenCustomerDialog] = useState(false);
const [startDate, setStartDate] = useState(moment().startOf('day'));
const [totalCount, setTotalCount] = useState(0);
// const [usedByDesc, setUsedByDesc] = useState('');
const [selectBillingCode, setSelectBillingCode] = useState<string>('');
const [endDate, setEndDate] = useState(moment().endOf('day'));
const [usedBy, setUsedBy] = useState<Customer | null>(null);
const [email, setEmail] = useState<string>('');
const [enableDownloadBtn, setEnableDownloadBtn] = useState<Boolean>(false);
const maxDate = moment();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [billingCodeList, setBillingCodeList] = useState<string[]>([]);
const [B2BUsageReportList, setB2BUsageReportList] = useState<B2BUsageReport[]>([]);
const [pagination, setPagination] = useState({
page: 0,
rowsPerPage: 10,
offset: 0,
});
const searchByBillingCodeRef = useRef<any>('');
async function searchB2BUsageReportList() {
const payload: GetBusinessUsageReportPayload = {
offset: pagination.offset,
limit: pagination.rowsPerPage,
fromDate: moment(startDate).toISOString(),
toDate: moment(endDate).toISOString(),
billingCode: searchByBillingCodeRef.current.value
? searchByBillingCodeRef.current.value
: selectBillingCode,
};
const { data, error } = await getBusinessUsageReport(payload);
if (data) {
console.log(data.totalCount)
setB2BUsageReportList(data.objects);
setTotalCount(data.totalCount);
}
if (error) {
toast.error(error);
}
}
const initialSearchB2BUsageReport = () => {
setPagination({ ...pagination, page: 0, rowsPerPage: 10, offset: 0 });
};
const handleChangePage = (event: any, newPage: any) => {
const { page } = pagination;
if (page < newPage) {
setPagination({ ...pagination, offset: pagination.offset + 1, page: newPage });
} else {
setPagination({ ...pagination, offset: pagination.offset - 1, page: newPage });
}
// handlePagination(creditPlanOrginalList);
};
const handleChangeRowsPerPage = (event: any) => {
setPagination((state) => ({
...state,
rowsPerPage: event.target.value,
page: 0,
offset: 0,
}));
};
useEffect(() => {
if (searchByBillingCodeRef.current.value || selectBillingCode) {
searchB2BUsageReportList();
}
}, [pagination]);
useEffect(() => {
if (B2BUsageReportList.length === 0) {
setEnableDownloadBtn(false);
} else {
setEnableDownloadBtn(true);
}
}, [B2BUsageReportList]);
const handleMenuClose = () => {
setAnchorEl(null);
};
const isMenuOpen = Boolean(anchorEl);
function saveByteArray(reportName: string, type: string, byte: any) {
const blob = new Blob([byte]);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
const fileName = `${reportName}.${type}`;
link.download = fileName;
link.click();
}
const exportCreditLogs = (type: string) => {
handleMenuClose();
const reqData: any = {
fromDate: moment(startDate).toISOString(),
toDate: moment(endDate).toISOString(),
billingCode: searchByBillingCodeRef.current.value
? searchByBillingCodeRef.current.value
: selectBillingCode,
};
if (type === 'pdf') {
axios
.post(END_POINT.GENERATE_USAGE_REPORT_PDF, reqData, { responseType: 'arraybuffer' })
.then((res) => {
saveByteArray('Usage_Report', type, res.data);
})
.catch((err) => {
toast.error(getErrorMessage(err));
});
}
if (type === 'csv') {
axios
.post(END_POINT.GENERATE_USAGE_REPORT_CVS, reqData, {
responseType: 'arraybuffer',
})
.then((res) => {
saveByteArray('Usage_Report', type, res.data);
})
.catch((err) => {
toast.error(getErrorMessage(err));
});
}
};
const renderMenu = (
<Menu
anchorEl={anchorEl}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
keepMounted
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={isMenuOpen}
onClose={handleMenuClose}
>
<MenuItem onClick={() => exportCreditLogs('csv')}>CSV</MenuItem>
<MenuItem onClick={() => exportCreditLogs('pdf')}>PDF</MenuItem>
</Menu>
);
const handleProfileMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleCustomerSelection = async (selectedCustomer: Customer) => {
searchByBillingCodeRef.current.value = '';
setBillingCodeList([]);
setB2BUsageReportList([]);
setSelectBillingCode('');
const { data, error } = await getBillingCodesByEmail(selectedCustomer.email);
if (data) {
setBillingCodeList(data);
}
if (error) {
toast.error(error);
}
setUsedBy(selectedCustomer);
setEmail(selectedCustomer.email);
// setUsedByDesc(getFullName(selectedCustomer));
setOpenCustomerDialog(false);
};
const handleClose = () => {
setOpenCustomerDialog(false);
};
const handleClickOpen = () => {
setOpenCustomerDialog(true);
};
function handleBillingCodeSelection(billingCode: string) {
setSelectBillingCode(billingCode);
}
function searchByBillingCode() {
if (searchByBillingCodeRef.current.value) {
setBillingCodeList([]);
setB2BUsageReportList([]);
setUsedBy(null);
setEmail('');
setSelectBillingCode('');
setB2BUsageReportList([]);
}
}
return (
<AdminLayout>
<SEO title="B2BUsageReport" description="Convo Pilot Admin B2B Usage report" />
<div className="flex items-center justify-between mb-3">
<PageTitle>Usage Reports</PageTitle>
</div>
<StyledB2BUsageReport>
<Paper className="p-6">
<form noValidate name="B2B-Usage-Search-form">
<div className="search-area">
<div className="search-by-email">
<div className="flex box-width items-center">
<span className="mr-2 label-box label-text">Email:</span>
<TextField
readOnly
fullWidth
className="flex-grow"
value={email}
/>
<IconButton
id="email-search-btn"
color="primary"
onClick={handleClickOpen}
className="ml-3 search-btn"
>
<i className="material-icons">search</i>
</IconButton>
</div>
<div className="flex box-width items-center">
<span className="mr-2 label-box label-text">Billing Code:</span>
<Select
options={billingCodeList}
name="BillingCodeList"
getOptionLabel={(option) => option}
getOptionValue={(option) => option}
onChange={handleBillingCodeSelection}
value={selectBillingCode}
/>
</div>
</div>
<div className="wrapper">
<div className="line" />
<div className="wordwrapper">
<div className="word">or</div>
</div>
</div>
<div className="flex items-center half-box-width">
<span className="mr-2 ml-2 label-text">
Search By Billing code:
</span>
<TextField
fullWidth
className="flex-grow"
inputRef={searchByBillingCodeRef}
onChange={() => searchByBillingCode()}
/>
</div>
</div>
</form>
</Paper>
<Paper className="p-4">
<Grid container justify="center">
<Grid item xs={12}>
<Grid container justify="center" spacing={3}>
<Grid item xs={12} md={4} sm={6} style={{ display: 'flex' }}>
{/* <span className="date-picker-style">Date Picker</span> */}
</Grid>
<Grid item xs={12} md={3} sm={6} style={{ display: 'flex' }}>
<KeyboardDatePicker
style={{ width: '100%' }}
className={classes.datePicker}
value={startDate}
format={dateFormat}
label="Start Date"
maxDate={maxDate}
onChange={(date: any) => setStartDate(date)}
/>
</Grid>
<Grid item xs={12} md={3} sm={6} style={{ display: 'flex' }}>
<KeyboardDatePicker
style={{ width: '100%' }}
className={classes.datePicker}
value={endDate}
label="End Date"
format={dateFormat}
minDate={moment(startDate)}
maxDate={maxDate}
onChange={(date: any) => setEndDate(date)}
/>
</Grid>
<Grid item xs={12} md={2} sm={6} style={{ display: 'flex' }}>
<StyledButton
className="mr-2"
onClick={initialSearchB2BUsageReport}
>
<SearchIcon />
</StyledButton>
<StyledButton
disabled={!enableDownloadBtn}
onClick={handleProfileMenuOpen}
>
<GetAppIcon />
</StyledButton>
</Grid>
{renderMenu}
</Grid>
</Grid>
</Grid>
</Paper>
<Paper className="p-4">
<div className="flex justify-end align-content-end">
<div className="billing-code-div">
<span className="ml-2 mr-5">Billing Code:</span>
<span>{selectBillingCode || searchByBillingCodeRef.current.value}</span>
</div>
</div>
<TableContainer>
<Table aria-label="simple table" size="medium">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Owned By</TableCell>
<TableCell>Number Type</TableCell>
<TableCell>Billing Code</TableCell>
<TableCell>Phone Number</TableCell>
<TableCell>Consolidated usage</TableCell>
</TableRow>
</TableHead>
<TableBody>
{B2BUsageReportList.map(
(b2BUsageReport: B2BUsageReport, index: number, arr: any[]) => (
<TableRow key={arr ? arr.length : 0}>
<TableCell component="th" scope="row">
{b2BUsageReport.name}
</TableCell>
<TableCell>{b2BUsageReport.ownedByType}</TableCell>
<TableCell>{b2BUsageReport.numberType}</TableCell>
<TableCell>{b2BUsageReport.billingCode}</TableCell>
<TableCell>{b2BUsageReport.phoneNumber}</TableCell>
<TableCell>{b2BUsageReport.totalUsage}</TableCell>
</TableRow>
),
)}
</TableBody>
</Table>
<TablePagination
rowsPerPageOptions={ROW_PER_PAGE_OPTIONS}
component="div"
count={totalCount}
rowsPerPage={pagination.rowsPerPage}
page={pagination.page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</TableContainer>
{/* <div className="flex justify-end align-content-end"> */}
{/* <div className="billing-code-div"> */}
{/* <span className="ml-2 mr-5">Grant Total:</span> */}
{/* <span>xxxxxxxxx</span> */}
{/* </div> */}
{/* </div> */}
</Paper>
<CustomerSelectDialog
onCustomerSelect={handleCustomerSelection}
selectedCustomer={usedBy}
onClose={handleClose}
open={openCustomerDialog}
/>
</StyledB2BUsageReport>
</AdminLayout>
);
};
export default B2BUsageReports;
Here I am getting issue in loading next records. Suppose We have total 15 records and on the first load 10 records are displayed in UI because the limit is set as 10 and when I click on next to load the next 5 records then previous 10 records are also displayed with the latest 5 records which is wrong. In API I am getting the records correctly like first it is showing in payload limit 10 , offset:0 and records:0-9 and for the next 5 records it
is payload is like offset:1, limit:10 and records:0-4 but in UI it is not showing correctly for rest 5 record. It should show rest 5 records in new page separately as we are using pagination. Some help would be appreciated.