Skip to content

Commit

Permalink
Merge pull request #24 from calblueprint/kevincai/favorite_items
Browse files Browse the repository at this point in the history
kevin_cai/Fav_Items
  • Loading branch information
EthanAuyeung authored Nov 6, 2023
2 parents 7ba4589 + 54a738f commit 23cf026
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 65 deletions.
41 changes: 23 additions & 18 deletions src/api/supabase/queries/tests/user_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,43 @@
import {
fetchUserData,
fetchUserByUUID,
addUserAddress,
fetchFavoriteItems,
addToFavorites,
removeFromFavorites,
} 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 fullFavItemTest() {
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);
addToFavorites(testUserId, testItemId);
let result1 = await fetchFavoriteItems(testUserId);
console.log('fetchFavoriteItems Result:', result1);
removeFromFavorites(testUserId, testItemId);
result1 = await fetchFavoriteItems(testUserId);
console.log('fetchFavoriteItems Result:', result1);
} catch (error) {
console.error('Test Add User Address Error:', error);
console.error('Error in incrementCartItemByOne:', error);
}
}
120 changes: 79 additions & 41 deletions src/api/supabase/queries/user_queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ export async function fetchUserData(): Promise<
PostgrestSingleResponse<User[]> | { data: never[]; error: PostgrestError }
> {
try {
const { data: users, error } = await supabase
.from('profiles')
.select('*')
.single();
const { data: users, error } = await supabase.from('profiles').select('*');

if (error) {
console.error('Error fetching data:', error);
Expand Down Expand Up @@ -56,47 +53,88 @@ export async function fetchUserByUUID(uuid: string) {
}
}

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();
export async function fetchFavoriteItems(
userId: string,
): Promise<Record<string, number>> {
// Fetch fav_items for the specified user
const { data, error } = await supabase
.from('profiles')
.select('fav_items')
.eq('user_id', userId)
.single();

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

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

const { data, error } = await supabase
.from('profiles')
.update({
street: updatedStreet,
city: updatedCity,
zipcode: updatedZipcode,
})
.eq('user_id', uuid)
.single();
export async function addToFavorites(userId: string, productId: string) {
// First, fetch the current fav_items for the user
const { data, error } = await supabase
.from('profiles')
.select('fav_items')
.eq('user_id', userId)
.single();

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

return { data, error: null, status: 200, statusText: 'OK', count: 1 };
} catch (error) {
console.error('Error:', error);
throw error;
const currentFavItems = data?.fav_items || {};

// Add the product to fav_items or update its quantity
currentFavItems[productId] = currentFavItems[productId] || 0;

// Now update the user's fav_items in the database
const updateResponse = await supabase
.from('profiles')
.update({ fav_items: currentFavItems })
.eq('user_id', userId);

if (updateResponse.error) {
throw new Error(
`An error occurred when trying to update the user's favorite items: ${updateResponse.error.message}`,
);
}
}

// Function to remove a product from fav_items
export async function removeFromFavorites(userId: string, productId: string) {
// First, fetch the current fav_items for the user
const { data, error } = await supabase
.from('profiles')
.select('fav_items')
.eq('user_id', userId)
.single();

if (error) {
throw new Error(
`An error occurred when trying to fetch the user's favorite items: ${error.message}`,
);
}

const currentFavItems = data?.fav_items || {};

// Remove the product from fav_items
delete currentFavItems[productId];
console.log(currentFavItems);
// Now update the user's fav_items in the database
const updateResponse = await supabase
.from('profiles')
.update({ fav_items: currentFavItems })
.eq('user_id', userId);

if (updateResponse.error) {
throw new Error(
`An error occurred when trying to update the user's favorite items: ${updateResponse.error.message}`,
);
}
}
18 changes: 12 additions & 6 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* 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 { fullFavItemTest } from '../api/supabase/queries/tests/user_test';
import {
testFetchOrderByUUID,
testFetchOrders,
Expand All @@ -24,7 +24,7 @@ import {
} from '../api/supabase/queries/tests/pickup_test';

export default function Checkout() {
testFetchUserData();
// testFetchUserData();
// testFetchUserByUUID();
// testAddUserAddress();
// testFetchOrderByUUID();
Expand All @@ -36,6 +36,12 @@ export default function Checkout() {
// testFetchPickupData();
// testFetchPickupTimesByUUID();
// testUpdateAllOrdersProgressToTrue();
useEffect(() => {
async function testEverything() {
await fullFavItemTest();
}
testEverything();
});

return (
<main>
Expand Down

1 comment on commit 23cf026

@vercel
Copy link

@vercel vercel bot commented on 23cf026 Nov 6, 2023

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.