Skip to content

Instantly share code, notes, and snippets.

@Prottoy2938
Created May 10, 2024 11:25
Show Gist options
  • Save Prottoy2938/f77aa33dcdde7542cab64aca2bc9a906 to your computer and use it in GitHub Desktop.
Save Prottoy2938/f77aa33dcdde7542cab64aca2bc9a906 to your computer and use it in GitHub Desktop.
History Section
import React, { useRef, useEffect, useState } from "react";
import { RxCross2 } from "react-icons/rx";
import { motion } from "framer-motion";
import { BiDotsHorizontalRounded } from "react-icons/bi";
import { useLocation } from "react-router-dom";
import { Rings } from "react-loader-spinner";
function checkIfArraysEmpty(obj) {
for (let key in obj) {
if (Array.isArray(obj[key]) && obj[key].length > 0) {
return false; // At least one array is not empty
}
}
return true; // All arrays are empty
}
function History({ setNotifications }) {
const reff = useRef(null);
const location = useLocation();
const page = location.pathname.substring(1); // Assuming the pathname contains the page name
// const accessToken = localStorage.getItem("access_token"); //TODO: Update here
const accessToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZGNkMThmZmYtMWMzZS00OWM4LWE3YzUtZDU1ZDFjZTg1Y2JlIiwiZXhwIjoxNzE1NzYzMzYwfQ.F_whOOeLtuLpqF_xdJczNBUsRoSPtiyqsQrA6VNdZbc";
const [historyData, setHistoryData] = useState([]);
const [sortedHistoryData, setSortedHistoryData] = useState({});
const [historyLoading, setHistoryLoading] = useState(true);
useEffect(() => {
function handleClickOutside(event) {
if (reff.current && !reff.current.contains(event.target)) {
setNotifications(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
useEffect(() => {
const fetchData = async () => {
try {
// TODO: ONLY FETCH ONE ENDPONT IF WE'RE NOT ON THE HOMEPAGE
const endpoints = {
teamSummarizer: "https://cbinternaltools.com/team-summarizer/history",
socialHistory: "https://cbinternaltools.com/social/history",
newsletterHistory: "https://cbinternaltools.com/newsletter/history",
translateHistory: "https://cbinternaltools.com/translate/history",
};
const requests = Object.keys(endpoints).map(async (endpoint) => {
const response = await fetch(endpoints[endpoint], {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const data = await response.json();
return { endpoint, data: data };
});
const results = await Promise.all(requests);
const combinedData = results.reduce((acc, { endpoint, data }) => {
switch (endpoint) {
case "teamSummarizer":
console.log(data[0].action.context1);
return acc.concat(
data.map((item) => ({
created: item.created,
endpointName: "teamSummarizer",
content: item.action?.context1 ? item.action?.context1 : "",
}))
);
case "socialHistory":
return acc.concat(
data.map((item) => ({
created: item.created,
endpointName: "socialHistory",
content: item.post,
}))
);
case "newsletterHistory":
return acc.concat(
data.map((item) => ({
created: item.created,
endpointName: "newsletterHistory",
content: item.summary,
}))
);
case "translateHistory":
return acc.concat(
data.map((item) => ({
created: item.created,
endpointName: "translateHistory",
content: item.blob_name,
}))
);
default:
return acc;
}
}, []);
// Sort data by created date in descending order
combinedData.sort((a, b) => new Date(b.created) - new Date(a.created));
// Group data by week
const groupedData = combinedData.reduce((acc, item) => {
const week = new Date(item.created).toISOString().substring(0, 10);
acc[week] = acc[week] ? [...acc[week], item] : [item];
return acc;
}, {});
setHistoryData(groupedData);
} catch (error) {
console.error("Error fetching history data:", error);
}
};
fetchData();
}, [accessToken, location]);
function filterByPage(array) {
return array.filter((obj) => {
if (page === "apps/0/Team%20Summarizer") {
return obj.endpointName === "teamSummarizer";
} else if (page === "apps/2/Social%20Media%20Post%20Generator") {
return obj.endpointName === "socialHistory";
} else if (page === "apps/1/Newsletter") {
return obj.endpointName === "newsletterHistory";
} else if (page === "apps/3/Translator") {
return obj.endpointName === "translateHistory";
} else {
// for all other APIs
return true;
}
});
}
useEffect(() => {
// Filter data based on the current page
const filteredData = Object.entries(historyData).filter(([week, data]) => {
// alert("runnign here");
// Filter based on the page
console.log(Object.entries(historyData));
switch (page) {
case "apps/0/Team%20Summarizer":
return data.some((item) => item.endpointName === "teamSummarizer");
case "apps/2/Social%20Media%20Post%20Generator":
return data.some((item) => item.endpointName === "socialHistory");
case "apps/1/Newsletter":
return data.some((item) => item.endpointName === "newsletterHistory");
case "apps/3/Translator":
console.log(
"RUNNIG HER 1",
data.some((item) => item.endpointName === "translateHistory")
);
return data.some((item) => item.endpointName === "translateHistory");
default:
return true; // If on the homepage, show all data
}
});
// Sort data into different timelines
const timelines = {
today: [],
yesterday: [],
previous7days: [],
previous14days: [],
previous21days: [],
older: [],
};
const today = new Date();
filteredData.forEach(([week, data]) => {
data.forEach((item) => {
const createdDate = new Date(item.created);
const daysDifference = Math.floor(
(today - createdDate) / (1000 * 60 * 60 * 24)
);
if (daysDifference <= 1) {
timelines.today.push(item);
} else if (daysDifference <= 2) {
// If the difference is 1 or 2 days, include in "yesterday"
timelines.yesterday.push(item);
} else if (daysDifference <= 7) {
timelines.previous7days.push(item);
} else if (daysDifference <= 14) {
timelines.previous14days.push(item);
} else if (daysDifference <= 21) {
timelines.previous21days.push(item);
} else {
timelines.older.push(item);
}
});
});
setSortedHistoryData(timelines);
setHistoryLoading(checkIfArraysEmpty(timelines)); //setting loading to be false once we load the data
}, [historyData]);
return (
<motion.div
initial={{ opacity: 0 }}
whileInView={{ opacity: 1 }}
className="fixed top-0 left-0 right-0 h-screen w-full bg-black-500/10 z-400"
>
<motion.div
initial={{ top: "7%", right: "2%" }}
whileInView={{ top: "7%", right: "2%" }}
transition={{ duration: 0.5, type: "spring" }}
style={{ width: "300px", height: "850px" }}
ref={reff}
className="overflow-auto bg-white fixed w-[50%] sm:w-full sm:left-0 sm:h-[500px] h-[600px] right-[26.5%] rounded-xl py-10 sm:pt-4"
>
<div className="flex justify-between items-center px-6 mb-4">
<h2 className="font-Satoshi font-bold text-black-500/80 text-xl">
History
</h2>
<span
onClick={() => setNotifications(false)}
className="flex justify-center items-center p-2 bg-lemon rounded-full cursor-pointer"
>
<RxCross2 className="text-black-200 text-xl hover:text-green-200" />
</span>
</div>
{/* this is a check to see isf we have any history data loaded yet */}
{!historyLoading ? (
<div className="flex flex-col overflow-scroll">
<Item
headline={"Today"}
historyQuery={filterByPage(sortedHistoryData.today)}
/>
<Item
headline={"Yesterday"}
historyQuery={filterByPage(sortedHistoryData.yesterday)}
/>
<Item
headline={"Previous 7 Days"}
historyQuery={filterByPage(sortedHistoryData.previous7days)}
/>
<Item
headline={"Previous 14 Days"}
historyQuery={filterByPage(sortedHistoryData.previous14days)}
/>
<Item
headline={"Previous 21 Days"}
historyQuery={filterByPage(sortedHistoryData.previous21days)}
/>
<Item
headline={"Older"}
historyQuery={filterByPage(sortedHistoryData.older)}
/>
</div>
) : (
<Rings
visible={true}
height="40"
width="40"
color="#8AC825"
ariaLabel="rings-loading"
wrapperStyle={{ marginTop: "50px", marginLeft: "120px" }}
wrapperClass=""
/>
)}
</motion.div>
</motion.div>
);
}
export default History;
const Item = ({ headline, historyQuery }) => {
const location = useLocation();
const page = location.pathname.substring(1); // Assuming the pathname contains the page name
return (
<>
<div className="flex justify-between items-center gap-8 pl-6 py-5 cursor-pointer sm:px-4 sm:py-3 z-400">
<div className="flex justify-start items-start gap-5 sm:gap-2">
<div>
<p className="mb-5 font-Satoshi font-normal text-black-500/60 text-base leading-5 sm:text-sm sm:leading-4">
{headline}
</p>
{historyQuery.length == 0 && (
<h2 className="hover:bg-[#FAFAFA] pr-10 py-2 rounded mb-3 font-Satoshi font-bold text-black-500/80 text-md leading-0 sm:text-base">
No History Found
</h2>
)}
{historyQuery.map((query, i) => (
<h2
key={i}
className="hover:bg-[#FAFAFA] px-2 py-2 rounded mb-3 font-Satoshi font-bold text-black-500/80 text-md leading-0 sm:text-base"
>
{page == "" && (
<div className="text-xs mb-2">{query.endpointName}</div>
)}
{query.content ? query.content.substring(0, 26) : "N/A"}...
</h2>
))}
</div>
</div>
</div>
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment