-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
22 changed files
with
456 additions
and
581 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,8 @@ | ||
{ | ||
"typescript.tsdk": "node_modules\\typescript\\lib", | ||
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }, | ||
"editor.codeActionsOnSave": { | ||
"source.fixAll.eslint": "explicit" | ||
}, | ||
"editor.formatOnSave": true, | ||
"files.autoSave": "onFocusChange" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
import supabase from '../createClient'; | ||
|
||
import { fetchUser } from './user_queries'; | ||
|
||
// define cart item type | ||
export type CartItem = { | ||
id: number; | ||
product_id: number; | ||
quantity: number; | ||
}; | ||
|
||
/** | ||
* get cart item by id | ||
* @param number - cart item id | ||
* @returns Promise<CartItem> - A CartItem object. | ||
*/ | ||
export async function fetchCartItem(cartItemID: number): Promise<CartItem> { | ||
const { data, error } = await supabase | ||
.from('cart_items') | ||
.select('*') | ||
.match({ id: cartItemID }) | ||
.single(); | ||
if (error) { | ||
throw new Error(`Error fetching cart item: ${error.message}`); | ||
} | ||
return data; | ||
} | ||
|
||
/** | ||
* get cart items in a user's cart | ||
* @returns Promise<CartItem[]> - An array of CartItem objects. | ||
*/ | ||
export async function fetchCart(): Promise<CartItem[]> { | ||
const user = await fetchUser(); | ||
const cartID = user.cart_id; | ||
const { data, error } = await supabase | ||
.from('order') | ||
.select('*') | ||
.match({ id: cartID }) | ||
.single(); | ||
if (error) { | ||
throw new Error(`Error fetching cart: ${error.message}`); | ||
} | ||
const products = data.product_id_array; | ||
const productPromises = products.map(async (productID: number) => { | ||
const product = await fetchCartItem(productID); | ||
return product; | ||
}); | ||
const fetchedProducts = await Promise.all(productPromises); | ||
|
||
return fetchedProducts; | ||
} | ||
|
||
/** | ||
* update cart | ||
* @param cartID - cart id | ||
* @param cartIDArray - cart id array | ||
*/ | ||
async function updateCart(cartID: number, cartIDArray: number[]) { | ||
await supabase | ||
.from('order') | ||
.update({ cart_id_array: cartIDArray }) | ||
.match({ id: cartID }); | ||
} | ||
|
||
/** | ||
* add product to cart | ||
* @param productID - product id | ||
* @param quantity - quantity of product | ||
*/ | ||
export async function addToCart(productID: number, quantity: number) { | ||
const items = await fetchCart(); | ||
|
||
// check if product is already in cart | ||
const existingItem = items.find(item => item.product_id === productID); | ||
if (existingItem) { | ||
const newQuantity = existingItem.quantity + quantity; | ||
await supabase | ||
.from('cart_items') | ||
.update({ quantity: newQuantity }) | ||
.match({ id: existingItem.id }); | ||
} else { | ||
const { data, error } = await supabase | ||
.from('cart_items') | ||
.insert([{ product_id: productID, quantity }]) | ||
.select('*') | ||
.single(); | ||
if (error) { | ||
throw new Error(`Error adding to cart: ${error.message}`); | ||
} | ||
// append to existing cart | ||
const user = await fetchUser(); | ||
const cartID = user.cart_id; | ||
const productIdArray = items.map(item => item.id); | ||
productIdArray.push(data.id); | ||
updateCart(cartID, productIdArray); | ||
} | ||
} | ||
|
||
/** | ||
* decrease quantity of product in cart | ||
* @param productID - product id | ||
* @param quantity - quantity of product | ||
*/ | ||
export async function decreaseFromCart(productID: number, quantity: number) { | ||
const items = await fetchCart(); | ||
const existingItem = items.find(item => item.product_id === productID); | ||
if (existingItem) { | ||
const newQuantity = existingItem.quantity - quantity; | ||
if (newQuantity <= 0) { | ||
await supabase | ||
.from('cart_items') | ||
.delete() | ||
.match({ id: existingItem.id }) | ||
.select('*') | ||
.single(); | ||
|
||
// remove from existing cart | ||
const user = await fetchUser(); | ||
const cartID = user.cart_id; | ||
const productIdArray = items.map(item => item.id); | ||
const index = productIdArray.indexOf(existingItem.id); | ||
productIdArray.splice(index, 1); | ||
updateCart(cartID, productIdArray); | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* remove product from cart | ||
* @param productID - product id | ||
*/ | ||
export async function removeCartItem(productID: number) { | ||
decreaseFromCart(productID, Infinity); | ||
} | ||
|
||
/** | ||
* clear cart | ||
*/ | ||
export async function clearCart() { | ||
const user = await fetchUser(); | ||
const cartID = user.cart_id; | ||
updateCart(cartID, []); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,162 +1,95 @@ | ||
/* eslint-disable no-console */ | ||
// | ||
|
||
import { | ||
PostgrestSingleResponse, | ||
PostgrestError, | ||
createClient, | ||
} from '@supabase/supabase-js'; | ||
import { Order } from '../../../schema/schema'; | ||
|
||
// Replace these with your Supabase project URL and API key | ||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; | ||
const supabaseApiKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; | ||
|
||
// Initialize the Supabase client | ||
const supabase = createClient(supabaseUrl ?? '', supabaseApiKey ?? ''); | ||
|
||
export async function fetchOrders(): Promise< | ||
PostgrestSingleResponse<Order[]> | { data: never[]; error: PostgrestError } | ||
> { | ||
try { | ||
const { data: orders, error } = await supabase | ||
.from('order') // Update to the "Order" table | ||
.select('*'); | ||
|
||
if (error) { | ||
console.error('Error fetching data:', error); | ||
return { data: [], error }; | ||
} | ||
|
||
return { data: orders } as PostgrestSingleResponse<Order[]>; | ||
} catch (error) { | ||
console.error('Error:', error); | ||
throw error; | ||
import { fetchUser } from './user_queries'; | ||
import supabase from '../createClient'; | ||
|
||
/** | ||
* Fetches all orders from the database. | ||
* @returns Promise<Order[]> - An array of Order objects. | ||
*/ | ||
export async function getOrderById(orderId: number): Promise<Order> { | ||
const { data: order, error } = await supabase | ||
.from('order') // Update to the "Order" table | ||
.select('*') | ||
.eq('id', orderId) | ||
.single(); | ||
if (error) { | ||
throw new Error(`Error fetching order: ${error.message}`); | ||
} | ||
return order; | ||
} | ||
|
||
export async function fetchOrderByUUID( | ||
uuid: string, | ||
): Promise<PostgrestSingleResponse<Order>> { | ||
try { | ||
const { data: order, error } = await supabase | ||
.from('order') // Update to the "Order" table | ||
.select('*') | ||
.eq('id', uuid) | ||
.single(); | ||
|
||
if (error) { | ||
console.error('Error fetching order data:', error); | ||
} | ||
|
||
return order; | ||
} catch (error) { | ||
console.error('Error:', error); | ||
throw error; | ||
/** | ||
* creates a new order for the user | ||
*/ | ||
export async function createOrder() { | ||
const user = await fetchUser(); | ||
|
||
const { data: order, error } = await supabase | ||
.from('order') | ||
.insert({ user_id: user.id }) | ||
.select('*') | ||
.single(); | ||
if (error) { | ||
throw new Error(`Error creating order: ${error.message}`); | ||
} | ||
} | ||
|
||
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; | ||
} | ||
await supabase | ||
.from('users') | ||
.update({ cart_id: order.id }) | ||
.match({ id: user.id }); | ||
} | ||
|
||
// Function to get an order by its ID | ||
export async function getOrderById( | ||
orderId: string, | ||
): Promise<PostgrestSingleResponse<Order>> { | ||
try { | ||
const { data: order, error } = await supabase | ||
.from('order') | ||
.select('*') | ||
.eq('id', orderId) | ||
.single(); | ||
|
||
if (error) { | ||
console.error('Error fetching order:', error); | ||
} | ||
|
||
return order; | ||
} catch (error) { | ||
console.error('Error:', error); | ||
throw error; | ||
} | ||
/** | ||
* gets all orders by user id and sorted it by creation data | ||
* @param Order[] - An array of Order objects. | ||
* @returns Promise<Order[]> - An array of Order objects. | ||
*/ | ||
function sortOrdersByCreated(orders: Order[]): Order[] { | ||
return orders.sort( | ||
(a, b) => | ||
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(), | ||
); | ||
} | ||
|
||
export async function toggleOrderProgress( | ||
orderId: string, | ||
): Promise<PostgrestSingleResponse<Order>> { | ||
try { | ||
// Fetch the order by ID to get its current "approved" value | ||
const { data: currentOrder, error: fetchError } = await supabase | ||
.from('order') | ||
.select('approved') | ||
.eq('id', orderId) | ||
.single(); | ||
|
||
if (fetchError) { | ||
console.error('Error fetching order:', fetchError); | ||
throw fetchError; | ||
} | ||
|
||
// Toggle the "approved" value | ||
const updatedApprovedValue = !currentOrder?.approved; | ||
|
||
// Update the order with the new "approved" value | ||
const { data: updatedOrder, error: updateError } = await supabase | ||
.from('order') | ||
.update({ approved: updatedApprovedValue }) | ||
.eq('id', orderId) | ||
.single(); | ||
|
||
if (updateError) { | ||
console.error('Error updating order:', updateError); | ||
throw updateError; | ||
} | ||
|
||
return updatedOrder; | ||
} catch (error) { | ||
console.error('Error:', error); | ||
throw error; | ||
/** | ||
* gets all orders by user id and sorted it by creation data | ||
* @param Order[] - An array of Order objects. | ||
* @returns Promise<Order[]> - An array of Order objects. | ||
*/ | ||
export async function fetchOrdersByUser(): Promise<Order[]> { | ||
const user = await fetchUser(); | ||
const userId = user.id; | ||
const { data, error } = await supabase | ||
.from('order') | ||
.select('*') | ||
.eq('user_id', userId); | ||
|
||
if (error) { | ||
throw new Error(`Error fetching orders for user: ${error.message}`); | ||
} | ||
} | ||
|
||
export async function updateAllOrdersProgressToTrue(): Promise< | ||
boolean | string | ||
> { | ||
try { | ||
// Update all orders to set "approved" to true | ||
const { error: updateError } = await supabase | ||
.from('order') | ||
.update({ approved: true }); | ||
return data; | ||
} | ||
|
||
if (updateError) { | ||
console.error('Error updating orders:', updateError); | ||
return 'Update failed'; // Return an error message if the update fails | ||
} | ||
/** | ||
* gets all orders by user id and sorted it by creation data | ||
* @param Order[] - An array of Order objects. | ||
* @returns Promise<Order[]> - An array of Order objects. | ||
*/ | ||
export async function fetchOrdersByUserIdSorted(): Promise<Order[]> { | ||
const orders = await fetchOrdersByUser(); | ||
return sortOrdersByCreated(orders); | ||
} | ||
|
||
return true; // Return true if the update succeeds | ||
} catch (error) { | ||
console.error('Error:', error); | ||
return 'Update failed'; // Return an error message if an exception occurs | ||
} | ||
/** | ||
* gets all orders by user id and sorted it by creation data and get the first n orders | ||
* @param Order[] - An array of Order objects. | ||
* @returns Promise<Order[]> - An array of Order objects. | ||
*/ | ||
export async function fetchNOrdersByUserIdSorted(n: number): Promise<Order[]> { | ||
const orders = await fetchOrdersByUser(); | ||
return sortOrdersByCreated(orders).slice(0, n); | ||
} |
Oops, something went wrong.