Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kevincai/back cart #26

Closed
wants to merge 26 commits into from
Closed
Show file tree
Hide file tree
Changes from 22 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 0 additions & 41 deletions src/api/supabase/queries/tests/user_test.ts

This file was deleted.

221 changes: 150 additions & 71 deletions src/api/supabase/queries/user_queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,87 +16,166 @@ const supabaseApiKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
// Initialize the Supabase client
const supabase = createClient(supabaseUrl ?? '', supabaseApiKey ?? '');

export async function fetchUserData(): Promise<
PostgrestSingleResponse<User[]> | { data: never[]; error: PostgrestError }
> {
try {
const { data: users, error } = await supabase
.from('profiles')
.select('*')
.single();

if (error) {
console.error('Error fetching data:', error);
return { data: [], error };
}
export async function fetchUserData() {
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
const { data, error }: { data: User[] | null; error: PostgrestError | null } =
await supabase.from('profiles').select('*');

return { data: users } as PostgrestSingleResponse<User[]>;
} catch (error) {
console.error('Error:', error);
throw error;
if (error) {
throw new Error(`An error occured when trying to read profiles: ${error}`);
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
} else {
return data;
}
}

export async function fetchUserByUUID(uuid: string) {
try {
const { data: user, error } = await supabase
.from('profiles')
.select('*')
.eq('user_id', uuid)
.single();

if (error) {
console.error('Error fetching user data:', error);
}
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('user_id', uuid)
.single();
if (error) {
throw new Error(`An error occured when trying to read profiles: ${error}`);
} else {
return data;
}
}

export async function fetchUserCart(
Copy link

Choose a reason for hiding this comment

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

i'd say for all queries that are rn taking the userId as a parameter, you can remove it. i don't think yall are using an auth/profile context, so i'd say when you're calling these queries from your components, it's probably easier to just omit getting the userId there and passing it to the queries. rather i'd say it'd be easier to just use the supabase.auth.getUser() function (which returns current logged in user which makes sense b/c all of these queries should only be available to person who's logged in at the moment) inside these queries and you can get the userId off of the object returned here.

userId: string,
): Promise<Record<string, number>> {
const { data, error }: { data: User | null; error: PostgrestError | null } =
await supabase.from('profiles').select('*').eq('user_id', userId).single();
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved

return user;
} catch (error) {
console.error('Error:', error);
throw error;
if (error) {
throw new Error(
`An error occurred when trying to fetch the cart: ${error.message}`,
);
} else if (!data) {
throw new Error('No user found with the specified user_id.');
}

return data.cart;
}

export async function addUserAddress(
uuid: string,
newStreet: string,
newCity: string,
newZipcode: string,
): Promise<PostgrestSingleResponse<unknown>> {
try {
const { data: existingUser, error: selectError } = await supabase
.from('profiles')
.select('street, city, zipcode')
.eq('user_id', uuid)
.single();

if (selectError) {
console.error('Error selecting user data:', selectError);
throw selectError;
}
export async function updateCart(
userId: string,
currentCart: Record<string, number>,
) {
const { data, error } = await supabase
.from('profiles')
.update({ cart: currentCart })
.eq('user_id', userId);

// Append new values to the arrays
const updatedStreet = [...(existingUser?.street || []), newStreet];
const updatedCity = [...(existingUser?.city || []), newCity];
const updatedZipcode = [...(existingUser?.zipcode || []), newZipcode];

const { data, error } = await supabase
.from('profiles')
.update({
street: updatedStreet,
city: updatedCity,
zipcode: updatedZipcode,
})
.eq('user_id', uuid)
.single();

if (error) {
console.error('Error updating user data:', error);
throw error;
}
if (error) {
throw new Error(
`An error occurred when trying to update the cart: ${error.message}`,
);
}
}

export async function incrementCartItem(
userId: string,
itemId: string,
n: number,
) {
// First, fetch the current cart for the user
const { data, error }: { data: User | null; error: PostgrestError | null } =
await supabase.from('profiles').select('*').eq('user_id', userId).single();
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved

if (error) {
throw new Error(
`An error occurred when trying to fetch the cart: ${error.message}`,
);
} else if (!data) {
throw new Error('No user found with the specified user_id.');
}

const currentCart = data.cart;

// Increment the item's quantity by n or set it to n if not present
currentCart[itemId] = (currentCart[itemId] || 0) + n;
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved

// Use the updateCart function to update the cart in the database
await updateCart(userId, currentCart);
}

return { data, error: null, status: 200, statusText: 'OK', count: 1 };
} catch (error) {
console.error('Error:', error);
throw error;
export async function incrementCartItemByOne(userId: string, itemId: string) {
return incrementCartItem(userId, itemId, 1);
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
}

export async function decrementCartItem(
userId: string,
itemId: string,
n: number,
) {
// First, fetch the current cart for the user
const { data, error }: { data: User[] | null; error: PostgrestError | null } =
await supabase.from('profiles').select('*').eq('user_id', userId);
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved

if (error) {
throw new Error(
`An error occurred when trying to fetch the cart: ${error.message}`,
);
} else if (!data || data.length === 0) {
throw new Error('No user found with the specified user_id.');
}

const currentCart = data[0].cart;

// Decrement the item's quantity by n or remove it if it's 0 or below
if (currentCart[itemId]) {
currentCart[itemId] -= n;

if (currentCart[itemId] <= 0) {
delete currentCart[itemId];
}
}

// Use the updateCart function to update the cart in the database
await updateCart(userId, currentCart);
}

export async function decrementCartItemByOne(userId: string, itemId: string) {
return decrementCartItem(userId, itemId, 1);
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
}

// export async function addUserAddress(
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
// uuid: string,
// newStreet: string,
// newCity: string,
// newZipcode: string,
// ): Promise<PostgrestSingleResponse<unknown>> {
// try {
// const { data: existingUser, error: selectError } = await supabase
// .from('profiles')
// .select('street, city, zipcode')
// .eq('user_id', uuid)
// .single();

// if (selectError) {
// throw selectError;
// }

// // Append new values to the arrays
// const updatedStreet = [...(existingUser?.street || []), newStreet];
// const updatedCity = [...(existingUser?.city || []), newCity];
// const updatedZipcode = [...(existingUser?.zipcode || []), newZipcode];

// const { data, error } = await supabase
// .from('profiles')
// .update({
// street: updatedStreet,
// city: updatedCity,
// zipcode: updatedZipcode,
// })
// .eq('user_id', uuid)
// .single();

// if (error) {
// throw error;
// }

// return { data, error: null, status: 200, statusText: 'OK', count: 1 };
// } catch (error) {
// }
// }
31 changes: 13 additions & 18 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/* eslint-disable @typescript-eslint/no-unused-vars */

'use client';

import React, { useEffect } from 'react';
import Link from 'next/link';
import {
testFetchUserData,
testFetchUserByUUID,
testAddUserAddress,
} from '../api/supabase/queries/tests/user_test';
import {
testFetchOrderByUUID,
testFetchOrders,
Expand All @@ -23,20 +21,17 @@ import {
testFetchPickupTimesByUUID,
} from '../api/supabase/queries/tests/pickup_test';

export default function Checkout() {
testFetchUserData();
// testFetchUserByUUID();
// testAddUserAddress();
// testFetchOrderByUUID();
// testFetchOrders();
// testGetOrderById();
// testToggleOrderProgress();
// testFetchProducts();
// testFetchProductByName();
// testFetchPickupData();
// testFetchPickupTimesByUUID();
// testUpdateAllOrdersProgressToTrue();
export const revalidate = 10;
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved

export default async function Checkout() {
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
// useEffect(() => {
// async function testEverything() {
// await fullCartTest();
// }
// testEverything();
// });

// await fullCartTest();
return (
<main>
<Link href="/login">Login</Link>
Expand Down
13 changes: 4 additions & 9 deletions src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ export type User = {
first_name: string;
last_name: string;
pet_information: string;
delivery_allowed: boolean;
created_at: Date; // timestamp of when record was created
cart_id: string; // UUID
order_option: boolean;
creaed_at: string; // timestamp with time zone not null default now();
kevinjcai marked this conversation as resolved.
Show resolved Hide resolved
address_id: string; // UUID
cart: Record<string, number>; // JSONB with item as key and quantity as value
};

export type Order = {
id: number; // bigint generated by default as identity
user_id: string; // UUID not null
cart: Record<string, number>; // JSONB with item as key and quantity as value
status: string; // bigint null
pickup_time: number; // bigint null
};
Expand All @@ -34,9 +35,3 @@ export type Product = {
photo: string; // text null;
updated_at: Date; // timestamp with time zone not null default now();
};

export type Cart = {
id: number; // bigint generated by default as identity
user_id: string; // UUID not null
product_id: Record<string, number>; // JSONB with item as key and quantity as value
};
22 changes: 11 additions & 11 deletions src/styles/fonts.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import styled from 'styled-components/native';

export const Heading1 = styled.Text`
font-family: public-sans;
font-size: 40px;
font-style: normal;
font-weight: 700;
line-height: normal;
font-family: public-sans;
font-size: 40px;
font-style: normal;
font-weight: 700;
line-height: normal;
`;

export const Heading4 = styled.Text`
font-family: public-sans;
font-size: 15px;
font-style: normal;
font-weight: 400;
line-height: normal;
`;
font-family: public-sans;
font-size: 15px;
font-style: normal;
font-weight: 400;
line-height: normal;
`;