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/submit order #25

Closed
wants to merge 13 commits into from
95 changes: 71 additions & 24 deletions src/api/supabase/queries/order_queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,30 +56,6 @@ export async function fetchOrderByUUID(
}
}

export async function getOrdersByUserId(
userId: string,
): Promise<
PostgrestSingleResponse<Order[]> | { 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,
Expand Down Expand Up @@ -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);
}
30 changes: 18 additions & 12 deletions src/api/supabase/queries/tests/order_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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);
}
}
44 changes: 2 additions & 42 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<main>
<Link href="/login">Login</Link>
Expand Down
31 changes: 31 additions & 0 deletions src/components/submitOrderButton.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<button type="button" onClick={handleSubmit}>
Submit Order
</button>
);
}

export default SubmitOrderButton;
1 change: 1 addition & 0 deletions src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Loading