Skip to content

Commit

Permalink
Merge pull request #37 from calblueprint/buyankhuu/OrderConfirmationP…
Browse files Browse the repository at this point in the history
…ages

Buyankhuu/order confirmation pages
  • Loading branch information
BuyankhuuTsCAl authored Jan 12, 2024
2 parents 56a8335 + d68a88c commit c831426
Show file tree
Hide file tree
Showing 42 changed files with 679 additions and 395 deletions.
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib",
"editor.codeActionsOnSave": { "source.fixAll.eslint": true },
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.formatOnSave": true,
"files.autoSave": "onFocusChange"
}
93 changes: 73 additions & 20 deletions src/api/supabase/queries/cart_queries.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import supabase from '../createClient';

import { fetchUser } from './user_queries';
import { Product, ProductWithQuantity } from '../../../schema/schema';
import { fetchProductByID } from './product_queries';

// define cart item type
export type CartItem = {
Expand All @@ -16,9 +18,9 @@ export type CartItem = {
*/
export async function fetchCartItem(cartItemID: number): Promise<CartItem> {
const { data, error } = await supabase
.from('cart_items')
.from('order_product')
.select('*')
.match({ id: cartItemID })
.eq('id', cartItemID)
.single();
if (error) {
throw new Error(`Error fetching cart item: ${error.message}`);
Expand All @@ -43,24 +45,32 @@ export async function fetchCart(): Promise<CartItem[]> {
.from('order')
.select('*')
.match({ id: cartID })
.single();
.limit(1);

if (error) {
throw new Error(`Error fetching cart: ${error.message}`);
}

// Check if data is null (cart not found)
if (!data) {
throw new Error('Cart not found.');
const products = data[0].order_product_id_array;
if (products !== null && products !== undefined) {
const productPromises = products.map(async (productID: number) => {
const product = await fetchCartItem(productID);
return product;
});
const fetchedProducts = await Promise.all(productPromises);
return fetchedProducts;
}

const products = data.product_id_array;
const productPromises = products.map(async (productID: number) => {
const product = await fetchCartItem(productID);
return [] as CartItem[];
}

export async function fetchCartItems(): Promise<Product[]> {
const cart = await fetchCart();
const productPromises = cart.map(async (item: CartItem) => {
const product = await fetchProductByID(item.product_id);
return product;
});

const fetchedProducts = await Promise.all(productPromises);

return fetchedProducts;
}

Expand All @@ -72,7 +82,7 @@ export async function fetchCart(): Promise<CartItem[]> {
async function updateCart(cartID: number, cartIDArray: number[]) {
await supabase
.from('order')
.update({ cart_id_array: cartIDArray })
.update({ order_product_id_array: cartIDArray })
.match({ id: cartID });
}

Expand All @@ -85,16 +95,22 @@ export async function addToCart(productID: number, quantity: number) {
const items = await fetchCart();

// check if product is already in cart
const existingItem = items.find(item => item.product_id === productID);

const existingItem = items.find(
item => Number(item.product_id) === Number(productID),
);

if (existingItem) {
const newQuantity = existingItem.quantity + quantity;
await supabase
.from('cart_items')
.update({ quantity: newQuantity })
.match({ id: existingItem.id });
if (existingItem !== undefined && existingItem !== null) {
const newQuantity = existingItem.quantity + quantity;
await supabase
.from('order_product')
.update({ quantity: newQuantity })
.match({ id: existingItem.id });
}
} else {
const { data, error } = await supabase
.from('cart_items')
.from('order_product')
.insert([{ product_id: productID, quantity }])
.select('*')
.single();
Expand Down Expand Up @@ -122,7 +138,7 @@ export async function decreaseFromCart(productID: number, quantity: number) {
const newQuantity = existingItem.quantity - quantity;
if (newQuantity <= 0) {
await supabase
.from('cart_items')
.from('order_product')
.delete()
.match({ id: existingItem.id })
.select('*')
Expand All @@ -135,6 +151,11 @@ export async function decreaseFromCart(productID: number, quantity: number) {
const index = productIdArray.indexOf(existingItem.id);
productIdArray.splice(index, 1);
updateCart(cartID, productIdArray);
} else {
await supabase
.from('order_product')
.update({ quantity: newQuantity })
.eq('id', existingItem.id);
}
}
}
Expand All @@ -155,3 +176,35 @@ export async function clearCart() {
const cartID = user.cart_id;
updateCart(cartID, []);
}

/**
* @returns the number of items stored within the cart if there is no items then returns 0
*/

export async function totalNumberOfItemsInCart(): Promise<number> {
const cart = await fetchCart();
if (cart.length === 0 || cart === null || cart === null) {
return 0;
}
return cart.reduce((acc, item) => acc + item.quantity, 0);
}

export async function fetchCartItemsWithQuantity(): Promise<
ProductWithQuantity[]
> {
const cart = await fetchCart();
const productPromises = cart.map(async (item: CartItem) => {
const product = await fetchProductByID(item.product_id);
return {
name: product.name,
quantity: item.quantity,
photo: product.photo,
id: product.id,
category: product.category,
};
});

const fetchedProducts = await Promise.all(productPromises);

return fetchedProducts;
}
12 changes: 0 additions & 12 deletions src/api/supabase/queries/product_queries.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Product } from '../../../schema/schema';
import supabase from '../createClient';
import { fetchCart } from './cart_queries';

/**
* Fetches all products from the database.
Expand Down Expand Up @@ -34,17 +33,6 @@ export async function fetchProductByID(productId: number): Promise<Product> {
return product;
}

/**
* @returns the number of items stored within the cart if there is no items then returns 0
*/

export async function totalNumberOfItemsInCart(): Promise<number> {
const cart = await fetchCart();
if (cart.length === 0) {
return 0;
}
return cart.reduce((acc, item) => acc + item.quantity, 0);
}
/**
* @param productType
* @returns the products that match the productType
Expand Down
2 changes: 1 addition & 1 deletion src/api/supabase/queries/user_queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export async function addOrRemoveProductFromFavorite(
const productID = product.id;

if (isFav) {
favItems.push();
favItems.push(productID);
} else {
const index = favItems.indexOf(productID);
favItems.splice(index, 1);
Expand Down
12 changes: 9 additions & 3 deletions src/app/[productId]/Buttons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ import {
PlusMinusButton,
} from './styles';

export default function Buttons() {
import { addToCart } from '../../api/supabase/queries/cart_queries';

export default function Buttons(props: { productNumber: number }) {
const [quantity, setQuantity] = useState<number>(1);
const { productNumber } = props;

const increaseQuantity = () => {
setQuantity(quantity + 1);
Expand All @@ -21,7 +24,10 @@ export default function Buttons() {
};

// used hyphen instead of dash for display
const notify = () => toast(`you have added ${quantity} items to the cart!`);
const changeCart = () => {
addToCart(productNumber, quantity);
toast(`you have added ${quantity} items to the cart!`);
};

return (
<ButtonsWrapper>
Expand All @@ -35,7 +41,7 @@ export default function Buttons() {
</PlusMinusButton>
</QuantityButton>

<AddToCartButton onClick={notify}>Add to cart</AddToCartButton>
<AddToCartButton onClick={changeCart}>Add to cart</AddToCartButton>
</ButtonsWrapper>
);
}
21 changes: 4 additions & 17 deletions src/app/[productId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
'use client';

import Link from 'next/link';
import Image from 'next/image';
import { useEffect, useState } from 'react';
import { fetchProductByID } from '../../api/supabase/queries/product_queries';
import BackButton from '../../components/BackButton/BackButton';
import 'react-toastify/dist/ReactToastify.css';

import {
BackButton,
ImageContainer,
TextContainer,
DescriptionContainer,
ToastPopUP,
} from './styles';
import { GlobalStyle } from '../../styles/components';
import NavBar from '../../components/NavBar';
import NavBar from '../../components/NavBarFolder/NavBar';
import { Product } from '../../schema/schema';
import Buttons from './Buttons';

Expand Down Expand Up @@ -43,25 +41,14 @@ export default function ItemDisplay({
return (
<main>
<GlobalStyle />

<NavBar />
<ToastPopUP
position="top-right"
autoClose={500}
limit={1}
hideProgressBar
/>
<BackButton>
<Link href="/storefront">
<Image
src="/images/Arrow_Left_MD.png"
alt="Back Arrow"
width={20}
height={20}
/>
<span style={{ marginLeft: '8px' }}>Back</span>
</Link>
</BackButton>
<BackButton destination="./storefront" />
<DescriptionContainer>
<ImageContainer>
<img
Expand All @@ -75,7 +62,7 @@ export default function ItemDisplay({
<h4 style={{ fontWeight: 'normal', paddingTop: '5px' }}>
{Item?.category}
</h4>
<Buttons />
<Buttons productNumber={params.productId} />
<p style={{ paddingTop: '50px' }}>Product ID: {Item?.id}</p>
<p style={{ paddingTop: '20px' }}>Product Details:</p>
<p>{Item?.description}</p>
Expand Down
1 change: 0 additions & 1 deletion src/app/[productId]/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,5 @@ export const AddToCartButton = styled.button`
export const ToastPopUP = styled(ToastContainer)`
position: fixed;
z-index: 100;
transform: translatey(130px);
`;
49 changes: 42 additions & 7 deletions src/app/cart/Buttons.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,52 @@
import React, { useState } from 'react';
import React from 'react';

import { ButtonsWrapper, QuantityButton, PlusMinusButton } from './styles';

export default function Buttons() {
const [quantity, setQuantity] = useState<number>(1);
import {
decreaseFromCart,
addToCart,
} from '../../api/supabase/queries/cart_queries';

import { ProductWithQuantity } from '../../schema/schema';

export default function Buttons(props: {
productNumber: number;
quantity: number;
setNumberOfItems: (count: number) => void;
numberOfItems: number;
count: number;
setCount: (count: number) => void;
cart: ProductWithQuantity[];
setCart: (category: ProductWithQuantity[]) => void;
}) {
const {
productNumber,

setNumberOfItems,
numberOfItems,
count,
setCount,
cart,
setCart,
} = props;

const increaseQuantity = () => {
setQuantity(quantity + 1);
setCount(count + 1);
addToCart(productNumber, 1);
setNumberOfItems(numberOfItems + 1);
const indexOfItem = cart.findIndex(item => item.id === productNumber);
cart[indexOfItem].quantity += 1;
setCart(cart);
};

const decreaseQuantity = () => {
if (quantity > 1) {
setQuantity(quantity - 1);
if (count > 1) {
setCount(count - 1);
decreaseFromCart(productNumber, 1);
setNumberOfItems(numberOfItems - 1);
const indexOfItem = cart.findIndex(item => item.id === productNumber);
cart[indexOfItem].quantity -= 1;
setCart(cart);
}
};

Expand All @@ -23,7 +58,7 @@ export default function Buttons() {
<PlusMinusButton type="button" onClick={decreaseQuantity}>
</PlusMinusButton>
<span>{quantity}</span>
<span>{count}</span>
<PlusMinusButton type="button" onClick={increaseQuantity}>
+
</PlusMinusButton>
Expand Down
Loading

1 comment on commit c831426

@vercel
Copy link

@vercel vercel bot commented on c831426 Jan 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.