Skip to content

Commit

Permalink
Merge pull request #6 from vimalsonara/chart
Browse files Browse the repository at this point in the history
API integration last seven days chart
  • Loading branch information
vimalsonara authored Nov 19, 2023
2 parents ccc7f1a + 13c8da0 commit 69f4273
Show file tree
Hide file tree
Showing 7 changed files with 221 additions and 25 deletions.
74 changes: 74 additions & 0 deletions app/api/purchase/week-summary/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { getServerSession } from "next-auth";
import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "../../auth/[...nextauth]/route";
import { collection, getDocs } from "firebase/firestore";
import { db } from "@/lib/firebaseConfig";
import { Purchase } from "@/types/types";

export async function GET(req: NextRequest) {
const session = await getServerSession(authOptions);

if (session) {
const { searchParams } = new URL(req.url);
const date = searchParams.get("today");
const purchaseRef = collection(db, "purchaseEntries");
const purchaseList: Purchase[] = [];
const dateArray: string[] = [];

if (date !== null) {
const today = new Date(date);
const sevenDaysAgo = new Date(today);
sevenDaysAgo.setDate(today.getDate() - 6);

for (let i = 0; i < 7; i++) {
const currentDate = new Date(sevenDaysAgo);
currentDate.setDate(sevenDaysAgo.getDate() + i);

const formattedDate = currentDate.toISOString().split("T")[0];
console.log(formattedDate);
dateArray.push(formattedDate);
}

const snapshot = await getDocs(purchaseRef);

snapshot.docs.forEach((doc) => {
const purchaseData = doc.data();
const currentPurchase: Purchase = {
id: doc.id,
date: purchaseData.date,
totalAmount: purchaseData.totalAmount,
userId: purchaseData.userId,
vendorId: purchaseData.vendorId,
vendorName: purchaseData.vendorName,
items: purchaseData.items,
};
purchaseList.push(currentPurchase);
});
} else {
return NextResponse.json("Invaid date entered", { status: 400 });
}

if (purchaseList.length > 0) {
const lastSeven = [];
for (let i = 0; i < dateArray.length; i++) {
const totalAmount = purchaseList
.filter((purchase) => purchase.date === dateArray[i])
.reduce((acc, currPurchase) => acc + currPurchase.totalAmount, 0);

const purchase = {
date: dateArray[i],
amount: totalAmount,
};
lastSeven.push(purchase);
}
return NextResponse.json(lastSeven, { status: 200 });
} else {
return NextResponse.json("No purhcase found", { status: 404 });
}
} else {
return NextResponse.json(
{ error: "You are not authenticated." },
{ status: 401 }
);
}
}
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default async function RootLayout({
>
<div className="relative flex min-h-screen flex-col">
{session && <SiteHeader />}
<main className="container flex p-2">{children}</main>
<main className="container">{children}</main>
</div>
</ThemeProvider>
</SessionProvider>
Expand Down
69 changes: 47 additions & 22 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import axios from "axios";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import DashboardCard from "@/components/dashboardCard";
import BarChart from "@/components/charts/barChart";

interface Purchase {
totalAmount: number;
Expand All @@ -14,6 +15,7 @@ export default function Home() {
const [vendorList, setVendorList] = useState([]);
const [productList, setProductList] = useState([]);
const [purchaseList, setPurchaseList] = useState<Purchase[]>([]);
const [lastSevenDaysPurchase, setLastSevenDaysPurchase] = useState([]);

useEffect(() => {
if (session?.user.id) {
Expand All @@ -23,7 +25,6 @@ export default function Home() {
userId: session?.user.id,
});
if (vendors.data) {
console.log(vendors);
setVendorList(vendors.data);
} else {
setVendorList([]);
Expand All @@ -38,7 +39,6 @@ export default function Home() {
userId: session?.user.id,
});
if (products.data) {
console.log(products);
setProductList(products.data);
} else {
setProductList([]);
Expand All @@ -54,7 +54,6 @@ export default function Home() {
});

if (purchases.data) {
console.log(purchases);
setPurchaseList(purchases.data);
} else {
setPurchaseList([]);
Expand All @@ -63,9 +62,23 @@ export default function Home() {
console.log(error.message);
}
};

const getLastSevenDaysPurchase = async () => {
try {
const today = new Date();
const todayFormatted = today.toISOString().split("T")[0];
const lastSevenDaysData = await axios.get(
"/api/purchase/week-summary?today=" + todayFormatted
);
if (lastSevenDaysData) {
setLastSevenDaysPurchase(lastSevenDaysData.data);
}
} catch (error) {}
};
getVendors();
getProducts();
getPurchases();
getLastSevenDaysPurchase();
}
}, [session]);

Expand All @@ -75,28 +88,40 @@ export default function Home() {
);

return (
<div className="flex gap-3 mt-2 flex-wrap">
{vendorList.length > 0 && (
<DashboardCard cardTitle={"Total Vendors"} total={vendorList.length} />
)}
{productList.length > 0 && (
<DashboardCard
cardTitle={"Total Products"}
total={productList.length}
/>
)}
{purchaseList.length > 0 && (
<>
<>
<div className="flex gap-3 mt-2 flex-wrap">
{vendorList.length > 0 && (
<DashboardCard
cardTitle={"Total Purchase"}
total={purchaseList.length}
cardTitle={"Total Vendors"}
total={vendorList.length}
/>
)}
{productList.length > 0 && (
<DashboardCard
cardTitle={"Total Purchase Amount"}
total={totalPurchase}
cardTitle={"Total Products"}
total={productList.length}
/>
</>
)}
</div>
)}
{purchaseList.length > 0 && (
<>
<DashboardCard
cardTitle={"Total Purchase"}
total={purchaseList.length}
/>
<DashboardCard
cardTitle={"Total Purchase Amount"}
total={totalPurchase}
/>
</>
)}
</div>
<div className="grid md:grid-cols-2 mt-2">
{lastSevenDaysPurchase && (
<div>
<BarChart purchaseData={lastSevenDaysPurchase} />
</div>
)}
</div>
</>
);
}
53 changes: 53 additions & 0 deletions components/charts/barChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from "chart.js";
import { Bar } from "react-chartjs-2";

ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
import { LastSevenDaysPurchase } from "@/types/types";

interface BarChartProps {
purchaseData: LastSevenDaysPurchase[];
}

export default function BarChart({ purchaseData }: BarChartProps) {
const dateArray = [];
const amountArray = [];

for (const obj of purchaseData) {
dateArray.push(obj.date);
amountArray.push(obj.amount);
}

const options = {
responsive: true,
};

const labels = dateArray;

const data = {
labels,
datasets: [
{
label: "Last 7 days",
data: amountArray,
backgroundColor: "rgba(255, 99, 132, 0.5)",
},
],
};

return <Bar options={options} data={data} />;
}
38 changes: 37 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@tanstack/react-table": "^8.10.7",
"axios": "^1.5.1",
"bcryptjs": "^2.4.3",
"chart.js": "^4.4.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"date-fns": "^2.30.0",
Expand All @@ -28,11 +29,13 @@
"next-auth": "^4.23.2",
"next-themes": "^0.2.1",
"react": "^18",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18",
"react-hook-form": "^7.47.0",
"react-hot-toast": "^2.4.1",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7"
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.5",
Expand Down
5 changes: 5 additions & 0 deletions types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,8 @@ export interface Purchase {
vendorName: string;
items: Items[];
}

export interface LastSevenDaysPurchase {
date: string;
amount: number;
}

0 comments on commit 69f4273

Please sign in to comment.