Skip to content

Commit

Permalink
Cart Backend WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinjcai committed Nov 1, 2023
1 parent d317c3d commit 18980fb
Show file tree
Hide file tree
Showing 4 changed files with 209 additions and 103 deletions.
83 changes: 66 additions & 17 deletions src/api/supabase/queries/tests/user_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,87 @@
import {
fetchUserData,
fetchUserByUUID,
addUserAddress,
fetchUserCart,
incrementCartItemByOne,
decrementCartItemByOne,
decrementCartItem,
} from '../user_queries';

export async function testFetchUserData() {
export async function runFetchUserData() {
try {
const result = await fetchUserData();
console.log('Fetch Data Result:', result);
console.log('fetchUserData Result:', result);
} catch (error) {
console.error('Test Fetch Data Error:', error);
console.error('Error in fetchUserData:', error);
}
}

export async function testFetchUserByUUID() {
const uuid = '3b4a1317-b9ea-4cbd-95d7-e959aa80d1ea'; // Replace with a valid user ID
export async function runFetchUserByUUID() {
const testUUID = 'aeaf5f6c-a8bc-41b8-9850-5fb11e1b6dea';
try {
const result = await fetchUserByUUID(uuid);
console.log('Fetch User by UUID Result:', result);
const result = await fetchUserByUUID(testUUID);
console.log('fetchUserByUUID Result:', result);
} catch (error) {
console.error('Test Fetch User by UUID Error:', error);
console.error('Error in fetchUserByUUID:', error);
}
}

export async function testAddUserAddress() {
const uuid = '3b4a1317-b9ea-4cbd-95d7-e959aa80d1ea'; // Replace with a valid user ID
const newStreet = '123 New Street';
const newCity = 'New City';
const newZipcode = '12345';
export async function runFetchUserCart() {
const testUserId = 'aeaf5f6c-a8bc-41b8-9850-5fb11e1b6dea';
try {
const result = await fetchUserCart(testUserId);
console.log('fetchUserCart Result:', result);
} catch (error) {
console.error('Error in fetchUserCart:', error);
}
}

export async function runIncrementCartItemByOne() {
const testUserId = 'aeaf5f6c-a8bc-41b8-9850-5fb11e1b6dea';
const testItemId = '10';
try {
await incrementCartItemByOne(testUserId, testItemId);
const result = await fetchUserCart(testUserId);
console.log('fetchUserCart Result_1:', result);
console.log('incrementCartItemByOne executed successfully.');
} catch (error) {
console.error('Error in incrementCartItemByOne:', error);
}
}

export async function runDecrementCartItemByOne() {
const testUserId = 'aeaf5f6c-a8bc-41b8-9850-5fb11e1b6dea';
const testItemId = '10';
try {
await decrementCartItemByOne(testUserId, testItemId);
const result = await fetchUserCart(testUserId);
console.log('fetchUserCart Result_1:', result);
console.log('incrementCartItemByOne executed successfully.');
} catch (error) {
console.error('Error in incrementCartItemByOne:', error);
}
}

export async function fullCartTest() {
const testUserId = '4a934844-76fa-4a1a-80d7-fa00597398e1';
const testItemId = '10';
try {
const result = await addUserAddress(uuid, newStreet, newCity, newZipcode);
console.log('Add User Address Result:', result);
const result = await fetchUserByUUID(testUserId);
console.log('fetchUserData Result:', result);
await incrementCartItemByOne(testUserId, testItemId);
await incrementCartItemByOne(testUserId, testItemId);
await incrementCartItemByOne(testUserId, testItemId);
let result_1 = await fetchUserCart(testUserId);
console.log('fetchUserCart Result_1:', result_1);
// await decrementCartItemByOne(testUserId, testItemId);
result_1 = await fetchUserCart(testUserId);
console.log('fetchUserCart Result_2:', result_1);
// await decrementCartItem(testUserId, testItemId, 6);

// result = await fetchUserCart(testUserId);
// console.log('fetchUserCart Result_2:', result);
} catch (error) {
console.error('Test Add User Address Error:', error);
console.error('Error in incrementCartItemByOne:', error);
}
}

197 changes: 137 additions & 60 deletions src/api/supabase/queries/user_queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,86 +16,163 @@ 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('users').select('*');
export async function fetchUserData()
{
const { data , error }: {data:User[] | null, error: PostgrestError| null} = await supabase.from('profiles').select('*');

if (error) {
console.error('Error fetching data:', error);
return { data: [], error };
throw new Error(`An error occured when trying to read profiles: ${error}`);
} else {
return data;
}

return { data: users } as PostgrestSingleResponse<User[]>;
} catch (error) {
console.error('Error:', error);
throw error;
}
}

export async function fetchUserByUUID(
uuid: string,
): Promise<PostgrestSingleResponse<unknown>> {
try {
const { data: user, error } = await supabase
.from('Users')
) {

const { data , error }: {data:User | null, error: PostgrestError| null} = 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(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();

if (error) {
console.error('Error fetching user data:', 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 updateCart(userId: string, currentCart: Record<string, number>) {
console.log(currentCart);
const { data, error } = await supabase
.from('users')
.update({ cart: currentCart })
.eq('user_id', userId);

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();

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.");
}
// console.log(data);
const currentCart = data.cart;
console.log(currentCart);
// Increment the item's quantity by n or set it to n if not present
currentCart[itemId] = (currentCart[itemId] || 0) + n;
console.log(currentCart);
// Use the updateCart function to update the cart in the database
await updateCart(userId, currentCart);
}

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

if (selectError) {
console.error('Error selecting user data:', selectError);
throw selectError;
}
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);

// 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('Users')
.update({
street: updatedStreet,
city: updatedCity,
zipcode: updatedZipcode,
})
.eq('user_id', uuid)
.single();
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.");
}

if (error) {
console.error('Error updating user data:', error);
throw error;
}
const currentCart = data[0].cart;

return { data, error: null, status: 200, statusText: 'OK', count: 1 };
} catch (error) {
console.error('Error:', error);
throw error;
// 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);
}




// 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;
// }

// // 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;
// }

// return { data, error: null, status: 200, statusText: 'OK', count: 1 };
// } catch (error) {
// console.error('Error:', error);
// throw error;
// }
// }
18 changes: 2 additions & 16 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import Link from 'next/link';
import {
testFetchUserData,
testFetchUserByUUID,
testAddUserAddress,
fullCartTest
} from '../api/supabase/queries/tests/user_test';
import {
testFetchOrderByUUID,
Expand All @@ -24,19 +22,7 @@ import {
} from '../api/supabase/queries/tests/pickup_test';

export default function Checkout() {
testFetchUserData();
// testFetchUserByUUID();
// testAddUserAddress();
// testFetchOrderByUUID();
// testFetchOrders();
// testGetOrderById();
// testToggleOrderProgress();
// testFetchProducts();
// testFetchProductByName();
// testFetchPickupData();
// testFetchPickupTimesByUUID();
// testUpdateAllOrdersProgressToTrue();

fullCartTest();
return (
<main>
<Link href="/login">Login</Link>
Expand Down
14 changes: 4 additions & 10 deletions src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ export type User = {
pet_information: string;
user_id: string; // UUID
order_option: boolean;
address: number; // index of the address the street, city, and zipcode to build the address
street: string[];
city: string[];
zipcode: string[];
creaed_at: string; // timestamp with time zone not null default now();
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: number; // bigint[] 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 @@ -37,8 +36,3 @@ export type Product = {
updated_at: string; // 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
};

0 comments on commit 18980fb

Please sign in to comment.