diff --git a/src/api/supabase/queries/order_queries.ts b/src/api/supabase/queries/order_queries.ts index c6dd0e59..4bc18b59 100644 --- a/src/api/supabase/queries/order_queries.ts +++ b/src/api/supabase/queries/order_queries.ts @@ -56,30 +56,6 @@ export async function fetchOrderByUUID( } } -export async function getOrdersByUserId( - userId: string, -): Promise< - PostgrestSingleResponse | { data: never[]; error: PostgrestError } -> { - try { - const { data: orders, error } = await supabase - .from('order') - .select('*') - .eq('user_id', userId) - .single(); - - if (error) { - console.error('Error fetching orders:', error); - return { data: [], error }; - } - - return orders; - } catch (error) { - console.error('Error:', error); - throw error; - } -} - // Function to get an order by its ID export async function getOrderById( orderId: string, @@ -160,3 +136,74 @@ export async function updateAllOrdersProgressToTrue(): Promise< return 'Update failed'; // Return an error message if an exception occurs } } + +export async function createOrder(userId: string) { + // Fetch the user's cart + const { data, error } = await supabase + .from('profiles') + .select('*') + .eq('user_id', userId) + .single(); + + if (error) { + throw new Error(`Error fetching user's cart: ${error.message}`); + } + + if (!data) { + throw new Error('User not found.'); + } + + // Extract user's cart + const userCart = data.cart; + console.log('userCart:', userCart); + // Create a new order with user's cart + const { error: orderError } = await supabase.from('order').insert({ + user_id: userId, + order_cart: userCart, // Assuming cart in the order table is designed to accept the same structure as cart_items in users table + pickup_time: null, + }); + + if (orderError) { + throw new Error(`Error creating order: ${orderError.message}`); + } + + // Reset user's cart to an empty object + const { error: resetCartError } = await supabase + .from('profiles') + .update({ cart: {} }) + .eq('user_id', userId); + + if (resetCartError) { + throw new Error(`Error resetting user's cart: ${resetCartError.message}`); + } +} + +function sortOrdersByCreated(orders: Order[]) { + return orders.sort( + (a, b) => + new Date(b.created_at).getTime() - new Date(a.created_at).getTime(), + ); +} + +export async function fetchOrdersByUserId(userId: string) { + const { data, error } = await supabase + .from('order') + .select('*') + .eq('user_id', userId); + + if (error) { + throw new Error(`Error fetching orders for user: ${error.message}`); + } + + return data || []; +} + +export async function fetchOrdersByUserIdSorted(userId: string) { + const orders = await fetchOrdersByUserId(userId); + return sortOrdersByCreated(orders); +} + +export async function fetchNOrdersByUserIdSorted(userId: string, n: number) { + const orders = await fetchOrdersByUserId(userId); + return sortOrdersByCreated(orders).slice(0, n); +} diff --git a/src/api/supabase/queries/tests/order_test.ts b/src/api/supabase/queries/tests/order_test.ts index 47510f91..bf4b87d2 100644 --- a/src/api/supabase/queries/tests/order_test.ts +++ b/src/api/supabase/queries/tests/order_test.ts @@ -4,10 +4,12 @@ import { fetchOrders, fetchOrderByUUID, - getOrdersByUserId, getOrderById, toggleOrderProgress, updateAllOrdersProgressToTrue, + fetchOrdersByUserId, + fetchNOrdersByUserIdSorted, + fetchOrdersByUserIdSorted, } from '../order_queries'; // Replace './your-module' with the actual path to your module // Test fetching all orders @@ -31,17 +33,6 @@ export async function testFetchOrderByUUID() { } } -// Test fetching orders by user ID -export async function testGetOrdersByUserId() { - const userId = '3b4a1317-b9ea-4cbd-95d7-e959aa80d1ea'; // Replace with a valid user ID - try { - const result = await getOrdersByUserId(userId); - console.log('Get Orders by User ID Result:', result); - } catch (error) { - console.error('Test Get Orders by User ID Error:', error); - } -} - // Test fetching an order by ID export async function testGetOrderById() { const orderId = '2'; // Replace with a valid order ID @@ -73,3 +64,18 @@ export async function testUpdateAllOrdersProgressToTrue() { console.error('Test Update All Orders Progress Error:', error); } } + +export async function fullOrderTest() { + const testUserId = '4a934844-76fa-4a1a-80d7-fa00597398e1'; + try { + // createOrder(testUserId); + const orders = await fetchOrdersByUserId(testUserId); + console.log(orders); + const sortedOrders = await fetchOrdersByUserIdSorted(testUserId); + console.log(sortedOrders); + const nOrders = await fetchNOrdersByUserIdSorted(testUserId, 2); + console.log(nOrders); + } catch (error) { + console.error('Error in incrementCartItemByOne:', error); + } +} diff --git a/src/app/page.tsx b/src/app/page.tsx index 2d3f74a9..aebdd407 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,48 +1,8 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ - -'use client'; - -import React, { useEffect } from 'react'; +import React from 'react'; import Link from 'next/link'; -import { fullFavItemTest } from '../api/supabase/queries/tests/user_test'; -import { - testFetchOrderByUUID, - testFetchOrders, - testGetOrderById, - testToggleOrderProgress, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - testUpdateAllOrdersProgressToTrue, -} from '../api/supabase/queries/tests/order_test'; -import { - testFetchProducts, - testFetchProductByName, -} from '../api/supabase/queries/tests/product_test'; -import { - testFetchPickupData, - testFetchPickupTimesByUUID, -} from '../api/supabase/queries/tests/pickup_test'; - -export default function Checkout() { - // testFetchUserData(); - // testFetchUserByUUID(); - // testAddUserAddress(); - // testFetchOrderByUUID(); - // testFetchOrders(); - // testGetOrderById(); - // testToggleOrderProgress(); - // testFetchProducts(); - // testFetchProductByName(); - // testFetchPickupData(); - // testFetchPickupTimesByUUID(); - // testUpdateAllOrdersProgressToTrue(); - useEffect(() => { - async function testEverything() { - await fullFavItemTest(); - } - testEverything(); - }); +export default async function Checkout() { return (
Login diff --git a/src/components/submitOrderButton.tsx b/src/components/submitOrderButton.tsx new file mode 100644 index 00000000..281ff1a5 --- /dev/null +++ b/src/components/submitOrderButton.tsx @@ -0,0 +1,31 @@ +// SubmitOrderButton.tsx +import React from 'react'; + +// Assuming that submitOrder.ts is a TypeScript file with a named export for submitOrder +// and it is located in the same directory as this component file. +import { createOrder } from '../api/supabase/queries/order_queries'; // ensure this path is correct and the file exists + +function SubmitOrderButton() { + const handleSubmit = async () => { + try { + await createOrder('some order data'); + // Replace the alert with a more user-friendly notification system if needed + } catch (error) { + // If the error is an instance of Error, we can access the message property safely. + if (error instanceof Error) { + + // Replace the alert with a more user-friendly notification system if needed + throw new Error(`Failed to submit order: ${error.message}`); + } + } + }; + + // Add type="button" to the button element + return ( + + ); +} + +export default SubmitOrderButton; diff --git a/src/schema/schema.ts b/src/schema/schema.ts index ce5a9bdb..ffdc935e 100644 --- a/src/schema/schema.ts +++ b/src/schema/schema.ts @@ -16,6 +16,7 @@ export type Order = { user_id: string; // UUID not null status: string; // bigint null pickup_time: number; // bigint null + created_at: string; // timestamp with time zone not null default now(); }; export type Schedule = {