Skip to content

Commit

Permalink
Progress on showing previous bookings:
Browse files Browse the repository at this point in the history
	- Instead of a second table, now there's only one table with
	  additionaly dropdown options to select between different date
ranges.
	- Changed the date range filter logic to be on the query side
	  (instead of the previous logic where all data was being
fetched and filtered on the front end)
  • Loading branch information
nimanns committed Dec 15, 2024
1 parent 26d412f commit f301ba4
Show file tree
Hide file tree
Showing 8 changed files with 399 additions and 201 deletions.
98 changes: 66 additions & 32 deletions booking-app/components/src/client/routes/components/Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Booking,
BookingType,
DepartmentType,
Filters,
OperationHours,
PaUser,
PagePermission,
Expand All @@ -28,7 +29,6 @@ import { Timestamp } from "firebase-admin/firestore";
export interface DatabaseContextType {
adminUsers: AdminUser[];
bannedUsers: Ban[];
futureBookings: Booking[];
allBookings: Booking[];
bookingsLoading: boolean;
liaisonUsers: Approver[];
Expand All @@ -44,6 +44,7 @@ export interface DatabaseContextType {
userEmail: string | undefined;
netId: string | undefined;
userApiData: UserApiData | undefined;
loadMoreEnabled?: boolean;
reloadAdminUsers: () => Promise<void>;
reloadApproverUsers: () => Promise<void>;
reloadBannedUsers: () => Promise<void>;
Expand All @@ -54,13 +55,15 @@ export interface DatabaseContextType {
reloadBookingTypes: () => Promise<void>;
reloadSafetyTrainedUsers: () => Promise<void>;
setUserEmail: (x: string) => void;
fetchAllBookings: () => Promise<void>;
fetchAllBookings: (clicked: boolean) => Promise<void>;
setFilters: (x: Filters) => void;
setLoadMoreEnabled: (x: boolean) => void;
setLastItem: (x: any) => void;
}

export const DatabaseContext = createContext<DatabaseContextType>({
adminUsers: [],
bannedUsers: [],
futureBookings: [],
allBookings: [],
bookingsLoading: true,
liaisonUsers: [],
Expand All @@ -76,17 +79,21 @@ export const DatabaseContext = createContext<DatabaseContextType>({
userEmail: undefined,
netId: undefined,
userApiData: undefined,
reloadAdminUsers: async () => {},
reloadApproverUsers: async () => {},
reloadBannedUsers: async () => {},
reloadFutureBookings: async () => {},
reloadDepartmentNames: async () => {},
reloadOperationHours: async () => {},
reloadPaUsers: async () => {},
reloadBookingTypes: async () => {},
reloadSafetyTrainedUsers: async () => {},
setUserEmail: (x: string) => {},
fetchAllBookings: async () => {},
loadMoreEnabled: true,
reloadAdminUsers: async () => { },
reloadApproverUsers: async () => { },
reloadBannedUsers: async () => { },
reloadFutureBookings: async () => { },
reloadDepartmentNames: async () => { },
reloadOperationHours: async () => { },
reloadPaUsers: async () => { },
reloadBookingTypes: async () => { },
reloadSafetyTrainedUsers: async () => { },
setUserEmail: (x: string) => { },
fetchAllBookings: async () => { },
setFilters: (x: Filters) => { },
setLoadMoreEnabled: (x: boolean) => { },
setLastItem: (x: any) => { },
});

export const DatabaseProvider = ({
Expand All @@ -95,7 +102,7 @@ export const DatabaseProvider = ({
children: React.ReactNode;
}) => {
const [bannedUsers, setBannedUsers] = useState<Ban[]>([]);
const [futureBookings, setFutureBookings] = useState<Booking[]>([]);
// const [futureBookings, setFutureBookings] = useState<Booking[]>([]);
const [bookingsLoading, setBookingsLoading] = useState<boolean>(true);
const [allBookings, setAllBookings] = useState<Booking[]>([]);
const [adminUsers, setAdminUsers] = useState<AdminUser[]>([]);
Expand All @@ -107,6 +114,8 @@ export const DatabaseProvider = ({
const [policySettings, setPolicySettings] = useState<PolicySettings>({
finalApproverEmail: "",
});
const [loadMoreEnabled, setLoadMoreEnabled] = useState<boolean>(true);

const [roomSettings, setRoomSettings] = useState<RoomSetting[]>([]);
const [safetyTrainedUsers, setSafetyTrainedUsers] = useState<
SafetyTraining[]
Expand All @@ -116,8 +125,9 @@ export const DatabaseProvider = ({
const [userApiData, setUserApiData] = useState<UserApiData | undefined>(
undefined
);
const [lastItem, setLastItem] = useState<Timestamp>(null);
const LIMIT = 3;
const [lastItem, setLastItem] = useState<any>(null);
const [filters, setFilters] = useState<Filters>({ dateRange: "", sortField: "startDate" });
const LIMIT = 10;

const { user } = useAuth();
const netId = useMemo(() => userEmail?.split("@")[0], [userEmail]);
Expand Down Expand Up @@ -165,6 +175,10 @@ export const DatabaseProvider = ({
JSON.stringify(equipmentUsers),
]);

useEffect(() => {
console.log(allBookings.length);
}, [allBookings]);

useEffect(() => {
if (!bookingsLoading) {
fetchSafetyTrainedUsers();
Expand All @@ -173,26 +187,21 @@ export const DatabaseProvider = ({
fetchDepartmentNames();
fetchSettings();
} else {
fetchFutureBookings();
// fetchBookings();
}
}, [bookingsLoading, user]);

useEffect(() => {
fetchBookings();
}, [filters]);

useEffect(() => {
fetchActiveUserEmail();
fetchAdminUsers();
fetchPaUsers();
fetchRoomSettings();
}, [user]);

useEffect(() => {
if (
pagePermission === PagePermission.ADMIN ||
pagePermission === PagePermission.LIAISON ||
pagePermission === PagePermission.PA
)
fetchBookings();
}, [pagePermission]);

const fetchActiveUserEmail = () => {
if (!user) return;
setUserEmail(user.email);
Expand All @@ -201,20 +210,42 @@ export const DatabaseProvider = ({
const fetchFutureBookings = async () => {
fetchAllFutureBooking()
.then((fetchedData) => {
setFutureBookings(fetchedData as Booking[]);
// setFutureBookings(fetchedData as Booking[]);
setBookingsLoading(false);
})
.catch((error) => console.error("Error fetching data:", error));
};

const fetchBookings = async () => {
const fetchBookings = async (clicked = false) => {
try {

if (filters.dateRange === "") {
return;
}

const bookingsResponse: Booking[] = await fetchAllBookings(
pagePermission,
LIMIT,
filters,
lastItem
);
setLastItem(bookingsResponse[bookingsResponse.length - 1].requestedAt);
setAllBookings((oldBookings) => [...oldBookings, ...bookingsResponse]);



if (clicked && bookingsResponse.length === 0) {
setLoadMoreEnabled(false);
return;
}

if (clicked) {
setLastItem(bookingsResponse[bookingsResponse.length - 1]);
setAllBookings((oldBookings) => [...oldBookings, ...bookingsResponse]);
} else {
setLastItem(bookingsResponse[bookingsResponse.length - 1]);
setAllBookings(bookingsResponse);
}
setBookingsLoading(false);

} catch (error) {
console.error("Error fetching data:", error);
}
Expand Down Expand Up @@ -418,7 +449,6 @@ export const DatabaseProvider = ({
value={{
adminUsers,
bannedUsers,
futureBookings,
allBookings,
liaisonUsers,
equipmentUsers,
Expand All @@ -434,6 +464,7 @@ export const DatabaseProvider = ({
netId,
bookingsLoading,
userApiData,
loadMoreEnabled,
reloadAdminUsers: fetchAdminUsers,
reloadApproverUsers: fetchApproverUsers,
reloadBannedUsers: fetchBannedUsers,
Expand All @@ -445,6 +476,9 @@ export const DatabaseProvider = ({
reloadSafetyTrainedUsers: fetchSafetyTrainedUsers,
setUserEmail,
fetchAllBookings: fetchBookings,
setFilters: setFilters,
setLoadMoreEnabled,
setLastItem,
}}
>
{children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { Box } from "@mui/material";
import { DateRangeFilter } from "./hooks/getDateFilter";
import Dropdown from "../../booking/components/Dropdown";
import FilterList from "@mui/icons-material/FilterList";
import React from "react";
import React, { useContext } from "react";
import StatusChip from "./StatusChip";
import { DatabaseContext } from "../Provider";

interface Props {
allowedStatuses: BookingStatusLabel[];
Expand All @@ -24,6 +25,7 @@ export default function BookingTableFilters({
selectedDateRange,
setSelectedDateRange,
}: Props) {
const { setLoadMoreEnabled, setLastItem } = useContext(DatabaseContext);
const handleChipClick = (status: BookingStatusLabel) => {
setSelectedStatuses((prev: BookingStatusLabel[]) => {
if (prev.includes(status)) {
Expand All @@ -39,6 +41,8 @@ export default function BookingTableFilters({
) => {
if (newFilter != null) {
setSelectedDateRange(newFilter);
setLoadMoreEnabled(true);
setLastItem(null);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const Bookings: React.FC<BookingsProps> = ({
pageContext,
calendarEventId,
}) => {
const { futureBookings, bookingsLoading, reloadFutureBookings, fetchAllBookings, allBookings } =
const { bookingsLoading, reloadFutureBookings, fetchAllBookings, allBookings, loadMoreEnabled } =
useContext(DatabaseContext);
const allowedStatuses = useAllowedStatuses(pageContext);

Expand All @@ -41,13 +41,13 @@ export const Bookings: React.FC<BookingsProps> = ({
calendarEventId ? "All Future" : "Today"
);
const [orderBy, setOrderBy] = useState<keyof BookingRow>("startDate");
const [order, setOrder] = useState<ColumnSortOrder>("asc");
const [order, setOrder] = useState<ColumnSortOrder>("desc");

const isUserView = pageContext === PageContextLevel.USER;

useEffect(() => {
reloadFutureBookings();
}, []);
// useEffect(() => {
// reloadFutureBookings();
// }, []);

const filteredRows = useBookingFilters({
pageContext,
Expand Down Expand Up @@ -103,7 +103,7 @@ export const Bookings: React.FC<BookingsProps> = ({
}, [pageContext, statusFilters, allowedStatuses, selectedDateRange]);

const bottomSection = useMemo(() => {
if (bookingsLoading && futureBookings.length === 0) {
if (bookingsLoading && allBookings.length === 0) {
return (
<TableEmpty>
<Loading />
Expand Down Expand Up @@ -206,35 +206,10 @@ export const Bookings: React.FC<BookingsProps> = ({
closeModal={() => setModalData(null)}
/>
)}
{!isUserView && (
<Box marginTop={5}>
<Box sx={{ display: "flex", justifyContent: "center" }}>
<Typography>Previous Bookings</Typography>
</Box>
<Table
{...{ columns}}
sx={{
borderRadius: isUserView ? "0px" : "",
}}
>
{allBookings.map((row: BookingRow) => (
<BookingTableRow
key={row.calendarEventId}
{...{
booking: row,
calendarEventId,
pageContext,
isUserView,
setModalData,
}}
/>
))}
</Table>
<Box sx={{ display: "flex", justifyContent: "center" }}>
<Button onClick={fetchAllBookings}>Load More</Button>
</Box>
</Box>
)}
{loadMoreEnabled &&
(<Box sx={{ display: "flex", justifyContent: "center" }}>
<Button onClick={() => { fetchAllBookings(true) }}>Load More</Button>
</Box>)}
</Box>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const DATE_FILTERS: Record<DateRangeFilter, (x: Booking) => boolean> = {
date.getDate() === today.getDate()
);
},

"This Week": (row) => {
const today = new Date();
let dayOfWeek = today.getDay();
Expand All @@ -34,5 +35,55 @@ export const DATE_FILTERS: Record<DateRangeFilter, (x: Booking) => boolean> = {
const date = row.startDate.toDate();
return date >= startOfWeek && date <= endOfWeek;
},
"All Future": (row) => true,

"All Future": (row) => {
const today = new Date();
return row.startDate.toDate() >= today;
},

"Past 24 hours": (row) => {
const today = new Date();
const date = row.startDate.toDate();
const diff = today.getTime() - date.getTime();

// Check that the date is within the past 24 hours and not in the future
return diff >= 0 && diff < 24 * 60 * 60 * 1000;
},

"Past Week": (row) => {
const today = new Date();
today.setHours(0, 0, 0, 0); // Reset today to midnight

const date = row.startDate.toDate();
const diff = today.getTime() - date.getTime();

// Check that the date is within the past 7 days and not in the future
return diff >= 0 && diff < 7 * 24 * 60 * 60 * 1000;
},

"Past Month": (row) => {
const today = new Date();
const date = row.startDate.toDate();
const diff = today.getTime() - date.getTime();

// Check that the date is within the past 30 days and not in the future
return diff >= 0 && diff < 30 * 24 * 60 * 60 * 1000;
},

"Past 6 Months": (row) => {
const today = new Date();
const date = row.startDate.toDate();
const diff = today.getTime() - date.getTime();

// Check that the date is within the past 6 months and not in the future
return diff >= 0 && diff < 6 * 30 * 24 * 60 * 60 * 1000;
},

"All Past": (row) => {
const today = new Date();
const date = row.startDate.toDate();

// Check that the date is in the past (not in the future)
return today.getTime() - date.getTime() >= 0;
},
};
Loading

0 comments on commit f301ba4

Please sign in to comment.