From 7356831e2e650d0b82946fc96eda4938edd9fc1f Mon Sep 17 00:00:00 2001 From: Pattadon Date: Fri, 1 Nov 2024 14:32:33 +0700 Subject: [PATCH] Refactor portfolio hook and page components - Add functions to calculate total investment and get latest investment - Update graph data calculations for overall and four-year graphs - Update recent funds component to display latest investment deals - Minor code formatting and error handling improvements --- src/app/portfolio/[uid]/hook.ts | 111 +++++++++++++++++++++---------- src/app/portfolio/[uid]/page.tsx | 33 ++++++++- src/components/recent-funds.tsx | 19 +++--- 3 files changed, 114 insertions(+), 49 deletions(-) diff --git a/src/app/portfolio/[uid]/hook.ts b/src/app/portfolio/[uid]/hook.ts index 4675324..8efb2bd 100644 --- a/src/app/portfolio/[uid]/hook.ts +++ b/src/app/portfolio/[uid]/hook.ts @@ -1,6 +1,38 @@ import { SupabaseClient } from "@supabase/supabase-js"; import { getProjectTag, getTagName } from "@/lib/data/query"; +function getTotalInvestment(deals: { deal_amount : number}[]) { + let total = 0; + for (let index = 0; index < deals.length; index++) { + total += deals[index].deal_amount; + } + return total; +} +async function getLatestInvestment( + supabase: SupabaseClient, + deals: { project_id: number; deal_amount: number; created_time: Date }[] +) { + const llist = []; + const count = 8; + + for (let i = deals.length - 1; i >= 0 && llist.length < count; --i) { + let { data: project, error } = await supabase + .from("project") + .select("project_name") + .eq("id", deals[i].project_id); + if (error) { + console.error(error); + } + llist.push({ + name: project?.[0]?.project_name, + amount: deals[i].deal_amount, + date: new Date(deals[i].created_time), + }); + } + + return llist; +} + async function checkForInvest(supabase: SupabaseClient, userId: string) { let { count, error } = await supabase .from("investment_deal") @@ -30,7 +62,6 @@ function countValues(arr: { value: string }[][]): Record { return counts; } - async function getBusinessTypeName( supabase: SupabaseClient, projectId: number @@ -75,32 +106,38 @@ interface GraphData { } function overAllGraphData(deals: Deal[]): GraphData[] { - return deals - ? deals - .filter((item: Deal) => new Date(item.created_time) >= yearAgo(1)) - .reduce((acc: GraphData[], item: Deal) => { - // get the first three initial letter of the month - const monthName = getMonthName(item.created_time.toString()).slice( - 0, - 3 - ); - const existingMonth = acc.find( - (entry: GraphData) => entry.name === monthName - ); + // Initialize all months with value 0 + const months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; + const acc: GraphData[] = months.map((month) => ({ name: month, value: 0 })); - if (existingMonth) { - existingMonth.value += item.deal_amount; - } - // if month doesnt exist yet, create new record - else { - acc.push({ name: monthName, value: item.deal_amount }); - } + deals + .filter((item: Deal) => new Date(item.created_time) >= yearAgo(1)) + .forEach((item: Deal) => { + const monthName = getMonthName(item.created_time.toString()).slice(0, 3); + const monthEntry = acc.find((entry) => entry.name === monthName); - return acc; - }, [] as GraphData[]) - : []; + if (monthEntry) { + monthEntry.value += item.deal_amount; + } + }); + + return acc; } + interface Deal { created_time: string | number | Date; deal_amount: any; @@ -112,24 +149,26 @@ interface GraphData { } function fourYearGraphData(deals: Deal[]): GraphData[] { - return deals + const currentYear = new Date().getFullYear(); + const acc: GraphData[] = Array.from({ length: 4 }, (_, i) => ({ + name: (currentYear - i).toString(), + value: 0, + })).reverse(); + deals .filter((item: Deal) => new Date(item.created_time) >= yearAgo(3)) - .reduce((acc: GraphData[], item: Deal) => { - const year = new Date(item.created_time).getFullYear(); - const existingYear = acc.find( - (entry: GraphData) => entry.name === year.toString() - ); + .forEach((item: Deal) => { + const year = new Date(item.created_time).getFullYear().toString(); + const yearEntry = acc.find((entry) => entry.name === year); - if (existingYear) { - existingYear.value += item.deal_amount; - } else { - acc.push({ name: year.toString(), value: item.deal_amount }); + if (yearEntry) { + yearEntry.value += item.deal_amount; } + }); - return acc; - }, [] as GraphData[]); + return acc; } + interface DayOfWeekData { name: string; value: number; @@ -238,4 +277,6 @@ export { getBusinessTypeName, countValues, checkForInvest, + getLatestInvestment, + getTotalInvestment, }; diff --git a/src/app/portfolio/[uid]/page.tsx b/src/app/portfolio/[uid]/page.tsx index 6416885..05b40ee 100644 --- a/src/app/portfolio/[uid]/page.tsx +++ b/src/app/portfolio/[uid]/page.tsx @@ -11,6 +11,8 @@ import { getBusinessTypeName, countValues, checkForInvest, + getLatestInvestment, + getTotalInvestment, } from "./hook"; import CountUpComponent from "@/components/countUp"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; @@ -24,6 +26,7 @@ import { RecentFunds } from "@/components/recent-funds"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import QuestionMarkIcon from "@/components/icon/questionMark"; import { NoDataAlert } from "@/components/alert/noData/alert"; +import { error } from "console"; export default async function Portfolio({ params, @@ -33,7 +36,6 @@ export default async function Portfolio({ const supabase = createSupabaseClient(); // if user hasn't invest in anything if (!(await checkForInvest(supabase, params.uid))) { - return (
@@ -47,10 +49,22 @@ export default async function Portfolio({ if (investorDealError) { console.error(investorDealError); } + const { + data: { user }, + error: userError, + } = await supabase.auth.getUser(); + if (userError) { + console.error("Error while fetching user" + error); + } + const username = user ? user.user_metadata.name : "Anonymous"; + // console.log(username) const overAllData = deals ? overAllGraphData(deals) : []; const fourYearData = deals ? fourYearGraphData(deals) : []; const dayOfWeekData = deals ? dayOftheWeekData(deals) : []; const tags = deals ? await getInvestorProjectTag(supabase, deals) : []; + const latestDeals = deals ? await getLatestInvestment(supabase, deals) : []; + const totalInvestment = deals ? getTotalInvestment(deals) : 0; + // console.log(latestDeals); const tagCount = countTags(tags); // console.log(investedBusinessIds); const businessType = deals @@ -80,9 +94,22 @@ export default async function Portfolio({
{totalInvest}
*/} {/* */} +
+

+ Welcome to your Portfolio, {username}! +

+

+ Here's an overview of your investment journey and progress. +

+

+ Total Investment: $ + +

+
+
- + Daily Monthly Yearly @@ -246,7 +273,7 @@ export default async function Portfolio({ - +
diff --git a/src/components/recent-funds.tsx b/src/components/recent-funds.tsx index 97b9224..b078846 100644 --- a/src/components/recent-funds.tsx +++ b/src/components/recent-funds.tsx @@ -38,26 +38,23 @@ const data = [ }, ]; -interface RecentFundsProps{ - name?: string; - email?: string; - amount?: number; - avatar?: string; +interface RecentFundsProps { + data?: { name?: string; amount?: number; avatar?: string ; date?: Date}[]; } export function RecentFunds(props: RecentFundsProps) { return (
- {data.map((person, index) => ( + {(props?.data || []).map((deal, index) => (
- - {person.initials} + + {(deal.name ?? "").slice(0, 3)}
-

{person.name}

-

{person.email}

+

{deal.name}

+

{deal?.date?.toLocaleDateString()}

-
+${person.amount}
+
+${deal.amount}
))}