Skip to content

Commit

Permalink
OrderFunctionality (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
kebab01 authored May 23, 2024
1 parent 6a9305d commit a5e914e
Show file tree
Hide file tree
Showing 12 changed files with 322 additions and 181 deletions.
27 changes: 12 additions & 15 deletions app/(tabs)/Cart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import AddIcon from "../../assets/icons/icon-add-yellow.svg";
import { SB_COLOR_SCHEME } from "@/constants";
import { MenuItem, Cart, Customer } from "@/api/schema/SwiftByteTypes";
import { Api } from "@/api/api";
import { Button } from "@swift-byte/switftbytecomponents";
import { Button, Stepper } from "@swift-byte/switftbytecomponents";
import { Link, useFocusEffect } from "expo-router";
import { useCallback, useEffect, useState } from "react";
import { NavigationProp, ParamListBase, RouteProp } from "@react-navigation/native";
Expand Down Expand Up @@ -42,8 +42,17 @@ export default function CartScreen({route, navigation}: CartProps) {
}, [displayCart]);



const handleQuantChange = (e:any) =>{
console.log(e)
}

if (Api.getApi().getActiveCustomer().cart.foodItems.length === 0) {
return (
<View style={{width:"100%", height:"100%", justifyContent:'center', alignItems:'center'}}>
<Text style={styles.subtitle}>Your cart is empty</Text>
</View>
);
}
return (
<SafeAreaView style={styles.container}>
<ScrollView style={styles.scrollView}>
Expand Down Expand Up @@ -93,19 +102,7 @@ export default function CartScreen({route, navigation}: CartProps) {
</Text>
</View>
</View>
<View style={[styles.dFlex, { flex: 1 }]}>
<MinusIcon />
<Text
style={{
marginHorizontal: 10,
fontSize: 16,
fontWeight: "500",
}}
>
{item.quantity}
</Text>
<AddIcon />
</View>
<Stepper value={item.quantity} onPress={handleQuantChange} />
</View>
);
})}
Expand Down
80 changes: 48 additions & 32 deletions app/(tabs)/Explore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@ import { View, Text } from "@/components/Themed";
import { Button, TextInput } from "@swift-byte/switftbytecomponents";
import { useEffect, useState } from "react";
import { SB_COLOR_SCHEME } from "@/constants";
import { Restaurant, categories, promoCode, restaurants } from "@/mock_data";
import { categories, promoCode } from "@/mock_data";
import StarYellowIcon from "../../assets/icons/icon-star-yellow.svg";
import { router, useLocalSearchParams } from "expo-router";
import { Api } from "@/api/api";
import { Restaurant } from "@/api/schema/SwiftByteTypes";

export default function ExploreScreen() {
const { searchValue } = useLocalSearchParams<{ searchValue: string }>();
const [search, setSearch] = useState<string>("");
const [filteredResults, setFilteredResults] =
useState<Restaurant[]>(restaurants);
useState<Restaurant[]>([]);

const [restaurants, setRestaurants] = useState<Restaurant[]>([])

useEffect(() => {
console.log("search: ", search, searchValue);
Expand All @@ -29,42 +33,54 @@ export default function ExploreScreen() {
}
}, [searchValue]);

useEffect(() => {
// fetch restaurants
async function onLoad(){
const response = await Api.getApi().getRestaurants()

if (response){
setRestaurants(response)
}
}
onLoad()
},[])

const handleSearch = (val: string) => {
setSearch(val.toLowerCase());
const result = restaurants.filter((restaurant) => {
const matchRestaurantName = restaurant.name
.toLowerCase()
.includes(val.toLowerCase());
const matchCategoryName =
restaurant.categories.filter((cat) =>
cat.name.toLowerCase().includes(val.toLowerCase())
).length > 0
? true
: false;
const matchLocation = restaurant.address.street
.toLowerCase()
.includes(val.toLowerCase());
const matchMenuName =
restaurant.menu.filter((item) =>
item.name.toLowerCase().includes(val.toLowerCase())
).length > 0
? true
: false;

if (restaurants.length === 0) return

const result = restaurants.filter((restaurant) => {
const valLower = val.toLowerCase();

const matchRestaurantName = restaurant.name.toLowerCase().includes(valLower);

const matchCategoryName = restaurant.categories.some((cat) =>
cat.toLowerCase().includes(valLower)
);

const matchLocation = restaurant.address.toLowerCase().includes(valLower);

const matchMenuName = restaurant.menu.some((item) =>
item.name.toLowerCase().includes(valLower)
);

console.log(
restaurant.name,
matchCategoryName ||
matchLocation ||
matchMenuName ||
matchRestaurantName
restaurant.name,
matchCategoryName ||
matchLocation ||
matchMenuName ||
matchRestaurantName
);

return (
matchCategoryName ||
matchLocation ||
matchMenuName ||
matchRestaurantName
matchCategoryName ||
matchLocation ||
matchMenuName ||
matchRestaurantName
);
});
});


console.log("res", search, result);
setFilteredResults(result);
Expand Down Expand Up @@ -128,7 +144,7 @@ export default function ExploreScreen() {
]}
>
<Image
source={{ uri: item.imageUrl }}
source={{ uri: item.imageURI }}
width={64}
height={64}
style={[
Expand Down
40 changes: 36 additions & 4 deletions app/(tabs)/Orders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,40 @@ export default function OrdersScreen() {
<SafeAreaView style={styles.container}>
<ScrollView style={styles.scrollView} >
<View style={styles.container}>
<View>
<View
style={{
backgroundColor: SB_COLOR_SCHEME.SB_TERTIARY,
padding: 10,
width: "30%",
borderRadius: 40,
}}
>
<Text
style={{
textAlign: "center",
fontWeight: "500",
color: SB_COLOR_SCHEME.SB_PRIMARY,
}}
>
Pending
</Text>
</View>
<View style={{ marginTop: 20 }}>
{orders?.filter((order) => order.orderStatus == "pending")
.map((item) => {
return (
<Link href={{ pathname: "/delivery/[id]", params: { id: item.id } }} key={item.id} asChild>
<TouchableOpacity
style={styles.item}
>
<Text>{item.restaurant.name}</Text>
</TouchableOpacity>
</Link>
);
})}
</View>
</View>
{/* current order */}
<View>
<View
Expand All @@ -65,8 +99,7 @@ export default function OrdersScreen() {
</Text>
</View>
<View style={{ marginTop: 20 }}>
{orders
.filter((order) => order.orderStatus == "accepted")
{orders?.filter((order) => order.orderStatus == "accepted")
.map((item) => {
return (
<Link href={{ pathname: "/delivery/[id]", params: { id: item.id } }} key={item.id} asChild>
Expand Down Expand Up @@ -101,8 +134,7 @@ export default function OrdersScreen() {
</Text>
</View>
<View style={{ marginTop: 20 }}>
{orders
.filter((order) => order.orderStatus == "completed")
{orders?.filter((order) => order.orderStatus == "completed")
.map((item) => {
return (
<Link href={"/orderHistory"} key={item.id} asChild>
Expand Down
12 changes: 12 additions & 0 deletions app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,19 @@ import { Api } from "@/api/api";
export default function HomeScreen() {
const [search, setSearch] = useState<string>("");
const [restaurants, setRestaurants] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true)


useFocusEffect(useCallback(() => {
Api.getApi().getRestaurants().then((liveRestaurants) => {
if (liveRestaurants) {
console.log("liveRestaurants: ", liveRestaurants);
setRestaurants(liveRestaurants);
setIsLoading(false);
}
else{
console.error("Failed to get restaurants")
setIsLoading(false)
}
});
}, []))
Expand Down Expand Up @@ -169,6 +176,11 @@ export default function HomeScreen() {
Popular Restaurants Nearby
</Text>
</View>
{isLoading && (
<View style={{width:'100%', justifyContent:"center", alignItems:'center'}}>
<Image source={require("../../assets/images/loading.gif")} resizeMode="contain" style={{height:100}}/>
</View>
)}
<ScrollView horizontal={true} style={styles.scrollContainer}>
<View style={[styles.dFlex, { marginTop: 16 }]}>
{restaurants.map((item) => {
Expand Down
74 changes: 50 additions & 24 deletions app/MenuItemModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default function MenuItemModal() {
const [selectedMenuItem, setSelectedMenuItem] = React.useState<MenuItem | undefined>(undefined);
const [quantity, setQuantity] = useState(1)
const [notes, setNotes] = useState("")
console.log(quantity)
const [toppings, setToppings] = useState<Topping[]>(
[
{
Expand All @@ -35,40 +36,65 @@ export default function MenuItemModal() {
const [selectedToppings, setSelectedToppings] = useState<Topping[]>([])

useFocusEffect(useCallback(() => {
Api.getApi().getRestaurants().then((liveRestaurants) => {
try{
Api.getApi().getRestaurants().then((liveRestaurants) => {
if (liveRestaurants) {
console.log("liveRestaurants: ", JSON.stringify(liveRestaurants));
if (liveRestaurants) {
setSelectedMenuItem(liveRestaurants.find((r) => r.id.toString() === restaurantId)?.menu.find((m) => m.name === menuItemName));
}
console.log("liveRestaurants: ", JSON.stringify(liveRestaurants));
if (liveRestaurants) {
setSelectedMenuItem(liveRestaurants.find((r) => r.id.toString() === restaurantId)?.menu.find((m) => m.name === menuItemName));
}
}
})
})
}
catch(error){
Alert.alert("Error", "An error occurred while fetching the menu item")
}
}, [restaurantId]))

const handlePress = () => {
if (quantity < 1) {
Alert.alert("Please add at least one item")
return
}
const activeCart = Api.getApi().getActiveCustomer()?.cart
if (!activeCart.restaurant){
Api.getApi().getRestaurant(restaurantId).then((restaurant) => {
Api.getApi().getActiveCustomer().cart.restaurant = restaurant as Restaurant
})
}

//please forgive me for this monstrocity. Blame typescript for being so good?
let activeItemIndex = Api.getApi().getActiveCustomer()?.cart.foodItems.findIndex((item) => item.name === selectedMenuItem?.name);
console.log("activeItemIndex: ", activeItemIndex)
const prevQuantity = activeItemIndex !== -1 ? Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex as number].quantity || 0 : 0
if (!(activeItemIndex == -1)){
Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex as number]["quantity"] = quantity
try{

} else if (Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex as number].quantity !== undefined) {
Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex as number].quantity = prevQuantity + quantity
}
const activeCart = Api.getApi().getActiveCustomer()?.cart
if (!activeCart.restaurant){
Api.getApi().getRestaurant(restaurantId).then((restaurant) => {
Api.getApi().getActiveCustomer().cart.restaurant = restaurant as Restaurant
})
}


router.navigate("Cart")
console.log(Api.getApi().getActiveCustomer()?.cart)
//please forgive me for this monstrocity. Blame typescript for being so good?
let activeItemIndex = Api.getApi().getActiveCustomer()?.cart.foodItems.findIndex((item) => item.name === selectedMenuItem?.name);
console.log("activeItemIndex: ", activeItemIndex)
const prevQuantity = activeItemIndex >= 0 ? Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex].quantity : 0

if (activeItemIndex === -1){
Api.getApi().getActiveCustomer().cart.foodItems.push({
...selectedMenuItem as MenuItem,
quantity: quantity,
})
}
else {
Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex].quantity = prevQuantity as number + quantity
}
// if (activeItemIndex >= 0){
// Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex]["quantity"] = quantity

// } else if (Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex]?.quantity !== undefined) {
// Api.getApi().getActiveCustomer().cart.foodItems[activeItemIndex].quantity = prevQuantity + quantity
// }

router.navigate("Cart")
}
catch(error){
console.error(error)
Alert.alert("Error", "An error occurred while adding the item to the cart")
}
}

return (
Expand All @@ -86,7 +112,7 @@ export default function MenuItemModal() {
setQuantity(e < 0 ? 0 : e)}} />
</View>
</View>
<View>
{/* <View>
<Text style={[styles.title, { marginTop: 20 }]}>Extras</Text>
{toppings.map((topping, i) => {
return (
Expand All @@ -104,7 +130,7 @@ export default function MenuItemModal() {
</View>
)
})}
</View>
</View> */}
<TextArea style={styles.textArea} value={notes} onChangeText={setNotes} placeholder='Add notes here...'/>
<Button text={`Add to Cart $${selectedMenuItem?.price as number * quantity}`} type={'primary'} onPress={handlePress} />
<StatusBar style="light" />
Expand Down
Loading

0 comments on commit a5e914e

Please sign in to comment.