link graph overview to database:

This commit is contained in:
Naytitorn Chaovirachot 2024-10-20 13:03:41 +07:00
parent 616a357e21
commit f6461cb62c
4 changed files with 73 additions and 74 deletions

View File

@ -25,20 +25,45 @@ export async function getDealList() {
.eq('user_id', await getCurrentUserID()) .eq('user_id', await getCurrentUserID())
.single(); .single();
if (error || !dealData) { // Handle errors and no data cases
alert(JSON.stringify(error)); if (error) {
console.error('Error fetching deal list:', error); alert(JSON.stringify(error));
} else { console.error('Error fetching deal list:', error);
const dealList = dealData.project[0].investment_deal; return; // Exit on error
}
if (!dealList.length) { if (!dealData || !dealData.project.length) {
alert("No data available"); alert("No project available");
return; // Exit early if there's no data return; // Exit if there's no data
} }
// Sort the dealList by created_time in descending order const dealList = dealData.project[0].investment_deal;
const byCreatedTimeDesc = (a: Deal, b: Deal) =>
new Date(b.created_time).getTime() - new Date(a.created_time).getTime(); // Check for empty dealList
return dealList.sort(byCreatedTimeDesc); if (!dealList.length) {
} alert("No deal list available");
}; return; // Exit if there's no data
}
// Sort the dealList by created_time in descending order
const byCreatedTimeDesc = (a: Deal, b: Deal) =>
new Date(b.created_time).getTime() - new Date(a.created_time).getTime();
return dealList.sort(byCreatedTimeDesc);
};
// #TODO move to util
export function convertToGraphData(deals: Deal[]): Record<string, number> {
let graphData = deals.reduce((acc, deal) => {
const monthYear = new Date(deal.created_time).toISOString().slice(0, 7); // E.g., '2024-10'
acc[monthYear] = (acc[monthYear] || 0) + deal.deal_amount; // Sum the deal_amount
return acc;
}, {} as Record<string, number>); // Change type to Record<string, number>
// Sort keys in ascending order
const sortedKeys = Object.keys(graphData).sort((a, b) => (a > b ? 1 : -1));
// Create a sorted graph data object
const sortedGraphData: Record<string, number> = {};
sortedKeys.forEach((key) => {sortedGraphData[key] = graphData[key]});
return sortedGraphData;
}

View File

@ -1,5 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Deal, getDealList } from "../api/dealApi"; import { Deal, getDealList, convertToGraphData } from "../api/dealApi";
// custom hook for deal list // custom hook for deal list
export function useDealList() { export function useDealList() {
@ -14,4 +14,21 @@ export function useDealList() {
}, []); }, []);
return dealList; return dealList;
}
export function useGraphData() {
const [graphData, setGraphData] = useState<Record<string, number>>({});
const fetchGraphData = async () => {
const dealList = await getDealList();
if (dealList) {
setGraphData(convertToGraphData(dealList));
}
}
useEffect(() => {
fetchGraphData();
}, []);
return graphData;
} }

View File

@ -12,10 +12,11 @@ import { Overview } from "@/components/ui/overview";
import { RecentFunds } from "@/components/recent-funds"; import { RecentFunds } from "@/components/recent-funds";
import { useState } from "react"; import { useState } from "react";
import { useDealList } from "./hook"; import { useDealList, useGraphData } from "./hook";
export default function Dashboard() { export default function Dashboard() {
const [graphType, setGraphType] = useState("line"); const [graphType, setGraphType] = useState("line");
const graphData = useGraphData();
const dealList = useDealList(); const dealList = useDealList();
const totalDealAmount = dealList?.reduce((sum, deal) => sum + deal.deal_amount, 0) || 0; const totalDealAmount = dealList?.reduce((sum, deal) => sum + deal.deal_amount, 0) || 0;
@ -166,7 +167,7 @@ export default function Dashboard() {
<CardTitle>Overview</CardTitle> <CardTitle>Overview</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="pl-2"> <CardContent className="pl-2">
<Overview graphType={graphType} /> <Overview graphType={graphType} graphData={graphData} />
{/* tab to switch between line and bar graph */} {/* tab to switch between line and bar graph */}
<Tabs <Tabs
defaultValue="line" defaultValue="line"

View File

@ -2,66 +2,22 @@
import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis, LineChart, Line } from "recharts"; import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis, LineChart, Line } from "recharts";
const data = [ interface OverViewProps {
{ graphType: string;
name: "Jan", graphData: Record<string, number>; // Object with month-year as keys and sum as value
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Feb",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Mar",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Apr",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "May",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Jun",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Jul",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Aug",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Sep",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Oct",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Nov",
total: Math.floor(Math.random() * 5000) + 1000,
},
{
name: "Dec",
total: Math.floor(Math.random() * 5000) + 1000,
},
];
interface OverViewProps{
graphType:string;
} }
export function Overview(props: OverViewProps) { export function Overview(props: OverViewProps) {
// Transform the grouped data into the format for the chart
const chartData = Object.entries(props.graphData).map(([monthYear, totalArray]) => ({
name: monthYear,
total: totalArray, // Get the total amount for the month
}));
return ( return (
<ResponsiveContainer width="100%" height={350}> <ResponsiveContainer width="100%" height={350}>
{props.graphType === 'line' ? ( {props.graphType === 'line' ? (
<LineChart data={data}> <LineChart data={chartData}>
<XAxis <XAxis
dataKey="name" dataKey="name"
stroke="#888888" stroke="#888888"
@ -83,7 +39,7 @@ export function Overview(props: OverViewProps) {
/> />
</LineChart> </LineChart>
) : ( ) : (
<BarChart data={data}> <BarChart data={chartData}>
<XAxis <XAxis
dataKey="name" dataKey="name"
stroke="#888888" stroke="#888888"
@ -106,5 +62,5 @@ export function Overview(props: OverViewProps) {
</BarChart> </BarChart>
)} )}
</ResponsiveContainer> </ResponsiveContainer>
); );
} }