Skip to content

Commit

Permalink
Merge pull request #123 from ThatNinjaGuy/develop
Browse files Browse the repository at this point in the history
Enable multi restaurant support and updated logic to have segregation. #111 #110
  • Loading branch information
ThatNinjaGuy authored Oct 13, 2024
2 parents 2efbef7 + 8b04962 commit 2571719
Show file tree
Hide file tree
Showing 23 changed files with 803 additions and 348 deletions.
121 changes: 61 additions & 60 deletions .firebase/hosting.ZGlzdA.cache

Large diffs are not rendered by default.

76 changes: 62 additions & 14 deletions components/Authentication/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Platform } from "react-native";
import React, { createContext, useState, useEffect, useRef } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import LoadingScreen from "@/components/LoadingScreen/LoadingScreen";
import { fetchAllTables } from "@/firebase/queries/tables";
import { extractOrdersFromTable } from "@/utils/orderManagement";
Expand All @@ -15,6 +16,18 @@ import * as Notifications from "expo-notifications";
import { registerForPushNotificationsAsync } from "@/firebase/messaging";

const AuthContext = createContext();
const getSavedRestaurantPath = async () => {
try {
const savedPath = await AsyncStorage.getItem("restaurantPath");
if (savedPath) {
const parsedPath = JSON.parse(savedPath);
return parsedPath;
}
return undefined;
} catch (error) {
console.error("Error loading saved restaurant path:", error);
}
};

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
Expand All @@ -27,17 +40,16 @@ export const AuthProvider = ({ children }) => {
const [authInitialized, setAuthInitialized] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
const [restaurantPath, setRestaurantPath] = useState(
getSavedRestaurantPath()
);

useEffect(() => {
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
console.log("Notification received");
});
Notifications.addNotificationReceivedListener((notification) => {});

responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log("Notification response received");
});
Notifications.addNotificationResponseReceivedListener((response) => {});

return () => {
Notifications.removeNotificationSubscription(
Expand All @@ -51,9 +63,9 @@ export const AuthProvider = ({ children }) => {
setupNotificationHandler();
}, []);

const fetchHotelDetails = async () => {
const fetchHotelDetails = async (restaurantPath) => {
try {
const hotelDetails = await fetchHotelData();
const hotelDetails = await fetchHotelData(restaurantPath);
if (hotelDetails) {
setHotel(hotelDetails);
}
Expand All @@ -71,7 +83,7 @@ export const AuthProvider = ({ children }) => {
preferredLanguage: staff?.preferredLanguage || appDefaultLanguage,
});
if (staff) {
registerForPushNotificationsAsync(staff, staffs);
registerForPushNotificationsAsync(restaurantPath, staff, staffs);
}
};

Expand Down Expand Up @@ -116,15 +128,27 @@ export const AuthProvider = ({ children }) => {
const unsubscribeAuth = auth.onAuthStateChanged(handleAuthStateChange);

return () => unsubscribeAuth();
}, [authInitialized]);
}, [authInitialized, restaurantPath]);

const handleAuthStateChange = async (firebaseUser) => {
if (firebaseUser) {
try {
await fetchAllStaffs(setStaffs);
await fetchAllTables(setLiveTables, undefined);
setFirebaseUser(firebaseUser);
await fetchHotelDetails();

// Load the restaurant path from AsyncStorage
const savedPath =
restaurantPath || (await AsyncStorage.getItem("restaurantPath"));
if (
savedPath &&
savedPath.restaurantId &&
savedPath.restaurantId !== null
) {
setRestaurantPath(savedPath);

await fetchAllStaffs(savedPath, setStaffs);
await fetchAllTables(savedPath, setLiveTables);
await fetchHotelDetails(savedPath);
}
// Set up message handler
setupMessageHandler(Platform.OS);
} catch (error) {
Expand All @@ -151,13 +175,37 @@ export const AuthProvider = ({ children }) => {
}
};

useEffect(() => {
setRestaurantPath(getSavedRestaurantPath());
}, []);

const updateRestaurantPath = async (newPath) => {
try {
if (JSON.stringify(newPath) !== JSON.stringify(restaurantPath)) {
setRestaurantPath(newPath);
await AsyncStorage.setItem("restaurantPath", JSON.stringify(newPath));
}
} catch (error) {
console.error("Error updating restaurant path:", error);
}
};

if (loading) {
return <LoadingScreen />;
}

return (
<AuthContext.Provider
value={{ user, logout, liveTables, liveOrders, staffs, hotel }}
value={{
user,
logout,
liveTables,
liveOrders,
staffs,
hotel,
restaurantPath,
updateRestaurantPath,
}}
>
{children}
</AuthContext.Provider>
Expand Down
88 changes: 20 additions & 68 deletions components/RestaurantOverview/Overview.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import React, { useEffect, useState, useContext } from "react";
import { StyleSheet } from "react-native";
import { ThemedText } from "@/components/common/ThemedText";
import { ThemedView } from "@/components/common/ThemedView";
import { Platform } from "react-native";
import { db } from "@/firebase/firebaseConfig";
import { completedOrderPath } from "@/firebase/queries/completedOrder";
import { INDIAN_RUPPEE_SYMBOL } from "@/constants/common";
import {
ACTIVE_ORDERS,
Expand All @@ -20,9 +17,10 @@ import {
getRevenueTodayTranslation,
} from "@/utils/appText/homeScreen";
import AuthContext from "@/components/Authentication/AuthProvider";
import { fetchCompletedOrderSummary } from "@/firebase/queries/completedOrder";

const Overview = ({ preferredLanguage }) => {
const { liveTables, liveOrders } = useContext(AuthContext);
const { liveTables, liveOrders, restaurantPath } = useContext(AuthContext);
const ACTIVE_TABLES_TEXT = getActiveTablesTranslation(preferredLanguage);
const ACTIVE_ORDERS_TEXT = getActiveOrdersTranslation(preferredLanguage);
const IN_KITCHEN_ORDERS_TEXT =
Expand All @@ -42,64 +40,24 @@ const Overview = ({ preferredLanguage }) => {
]);

useEffect(() => {
const getCompletedOrderSummary = async () => {
try {
let unsubscribe;

if (Platform.OS === "web") {
const { collection, query, onSnapshot } = await import(
"firebase/firestore"
);
const completedOrdersRef = collection(db, completedOrderPath);
const q = query(completedOrdersRef);
unsubscribe = onSnapshot(q, handleQuerySnapshot);
} else {
// Android/iOS
const completedOrdersRef = db.collection(completedOrderPath);
unsubscribe = completedOrdersRef.onSnapshot(handleQuerySnapshot);
}

// Clean up the listener on component unmount
return () => unsubscribe();
} catch (error) {
console.error("Error fetching completed order summary:", error);
fetchCompletedOrderSummary(
restaurantPath,
({ orderCountToday, revenueToday }) => {
setOverviewItems((prevItems) =>
prevItems.map((item) => {
if (item.title === COMPLETED_BOOKINGS_TEXT) {
return { ...item, message: orderCountToday };
} else if (item.title === REVENUE_TODAY_TEXT) {
return {
...item,
message: `${INDIAN_RUPPEE_SYMBOL} ${revenueToday}`,
};
}
return item;
})
);
}
};

const handleQuerySnapshot = (querySnapshot) => {
let orderCountToday = 0;
let revenueToday = 0;

// Set current day to midnight
const midnightToday = new Date();
midnightToday.setHours(0, 0, 0, 0);

querySnapshot.docs.forEach((doc) => {
const data = doc.data();
const orderDate = data.bookingTime.toDate();

// Calculate order count and revenue for today
if (orderDate >= midnightToday) {
orderCountToday++;
revenueToday += data.orderValue;
}
});

// Update overview items using functional update
setOverviewItems((prevItems) =>
prevItems.map((item) => {
if (item.title === COMPLETED_BOOKINGS_TEXT) {
return { ...item, message: orderCountToday };
} else if (item.title === REVENUE_TODAY_TEXT) {
return {
...item,
message: `${INDIAN_RUPPEE_SYMBOL} ${revenueToday}`,
};
}
return item;
})
);
};
);

const getActiveOrdersSummary = () => {
const activeTables = liveTables.filter(
Expand Down Expand Up @@ -131,13 +89,7 @@ const Overview = ({ preferredLanguage }) => {
};

getActiveOrdersSummary();
getCompletedOrderSummary();

// Clean up function
return () => {
// Any cleanup code if needed
};
}, [liveTables, liveOrders]);
}, [liveTables, liveOrders, restaurantPath]);

return (
<ThemedView style={styles.overviewContainer}>
Expand Down
5 changes: 4 additions & 1 deletion components/Settings/Settings.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useContext, useState } from "react";
import {
View,
TextInput,
Expand All @@ -22,8 +22,10 @@ import {
DEFAULT_NOTIFICATION_SETTINGS,
NOTIFICATION_SETTINGS_LABELS,
} from "@/constants/notificationControls";
import AuthContext from "@/components/Authentication/AuthProvider";

const SettingsScreen = ({ userDetails, staffs, onCancel }) => {
const { restaurantPath } = useContext(AuthContext);
const [name, setName] = useState(userDetails?.name || "");
const [age, setAge] = useState(userDetails?.age || "");
const [email, setEmail] = useState(userDetails?.email || "");
Expand Down Expand Up @@ -52,6 +54,7 @@ const SettingsScreen = ({ userDetails, staffs, onCancel }) => {
const onUpdate = async () => {
setLoading(true);
await updateStaff(
restaurantPath,
userDetails.id,
{
...userDetails,
Expand Down
7 changes: 6 additions & 1 deletion firebase/messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { messaging } from "./firebaseConfig"; // Import your Firebase app instan
import { getToken } from "firebase/messaging";
import { updateStaff } from "@/firebase/queries/staffs";

export async function registerForPushNotificationsAsync(user, allUsers) {
export async function registerForPushNotificationsAsync(
restaurantPath,
user,
allUsers
) {
if (!user || !allUsers) return;
let token;

Expand Down Expand Up @@ -54,6 +58,7 @@ export async function registerForPushNotificationsAsync(user, allUsers) {
if (!notificationTokens.includes(token)) {
notificationTokens.push(token);
updateStaff(
restaurantPath,
user.id,
{
...user,
Expand Down
4 changes: 4 additions & 0 deletions firebase/queries/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const constructHotelPath = (restaurantPath) => {
const { countryId, stateId, cityId, restaurantId } = restaurantPath;
return `restaurants/${countryId}/states/${stateId}/cities/${cityId}/hotels/${restaurantId}`;
};
Loading

0 comments on commit 2571719

Please sign in to comment.