Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions prisma/initial_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ export const productVariant = [
{ productTitle: "Polo It Works On My Machine", sizes: ["small", "medium", "large"] },
];

export const stickersVariant = [
{ productTitle: "Sticker JavaScript", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker React", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker Git", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker Docker", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker Linux", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker VS Code", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker GitHub", measure: ["3*3", "5*5", "10*10"] },
{ productTitle: "Sticker HTML", measure: ["3*3", "5*5", "10*10"] },
];

export const products = [
{
title: "Polo React",
Expand Down
29 changes: 29 additions & 0 deletions prisma/migrations/20250822231633_stickers/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Warnings:

- A unique constraint covering the columns `[cartId,productId,productVariantId,stickersVariantId]` on the table `cart_items` will be added. If there are existing duplicate values, this will fail.

*/
-- DropIndex
DROP INDEX "cart_items_cartId_productId_productVariantId_key";

-- AlterTable
ALTER TABLE "cart_items" ADD COLUMN "stickersVariantId" INTEGER;

-- CreateTable
CREATE TABLE "stickersVariant" (
"id" SERIAL NOT NULL,
"productId" INTEGER NOT NULL,
"measure" TEXT NOT NULL,

CONSTRAINT "stickersVariant_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "cart_items_cartId_productId_productVariantId_stickersVarian_key" ON "cart_items"("cartId", "productId", "productVariantId", "stickersVariantId");

-- AddForeignKey
ALTER TABLE "stickersVariant" ADD CONSTRAINT "stickersVariant_productId_fkey" FOREIGN KEY ("productId") REFERENCES "products"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "cart_items" ADD CONSTRAINT "cart_items_stickersVariantId_fkey" FOREIGN KEY ("stickersVariantId") REFERENCES "stickersVariant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
12 changes: 12 additions & 0 deletions prisma/migrations/20250825232113_add_price/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Warnings:

- Added the required column `price` to the `cart_items` table without a default value. This is not possible if the table is not empty.
- Added the required column `price` to the `stickersVariant` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "cart_items" ADD COLUMN "price" DECIMAL(10,2) NOT NULL;

-- AlterTable
ALTER TABLE "stickersVariant" ADD COLUMN "price" DECIMAL(10,2) NOT NULL;
16 changes: 15 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ model Product {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamp(0)
updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamp(0)
variants ProductVariant[]
stickersVariants stickersVariant[]

category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
cartItems CartItem[]
Expand All @@ -80,6 +81,16 @@ model ProductVariant {
cartItems CartItem[] @relation("CartItemToProductVariant")
}

model stickersVariant {
id Int @id @default(autoincrement())
product Product @relation(fields: [productId], references: [id])
productId Int
measure String // '3*3', '5*5', '10*10'
price Decimal @db.Decimal(10, 2)

cartItems CartItem[] @relation("CartItemTostickersVariant")
}

model Cart {
id Int @id @default(autoincrement())
sessionCartId String @unique @default(dbgenerated("gen_random_uuid()")) @map("session_cart_id") @db.Uuid
Expand All @@ -98,15 +109,18 @@ model CartItem {
cartId Int
productId Int
productVariantId Int?
stickersVariantId Int?
price Decimal @db.Decimal(10, 2)
quantity Int
createdAt DateTime @default(now()) @map("created_at") @db.Timestamp(0)
updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamp(0)

cart Cart @relation(fields: [cartId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
productVariant ProductVariant? @relation("CartItemToProductVariant", fields: [productVariantId], references: [id])
stickersVariant stickersVariant? @relation("CartItemTostickersVariant", fields: [stickersVariantId], references: [id])

@@unique([cartId, productId, productVariantId], name: "unique_cart_item")
@@unique([cartId, productId, productVariantId, stickersVariantId], name: "unique_cart_item")
@@map("cart_items")
}

Expand Down
32 changes: 32 additions & 0 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ const prisma = new PrismaClient();

// Define las tallas para los productos tipo "Polo"
const poloSizes = ["small", "medium", "large"] as const;
// Define el tamaño para los productos tipo "Stickers"
const stickerMeasures = ["3*3", "5*5", "10*10"] as const;

async function seedDb() {
// Limpia las tablas para evitar duplicados
await prisma.productVariant.deleteMany();
await prisma.stickersVariant.deleteMany();
await prisma.product.deleteMany();
await prisma.category.deleteMany();

Expand Down Expand Up @@ -46,6 +49,35 @@ async function seedDb() {
}
console.log("3. Polo variants successfully inserted");
}

// Obtiene los productos tipo "Stickers" para agregar variantes
const stickersCategory = await prisma.category.findUnique({
where: { slug: "stickers" },
});
if (stickersCategory) {
const stickers = await prisma.product.findMany({
where: { categoryId: stickersCategory.id },
});

const stickerPrices: Record<typeof stickerMeasures[number], number> = {
"3*3": 2.99,
"5*5": 5.99,
"10*10": 8.99,
};

for (const sticker of stickers) {
for (const measure of stickerMeasures) {
await prisma.stickersVariant.create({
data: {
productId: sticker.id,
measure,
price: stickerPrices[measure], // Asigna el precio según la medida
},
});
}
}
console.log("4. Stickers variants successfully inserted");
}
}

seedDb()
Expand Down
46 changes: 46 additions & 0 deletions src/components/product/VariantSelector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
type VariantOption = {
id: number | string;
label: string;
value: string;
};

type VariantSelectorProps = {
label: string;
name: string;
options: VariantOption[];
selectedValue: string;
onSelect: (value: string) => void;
};

export function VariantSelector({
label,
name,
options,
selectedValue,
onSelect,
}: VariantSelectorProps) {
return (
<div className="mb-4">
<label className="block mb-2 font-medium">{label}</label>
<div className="flex flex-wrap gap-2">
{options.map(option => (
<button
type="button"
key={option.id}
className={`px-4 py-2 rounded border transition-colors ${
selectedValue === option.value
? "bg-primary text-primary-foreground border-primary"
: "bg-background text-foreground border-border hover:bg-accent"
}`}
onClick={() => onSelect(option.value)}
>
{option.label}
</button>
))}
</div>
{/* input oculto para enviar la opción seleccionada */}
<input type="hidden" name={name} value={selectedValue} />
</div>
);
}

6 changes: 4 additions & 2 deletions src/lib/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ export async function addToCart(
sessionCartId: string | undefined,
productId: Product["id"],
quantity: number = 1,
productVariantId?: number
productVariantId?: number,
stickersVariantId?: number
) {
try {
const updatedCart = await alterQuantityCartItem(
userId,
sessionCartId,
productId,
quantity,
productVariantId
productVariantId,
stickersVariantId
);
return updatedCart;
} catch (error) {
Expand Down
6 changes: 6 additions & 0 deletions src/models/cart.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export type CartItem = PrismaCartItem & {
id: number;
size: "small" | "medium" | "large";
} | null;
stickersVariant?: {
id: number;
measure: "3*3" | "5*5" | "10*10";
} | null;
};

export type Cart = PrismaCart;
Expand All @@ -35,6 +39,8 @@ export type CartItemWithProduct = {
product: CartProductInfo;
quantity: number;
productVariantId: number | null;
stickersVariantId: number | null;
price: number;
};

// Tipo para el carrito con items y productos incluidos
Expand Down
7 changes: 7 additions & 0 deletions src/models/product.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import type { Product as PrismaProduct } from "@/../generated/prisma/client";
export type Product = Omit<PrismaProduct, "price"> & {
price: number;
variants?: ProductVariant[];
stickersVariants?: StickersVariant[];
};

export type StickersVariant = {
id: number;
measure: "3*3" | "5*5" | "10*10";
price: number;
};
export interface ProductVariant {
id: number;
Expand Down
21 changes: 20 additions & 1 deletion src/routes/cart/add-item/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { redirect } from "react-router";

Check failure on line 1 in src/routes/cart/add-item/index.tsx

View workflow job for this annotation

GitHub Actions / lint

There should be at least one empty line between import groups
import { prisma } from "@/db/prisma";
import { addToCart } from "@/lib/cart";
import { getSession } from "@/session.server";
Expand All @@ -10,12 +10,14 @@
const productId = Number(formData.get("productId"));
const quantity = Number(formData.get("quantity")) || 1;
const size = formData.get("size") as string | undefined;
const measure = formData.get("measure") as string | undefined;
const redirectTo = formData.get("redirectTo") as string | null;
const session = await getSession(request.headers.get("Cookie"));
const sessionCartId = session.get("sessionCartId");
const userId = session.get("userId");

let productVariantId: number | undefined = undefined;
let stickersVariantId: number | undefined = undefined;

// Si hay talla, busca el variant correspondiente
if (size) {
Expand All @@ -34,7 +36,24 @@
productVariantId = variant.id;
}

await addToCart(userId, sessionCartId, productId, quantity, productVariantId);
// Si hay medida, busca el variant correspondiente
if (measure) {
const variantMeasure = await prisma.stickersVariant.findFirst({
where: {
productId,
measure,
},
});
if (!variantMeasure) {
return new Response(
JSON.stringify({ error: "No se encontró la variante de stickers seleccionada." }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
stickersVariantId = variantMeasure.id;
}

await addToCart(userId, sessionCartId, productId, quantity, productVariantId, stickersVariantId);

return redirect(redirectTo || "/cart");
}
25 changes: 23 additions & 2 deletions src/routes/cart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import { type Cart } from "@/models/cart.model";
import { getSession } from "@/session.server";

import type { Route } from "./+types";

Check failure on line 9 in src/routes/cart/index.tsx

View workflow job for this annotation

GitHub Actions / lint

There should be at least one empty line between import groups
import { productVariant } from "prisma/initial_data";

Check failure on line 10 in src/routes/cart/index.tsx

View workflow job for this annotation

GitHub Actions / lint

'productVariant' is defined but never used. Allowed unused vars must match /^_/u

Check failure on line 10 in src/routes/cart/index.tsx

View workflow job for this annotation

GitHub Actions / lint

`prisma/initial_data` import should occur before import of `react-router`

export async function loader({ request }: Route.LoaderArgs) {
const session = await getSession(request.headers.get("Cookie"));
Expand All @@ -31,7 +31,8 @@
Carrito de compras
</h1>
<div className="border-solid border rounded-xl flex flex-col">
{cart?.items?.map(({ product, quantity, id, productVariant }) => (
{cart?.items?.map(
({ product, quantity, id, productVariant, stickersVariant }) => (
<div key={id} className="flex gap-7 p-6 border-b">
<div className="w-20 rounded-xl bg-muted">
<img
Expand All @@ -49,6 +50,11 @@
({productVariant.size})
</span>
)}
{stickersVariant && (
<span className="ml-2 text-xs text-muted-foreground">
({stickersVariant.measure})
</span>
)}
</h2>
<Form method="post" action="/cart/remove-item">
<Button
Expand All @@ -71,6 +77,13 @@
{productVariant && (
<input type="hidden" name="size" value={productVariant.size} />
)}
{stickersVariant && (
<input
type="hidden"
name="measure"
value={stickersVariant.measure}
/>
)}
<input type="hidden" name="productId" value={product.id} />
<Button
name="productId"
Expand All @@ -89,6 +102,13 @@
{productVariant && (
<input type="hidden" name="size" value={productVariant.size} />
)}
{stickersVariant && (
<input
type="hidden"
name="measure"
value={stickersVariant.measure}
/>
)}
<input type="hidden" name="productId" value={product.id} />
<Button
variant="outline"
Expand All @@ -103,7 +123,8 @@
</div>
</div>
</div>
))}
)
)}
<div className="flex justify-between p-6 text-base font-medium border-b">
<p>Total</p>
<p>S/{total.toFixed(2)}</p>
Expand Down
15 changes: 11 additions & 4 deletions src/routes/checkout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ export default function Checkout({
<div className="flex-grow">
<h2 className="text-lg font-medium mb-4">Resumen de la orden</h2>
<div className="border border-border rounded-xl bg-background flex flex-col">
{cart?.items?.map(({ product, quantity, id, productVariant }) => (
{cart?.items?.map(
({ product, quantity, id, productVariant, stickersVariant }) => (
<div
key={id}
className="flex gap-6 p-6 border-b border-border"
Expand All @@ -269,16 +270,22 @@ export default function Checkout({
<span className="ml-2 text-xs text-muted-foreground">
({productVariant.size})
</span>
)}
</h2>
)}
{stickersVariant && (
<span className="ml-2 text-xs text-muted-foreground">
({stickersVariant.measure})
</span>
)}
</h2>
<div className="flex text-sm font-medium gap-4 items-center self-end">
<p>{quantity}</p>
<X className="w-4 h-4" />
<p>S/{product.price.toFixed(2)}</p>
</div>
</div>
</div>
))}
)
)}
<div className="flex justify-between p-6 text-base font-medium">
<p>Total</p>
<p>S/{total.toFixed(2)}</p>
Expand Down
Loading
Loading