Skip to content

Commit

Permalink
updating cards in server correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
reedoooo committed Nov 19, 2023
1 parent 697d933 commit 2fbbd9a
Show file tree
Hide file tree
Showing 37 changed files with 2,041 additions and 1,496 deletions.
15 changes: 8 additions & 7 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ const useCronJob = (lastCronJobTriggerTime, setLastCronJobTriggerTime) => {
setLastCronJobTriggerTime(currentTime);
if (userId && listOfMonitoredCards) {
console.log('RETRIEVING LIST OF MONITORED CARDS (paused)');
// handleSendAllCardsInCollections(
// userId,
// listOfMonitoredCards
// // handleRetrieveListOfMonitoredCards()
// );
handleSendAllCardsInCollections(
userId,
listOfMonitoredCards
// handleRetrieveListOfMonitoredCards()
);
console.log('Triggered the cron job.');
}
}
Expand All @@ -140,7 +140,7 @@ const useCronJob = (lastCronJobTriggerTime, setLastCronJobTriggerTime) => {
const App = () => {
const { user } = useUserContext();
const { isLoading, setIsContextLoading } = useUtilityContext();
const { fetchAllCollectionsForUser } = useCollectionStore();
const { fetchAllCollectionsForUser, allCollections } = useCollectionStore();
const [lastCronJobTriggerTime, setLastCronJobTriggerTime] = useState(null);

useCronJob(lastCronJobTriggerTime, setLastCronJobTriggerTime);
Expand Down Expand Up @@ -174,6 +174,7 @@ const App = () => {
if (user && isMounted) {
try {
// const response = fet
await fetchAllCollectionsForUser(user.userID);
if (isMounted) {
console.log('Fetched collections because none were present.');
// Update state only if the component is still mounted
Expand All @@ -192,7 +193,7 @@ const App = () => {
return () => {
isMounted = false;
};
}, [user, fetchAllCollectionsForUser]);
}, [user, fetchAllCollectionsForUser, allCollections]);

return (
<>
Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -95,26 +95,33 @@ const LinearChart = ({
const theme = useTheme();
const [isZoomed, setIsZoomed] = useState(false);
const { hoveredData, handleMouseMove, handleMouseLeave } = useEventHandlers();

// const filteredData = useMemo(
// () => getFilteredData(filteredChartData, timeRange),
// [filteredChartData, timeRange]
// );
// console.log('filteredData', filteredData);

// const dataForChart = useMemo(() => {
// return datesTimesValues.dates.map((date, index) => ({
// x: formatDateToString(
// new Date(`${date} ${datesTimesValues.times[index]}`)
// ),
// y: datesTimesValues.values[index],
// }));
// }, [datesTimesValues]);
// CustomLogger('LinearChart', 'info', {
// filteredChartData,
// datesTimesValues,
// });
const tickValues = useMemo(() => getTickValues(timeRange), [timeRange]);
const [format, setFormat] = useState('0,0');
// Calculate tickValues and xFormat based on timeRange
const { tickValues, xFormat } = useMemo(() => {
let format, ticks;
switch (timeRange) {
case '2 hours':
format = '%H:%M';
ticks = 'every 15 minutes';
break;
case '24 hours':
format = '%H:%M';
ticks = 'every 1 hour';
break;
case '7 days':
format = '%b %d';
ticks = 'every 1 day';
break;
case '1 month':
format = '%b %d';
ticks = 'every 3 days';
break;
default:
format = '%b %d';
ticks = 'every 1 day';
}
return { tickValues: ticks, xFormat: `time:${format}` };
}, [timeRange]);

if (
!Array.isArray(filteredChartData) ||
Expand All @@ -126,86 +133,6 @@ const LinearChart = ({
</Typography>
);
}
// const classes = useStyles();
// const theme = useTheme();

// // Hooks should be at the top level of your component
// const [isZoomed, setIsZoomed] = useState(false);
// const filteredData = useMemo(
// () => getFilteredData(filteredChartData, timeRange),
// [filteredChartData, timeRange]
// );
// // const averagedData = useMemo(
// // () => getAveragedData(filteredData),
// // [filteredData]
// // );
// const { hoveredData, handleMouseMove, handleMouseLeave } = useEventHandlers();

// if (!Array.isArray(filteredChartData)) {
// return <Typography variant="body1">No valid data available</Typography>;
// }

// if (
// !datesTimesValues ||
// !datesTimesValues.dates ||
// !datesTimesValues.times ||
// !datesTimesValues.values
// ) {
// console.error('Invalid averaged chart data:', datesTimesValues);
// return <Typography variant="body1">Invalid data for the chart</Typography>;
// }

// const dataForChart = useMemo(() => {
// return [
// {
// id: 'Averaged Data',
// data: datesTimesValues.dates.map((date, index) => ({
// x: formatDateToString(
// new Date(`${date} ${datesTimesValues.times[index]}`)
// ),
// y: datesTimesValues.values[index],
// })),
// },
// ];
// }, [datesTimesValues]);

// if (dataForChart[0].data.length === 0) {
// return <Typography variant="body1">No valid data available</Typography>;
// }
// const tickValues = useMemo(() => getTickValues(timeRange), [timeRange]);

// if (
// !Array.isArray(filteredChartData) ||
// filteredChartData.some((d) => !d.x || !d.y)
// ) {
// return <Typography variant="body1">No valid data available</Typography>;
// }
// // logReadableChartInfo(
// // dataForChart,
// // datesTimesValues,
// // filteredChartData,
// // latestData
// // );
// try {
// const filteredData = useMemo(
// () => getFilteredData(filteredChartData, timeRange),
// [filteredChartData, timeRange]
// );
// getAveragedData(filteredData);
// } catch (error) {
// console.error('Error processing data for chart:', error);
// } // console.log('averagedData', averagedData);

// const lastData = useMemo(() => {
// if (filteredChartData && filteredChartData.length) {
// return {
// x: filteredChartData[filteredChartData.length - 1].x,
// y: filteredChartData[filteredChartData.length - 1].y,
// };
// }
// return {};
// }, [filteredChartData]);

const chartProps = {
margin: { top: 50, right: 110, bottom: 50, left: 60 },
// data: [{ id: 'Data', data: dataForChart }],
Expand All @@ -215,20 +142,26 @@ const LinearChart = ({
motionDamping: 15,
xScale: {
type: 'time',
format: '%Y-%m-%d %H:%M',
// format: '%Y-%m-%d %H:%M:%S',
format: '%Y-%m-%dT%H:%M:%S.%LZ',
useUTC: false,
precision: 'minute',
precision: 'second',
},
yScale: { type: 'linear', min: 'auto', max: 'auto' },
xFormat: 'time:%Y-%m-%d %H:%M:%S',
axisBottom: {
tickRotation: 0,
legendOffset: -12,
legend: 'Time',
tickPadding: 10,
tickSize: 10,
format: '%b %d',
// format: '%b %d',
// tickValues: 'every 2 days',
format: xFormat,
tickValues: tickValues,
// tickValues: tickValues,
},
yScale: { type: 'linear', min: 'auto', max: 'auto' },

axisLeft: {
orient: 'left',
legend: 'Value ($)',
Expand All @@ -250,12 +183,12 @@ const LinearChart = ({
onMouseLeave: handleMouseLeave,
onClick: () => setIsZoomed(!isZoomed),
tooltip: CustomTooltip,
sliceTooltip: ({ slice }) => {
const point = slice.points.find(
(p) => p.id === 'Data' && p.data.x === latestData.x
);
return point ? <CustomTooltip point={point} /> : null;
},
// sliceTooltip: ({ slice }) => {
// const point = slice.points.find(
// (p) => p.id === 'Data' && p.data.x === latestData.x
// );
// return point ? <CustomTooltip point={point} /> : null;
// },
};

return (
Expand Down
132 changes: 132 additions & 0 deletions src/components/chart/PortfolioChart.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Box, Container, Grid, Paper, styled, useTheme } from '@mui/material';
import LinearChart from './LinearChart';
import { useChartContext } from '../../context/ChartContext/ChartContext';
import ErrorBoundary from '../../context/ErrorBoundary';
import { useCollectionStore } from '../../context/CollectionContext/CollectionContext';
import { useCombinedContext } from '../../context/CombinedProvider';
import debounce from 'lodash/debounce';
import {
convertDataForNivo2,
getFilteredData2,
groupAndAverageData,
} from './chartUtils';

const ChartPaper = styled(Paper)(({ theme }) => ({
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[5],
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.secondary,
padding: theme.spacing(2),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
minHeight: '400px',
overflow: 'hidden',
margin: theme.spacing(2, 0),
}));

const PortfolioChart = () => {
const theme = useTheme();
const { latestData, setLatestData, timeRange } = useChartContext();
const [lastUpdateTime, setLastUpdateTime] = useState(null);
const chartContainerRef = useRef(null);
// const [nivoReadyData2, setNivoReadyData2] = useState(null); // Declare state for nivoReadyData2

const [chartDimensions, setChartDimensions] = useState({
width: 0,
height: 0,
});
const { selectedCollection } = useCollectionStore();

const filteredChartData2 = getFilteredData2(selectedCollection);
// let nivoReadyData2 = [];
// const rawData2 = useMemo(
// () => groupAndAverageData(filteredChartData2, threshold),
// [filteredChartData2, threshold]
// );

const handleThresholdUpdate = () => {
const currentTime = new Date().getTime();
if (!lastUpdateTime || currentTime - lastUpdateTime >= 600000) {
// 10 minutes
setLastUpdateTime(currentTime);
return currentTime;
}
return lastUpdateTime;
};

const threshold = handleThresholdUpdate();
const rawData2 = useMemo(
() => groupAndAverageData(filteredChartData2, threshold),
[filteredChartData2, threshold]
);

const nivoReadyData2 = useMemo(
() => convertDataForNivo2(rawData2),
[rawData2]
);

const HEIGHT_TO_WIDTH_RATIO = 2 / 3;

useEffect(() => {
const handleResize = debounce(() => {
if (chartContainerRef.current) {
const width = chartContainerRef.current.offsetWidth;
const height = width * HEIGHT_TO_WIDTH_RATIO;
setChartDimensions({ width, height });
}
}, 100);

window.addEventListener('resize', handleResize);
handleResize();

return () => {
window.removeEventListener('resize', handleResize);
handleResize.cancel();
};
}, []);

return (
<Container
maxWidth="lg"
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: theme.spacing(2),
gap: theme.spacing(2),
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
}}
>
<ErrorBoundary>
<Grid container spacing={2}>
<Grid
item
xs={12}
sx={{ height: '100%', borderRadius: 2, width: '100%' }}
>
<ChartPaper elevation={3} ref={chartContainerRef}>
{filteredChartData2.length > 0 ? (
<LinearChart
nivoReadyData={nivoReadyData2}
filteredChartData={filteredChartData2}
latestData={latestData}
dimensions={chartDimensions}
timeRanges={timeRange}
/>
) : (
<div>No data available</div>
)}
</ChartPaper>
</Grid>
</Grid>
</ErrorBoundary>
</Container>
);
};

export default PortfolioChart;
Loading

0 comments on commit 2fbbd9a

Please sign in to comment.