Skip to content
Merged
60 changes: 35 additions & 25 deletions src/lib/cart.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,31 @@
import type { CartItem } from "@/models/cart.model";
import type { CartItem, CartItemInput } from "@/models/cart.model";
import { type Product } from "@/models/product.model";
import {
alterQuantityCartItem,
deleteRemoteCartItem,
getRemoteCart,
getOrCreateCart,
} from "@/services/cart.service";
import { getProductById } from "@/services/product.service";

export async function getCart(request: Request) {
export async function getCart(userId?: number, sessionCartId?: string) {
try {
const remoteCart = await getRemoteCart(request);

// Si ya existe un carrito (con ítems o vacío), lo devolvemos
if (remoteCart) {
// Si no existe la propiedad total, calcúlala sumando las cantidades de cada ítem
if (remoteCart.total === undefined) {
remoteCart.total =
remoteCart.items?.reduce((total, item) => total + item.quantity, 0) ||
0;
}
return remoteCart;
}

// No se encontró carrito
return null;
return getOrCreateCart(userId, sessionCartId);
} catch (error) {
console.error(error);
return null;
}
}

export async function addToCart(
request: Request,
userId: number | undefined,
sessionCartId: string | undefined,
productId: Product["id"],
quantity: number = 1
) {
try {
const product = await getProductById(request, productId);
const updatedCart = await alterQuantityCartItem(
request,
product.id,
userId,
sessionCartId,
productId,
quantity
);
return updatedCart;
Expand All @@ -49,13 +35,37 @@ export async function addToCart(
}
}

export async function removeFromCart(request: Request, itemId: CartItem["id"]) {
export async function removeFromCart(
userId: number | undefined,
sessionCartId: string | undefined,
itemId: CartItem["id"]
) {
try {
// El backend determinará si es un usuario autenticado o invitado
const updatedCart = await deleteRemoteCartItem(request, itemId);
const updatedCart = await deleteRemoteCartItem(
userId,
sessionCartId,
itemId
);
return updatedCart;
} catch (error) {
console.error(error);
return null;
}
}

export function calculateTotal(items: CartItem[]): number;
export function calculateTotal(items: CartItemInput[]): number;

export function calculateTotal(items: CartItem[] | CartItemInput[]): number {
return items.reduce((total, item) => {
// Type guard to determine which type we're working with
if ("product" in item) {
// CartItem - has a product property
return total + item.product.price * item.quantity;
} else {
// CartItemInput - has price directly
return total + item.price * item.quantity;
}
}, 0);
}
4 changes: 2 additions & 2 deletions src/lib/client.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ export async function serverClient<T>(
const cookieHeader = request.headers.get("Cookie");
const session = await getSession(cookieHeader);
const token = session.get("token");
const cartSessionId = session.get("cartSessionId");
const sessionCartId = session.get("sessionCartId");

const cartSessionHeader: { "x-cart-id": string } | Record<string, string> =
cartSessionId ? { "x-cart-id": cartSessionId } : {};
sessionCartId ? { "x-cart-id": sessionCartId } : {};

const config: RequestInit = {
method: body ? "POST" : "GET",
Expand Down
14 changes: 10 additions & 4 deletions src/models/cart.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,22 @@ import { type User } from "./user.model";

export interface CartItem {
id: number;
product: Product;
product: Pick<
Product,
"id" | "title" | "imgSrc" | "alt" | "price" | "isOnSale"
>;
quantity: number;
createdAt: string;
updatedAt: string;
}

export interface Cart {
id: number;
userId?: User["id"];
sessionCartId?: string;
userId: User["id"] | null;
sessionCartId: string;
items: CartItem[];
total: number;
createdAt: string;
updatedAt: string;
}

export interface CartItemInput {
Expand Down
17 changes: 16 additions & 1 deletion src/models/order.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export interface OrderItem {
title: string;
price: number;
imgSrc: string;
createdAt: string;
updatedAt: string;
}

export interface Order {
Expand All @@ -29,5 +31,18 @@ export interface Order {
items: OrderItem[];
totalAmount: number;
details: OrderDetails;
createdAt: Date;
createdAt: string;
updatedAt: string;
}

export interface OrderItemInput {
productId: number;
quantity: number;
title: string;
price: number;
imgSrc: string;
}

export interface OrderResponse {
id: number;
}
7 changes: 5 additions & 2 deletions src/models/product.model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type Category } from "./category.model";
// import { type Category } from "./category.model";

export interface Product {
id: number;
Expand All @@ -7,7 +7,10 @@ export interface Product {
alt: string | null;
price: number;
description: string | null;
categorySlug: Category["slug"];
categoryId: number;
// categorySlug: Category["slug"];
isOnSale: boolean;
features: string[];
createdAt: string;
updatedAt: string;
}
Loading