1 Commits

Author SHA1 Message Date
Unchained
8b3389725e feat(saleor): Phase 3 - Cart Migration
- Create Saleor checkout store (Zustand + persist)
- Update CartDrawer to use Saleor checkout
- Update Header to use Saleor checkout store
- Update ProductDetail with Add to Cart functionality
- Add checkout initialization on app load
- Handle checkout line add/update/delete operations
- Add error handling and loading states
2026-03-21 12:42:41 +02:00
4 changed files with 482 additions and 96 deletions

View File

@@ -1,20 +1,42 @@
"use client";
import { useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import Link from "next/link";
import { useCartStore } from "@/stores/cartStore";
import { formatPrice } from "@/lib/woocommerce";
import { useSaleorCheckoutStore } from "@/stores/saleorCheckoutStore";
import { formatPrice } from "@/lib/saleor";
export default function CartDrawer() {
const { items, isOpen, closeCart, removeItem, updateQuantity, getTotal } = useCartStore();
const {
checkout,
isOpen,
isLoading,
error,
closeCart,
removeLine,
updateLine,
getTotal,
getLineCount,
getLines,
initCheckout,
clearError,
} = useSaleorCheckoutStore();
const lines = getLines();
const total = getTotal();
const lineCount = getLineCount();
// Initialize checkout on mount
useEffect(() => {
initCheckout();
}, [initCheckout]);
return (
<AnimatePresence>
{isOpen && (
<>
{/* Backdrop */}
<motion.div
className="fixed inset-0 bg-black/50 z-50"
initial={{ opacity: 0 }}
@@ -22,6 +44,8 @@ export default function CartDrawer() {
exit={{ opacity: 0 }}
onClick={closeCart}
/>
{/* Drawer */}
<motion.div
className="fixed top-0 right-0 bottom-0 w-full max-w-md bg-white z-50 shadow-xl flex flex-col"
initial={{ x: "100%" }}
@@ -29,8 +53,11 @@ export default function CartDrawer() {
exit={{ x: "100%" }}
transition={{ type: "tween", duration: 0.3 }}
>
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-border/30">
<h2 className="text-xl font-serif">Your Cart</h2>
<h2 className="text-xl font-serif">
Your Cart ({lineCount})
</h2>
<button
onClick={closeCart}
className="p-2"
@@ -42,12 +69,26 @@ export default function CartDrawer() {
</button>
</div>
{/* Error Message */}
{error && (
<div className="p-4 bg-red-50 border-b border-red-100">
<p className="text-red-600 text-sm">{error}</p>
<button
onClick={clearError}
className="text-red-600 text-xs underline mt-1"
>
Dismiss
</button>
</div>
)}
{/* Cart Items */}
<div className="flex-1 overflow-y-auto p-6">
{items.length === 0 ? (
{lines.length === 0 ? (
<div className="text-center py-12">
<p className="text-foreground-muted mb-6">Your cart is empty</p>
<Link
href="/en/products"
href="/products"
onClick={closeCart}
className="inline-block px-6 py-3 bg-foreground text-white"
>
@@ -56,39 +97,53 @@ export default function CartDrawer() {
</div>
) : (
<div className="space-y-6">
{items.map((item) => (
<div key={item.id} className="flex gap-4">
{lines.map((line) => (
<div key={line.id} className="flex gap-4">
{/* Product Image */}
<div className="w-20 h-20 bg-background-ice relative flex-shrink-0">
{item.image && (
{line.variant.product.media[0]?.url && (
<Image
src={item.image}
alt={item.name}
src={line.variant.product.media[0].url}
alt={line.variant.product.name}
fill
className="object-cover"
/>
)}
</div>
{/* Product Info */}
<div className="flex-1">
<h3 className="font-serif text-sm">{item.name}</h3>
<h3 className="font-serif text-sm">{line.variant.product.name}</h3>
{line.variant.name !== "Default" && (
<p className="text-foreground-muted text-xs">{line.variant.name}</p>
)}
<p className="text-foreground-muted text-sm mt-1">
{formatPrice(item.price)}
{formatPrice(
line.variant.pricing?.price?.gross?.amount || 0,
line.variant.pricing?.price?.gross?.currency
)}
</p>
{/* Quantity Controls */}
<div className="flex items-center gap-3 mt-2">
<button
onClick={() => updateQuantity(item.id, item.quantity - 1)}
className="w-8 h-8 border border-border flex items-center justify-center"
onClick={() => updateLine(line.id, line.quantity - 1)}
disabled={isLoading}
className="w-8 h-8 border border-border flex items-center justify-center disabled:opacity-50"
>
-
</button>
<span>{item.quantity}</span>
<span>{line.quantity}</span>
<button
onClick={() => updateQuantity(item.id, item.quantity + 1)}
className="w-8 h-8 border border-border flex items-center justify-center"
onClick={() => updateLine(line.id, line.quantity + 1)}
disabled={isLoading}
className="w-8 h-8 border border-border flex items-center justify-center disabled:opacity-50"
>
+
</button>
<button
onClick={() => removeItem(item.id)}
onClick={() => removeLine(line.id)}
disabled={isLoading}
className="ml-auto text-foreground-muted hover:text-red-500"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -103,18 +158,48 @@ export default function CartDrawer() {
)}
</div>
{items.length > 0 && (
{/* Footer with Checkout */}
{lines.length > 0 && (
<div className="p-6 border-t border-border/30">
<div className="flex items-center justify-between mb-4">
<span className="font-serif">Subtotal</span>
<span className="font-serif text-lg">{formatPrice(total.toString())}</span>
{/* Subtotal */}
<div className="flex items-center justify-between mb-2">
<span className="text-foreground-muted">Subtotal</span>
<span>{formatPrice(checkout?.subtotalPrice?.gross?.amount || 0)}</span>
</div>
<a
href="https://manoonoils.com/checkout"
className="block w-full py-3 bg-foreground text-white text-center font-medium hover:bg-accent-dark transition-colors"
{/* Shipping */}
<div className="flex items-center justify-between mb-4">
<span className="text-foreground-muted">Shipping</span>
<span>
{checkout?.shippingPrice?.gross?.amount
? formatPrice(checkout.shippingPrice.gross.amount)
: "Calculated at checkout"
}
</span>
</div>
{/* Total */}
<div className="flex items-center justify-between mb-4 pt-4 border-t border-border/30">
<span className="font-serif">Total</span>
<span className="font-serif text-lg">{formatPrice(total)}</span>
</div>
{/* Checkout Button */}
<Link
href="/checkout"
onClick={closeCart}
className="block w-full py-3 bg-foreground text-white text-center font-medium hover:bg-accent-dark transition-colors disabled:opacity-50"
>
Checkout
</a>
{isLoading ? "Processing..." : "Checkout"}
</Link>
{/* Continue Shopping */}
<button
onClick={closeCart}
className="block w-full py-3 text-center text-foreground-muted hover:text-foreground mt-2"
>
Continue Shopping
</button>
</div>
)}
</motion.div>

View File

@@ -1,19 +1,24 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { AnimatePresence } from "framer-motion";
import { useCartStore } from "@/stores/cartStore";
import { useSaleorCheckoutStore } from "@/stores/saleorCheckoutStore";
import { User, ShoppingBag, Menu } from "lucide-react";
import MobileMenu from "./MobileMenu";
import CartDrawer from "@/components/cart/CartDrawer";
export default function Header() {
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const { items, toggleCart } = useCartStore();
const { getLineCount, toggleCart, initCheckout } = useSaleorCheckoutStore();
const itemCount = items.reduce((count, item) => count + item.quantity, 0);
const itemCount = getLineCount();
// Initialize checkout on mount
useEffect(() => {
initCheckout();
}, [initCheckout]);
return (
<>

View File

@@ -3,45 +3,55 @@
import { useState } from "react";
import Image from "next/image";
import { motion } from "framer-motion";
import { WooProduct, formatPrice, getProductImage } from "@/lib/woocommerce";
import { useCartStore } from "@/stores/cartStore";
import type { Product } from "@/types/saleor";
import { useSaleorCheckoutStore } from "@/stores/saleorCheckoutStore";
import { getProductPrice, getProductImage, getLocalizedProduct } from "@/lib/saleor";
import ProductCard from "@/components/product/ProductCard";
interface ProductDetailProps {
product: WooProduct;
relatedProducts: WooProduct[];
product: Product;
relatedProducts: Product[];
locale?: string;
}
export default function ProductDetail({ product, relatedProducts }: ProductDetailProps) {
export default function ProductDetail({ product, relatedProducts, locale = "SR" }: ProductDetailProps) {
const [selectedImage, setSelectedImage] = useState(0);
const [quantity, setQuantity] = useState(1);
const [activeTab, setActiveTab] = useState<"details" | "ingredients" | "usage">("details");
const addItem = useCartStore((state) => state.addItem);
const [isAdding, setIsAdding] = useState(false);
const { addLine, openCart } = useSaleorCheckoutStore();
const images = product.images?.length > 0
? product.images
: [{ id: 0, src: "/placeholder-product.jpg", alt: product.name }];
const localized = getLocalizedProduct(product, locale);
const variant = product.variants?.[0];
const images = product.media?.length > 0
? product.media
: [{ id: "0", url: "/placeholder-product.jpg", alt: localized.name, type: "IMAGE" }];
const handleAddToCart = () => {
addItem({
id: product.id,
name: product.name,
price: product.price || product.regular_price,
quantity,
image: images[0]?.src || "",
sku: product.sku || "",
});
const handleAddToCart = async () => {
if (!variant?.id) return;
setIsAdding(true);
try {
await addLine(variant.id, quantity);
openCart();
} finally {
setIsAdding(false);
}
};
const stripHtml = (html: string) => {
if (!html) return "";
return html.replace(/<[^>]*>/g, "");
};
const isAvailable = variant?.quantityAvailable > 0;
const price = getProductPrice(product);
return (
<>
<section className="py-12 md:py-20 px-4">
<div className="max-w-7xl mx-auto">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
{/* Product Images */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
@@ -50,8 +60,8 @@ export default function ProductDetail({ product, relatedProducts }: ProductDetai
<div className="relative aspect-square bg-background-ice mb-4">
{images[selectedImage] && (
<Image
src={images[selectedImage].src}
alt={images[selectedImage].alt || product.name}
src={images[selectedImage].url}
alt={images[selectedImage].alt || localized.name}
fill
className="object-cover"
priority
@@ -70,8 +80,8 @@ export default function ProductDetail({ product, relatedProducts }: ProductDetai
}`}
>
<Image
src={image.src}
alt={image.alt || product.name}
src={image.url}
alt={image.alt || localized.name}
fill
className="object-cover"
/>
@@ -81,97 +91,102 @@ export default function ProductDetail({ product, relatedProducts }: ProductDetai
)}
</motion.div>
{/* Product Info */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.6, delay: 0.2 }}
>
<h1 className="text-3xl md:text-4xl font-serif mb-4">
{product.name}
{localized.name}
</h1>
<p className="text-2xl text-foreground-muted mb-6">
{product.price ? formatPrice(product.price) : "Contact for price"}
{price || (locale === "EN" ? "Contact for price" : "Kontaktirajte za cenu")}
</p>
{/* Short Description */}
<div className="prose prose-sm max-w-none mb-8 text-foreground-muted">
<p>{stripHtml(product.short_description || product.description.slice(0, 200))}</p>
<p>{stripHtml(localized.description).slice(0, 200)}...</p>
</div>
{product.stock_status === "instock" ? (
{/* Add to Cart */}
{isAvailable ? (
<div className="flex items-center gap-4 mb-8">
{/* Quantity Selector */}
<div className="flex items-center border border-border">
<button
onClick={() => setQuantity(Math.max(1, quantity - 1))}
className="px-4 py-3"
className="px-4 py-3 hover:bg-gray-50"
>
-
</button>
<span className="px-4 py-3">{quantity}</span>
<span className="px-4 py-3 min-w-[3rem] text-center">{quantity}</span>
<button
onClick={() => setQuantity(quantity + 1)}
className="px-4 py-3"
className="px-4 py-3 hover:bg-gray-50"
>
+
</button>
</div>
{/* Add to Cart Button */}
<button
onClick={handleAddToCart}
className="flex-1 py-3 bg-foreground text-white hover:bg-accent-dark transition-colors"
disabled={isAdding}
className="flex-1 py-3 bg-foreground text-white hover:bg-accent-dark transition-colors disabled:opacity-50"
>
Add to Cart
{isAdding
? (locale === "EN" ? "Adding..." : "Dodavanje...")
: (locale === "EN" ? "Add to Cart" : "Dodaj u korpu")
}
</button>
</div>
) : (
<div className="py-3 bg-red-50 text-red-600 text-center mb-8">
Out of Stock
{locale === "EN" ? "Out of Stock" : "Nema na stanju"}
</div>
)}
<div className="border-t border-border/30">
<div className="flex border-b border-border/30">
{(["details", "ingredients", "usage"] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`flex-1 py-4 font-medium capitalize ${
activeTab === tab
? "border-b-2 border-foreground"
: "text-foreground-muted"
}`}
>
{tab}
</button>
))}
{/* SKU */}
{variant?.sku && (
<p className="text-sm text-foreground-muted mb-4">
SKU: {variant.sku}
</p>
)}
{/* Full Description */}
{localized.description && (
<div className="border-t border-border/30 pt-6">
<h3 className="font-serif text-lg mb-4">
{locale === "EN" ? "Description" : "Opis"}
</h3>
<div
className="prose max-w-none text-foreground-muted"
dangerouslySetInnerHTML={{ __html: localized.description }}
/>
</div>
<div className="py-6 text-foreground-muted">
{activeTab === "details" && (
<p>{stripHtml(product.description)}</p>
)}
{activeTab === "ingredients" && (
<p>Natural ingredients - Contact for detailed information.</p>
)}
{activeTab === "usage" && (
<p>Apply to clean skin or hair. Use daily for best results.</p>
)}
</div>
</div>
)}
</motion.div>
</div>
</div>
</section>
{/* Related Products */}
{relatedProducts.length > 0 && (
<section className="py-12 px-4 bg-background-ice">
<div className="max-w-7xl mx-auto">
<h2 className="text-2xl font-serif text-center mb-8">
You May Also Like
{locale === "EN" ? "You May Also Like" : "Možda će vam se svideti"}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
{relatedProducts.map((product, index) => (
<ProductCard key={product.id} product={product} index={index} />
{relatedProducts.map((relatedProduct, index) => (
<ProductCard
key={relatedProduct.id}
product={relatedProduct}
index={index}
locale={locale}
/>
))}
</div>
</div>

View File

@@ -0,0 +1,281 @@
"use client";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { saleorClient } from "@/lib/saleor/client";
import {
CHECKOUT_CREATE,
CHECKOUT_LINES_ADD,
CHECKOUT_LINES_UPDATE,
CHECKOUT_LINES_DELETE,
CHECKOUT_EMAIL_UPDATE,
} from "@/lib/saleor/mutations/Checkout";
import { GET_CHECKOUT } from "@/lib/saleor/queries/Checkout";
import type { Checkout, CheckoutLine } from "@/types/saleor";
const CHANNEL = process.env.NEXT_PUBLIC_SALEOR_CHANNEL || "default-channel";
interface SaleorCheckoutStore {
checkout: Checkout | null;
checkoutToken: string | null;
isOpen: boolean;
isLoading: boolean;
error: string | null;
// Actions
initCheckout: () => Promise<void>;
addLine: (variantId: string, quantity: number) => Promise<void>;
updateLine: (lineId: string, quantity: number) => Promise<void>;
removeLine: (lineId: string) => Promise<void>;
setEmail: (email: string) => Promise<void>;
refreshCheckout: () => Promise<void>;
toggleCart: () => void;
openCart: () => void;
closeCart: () => void;
clearError: () => void;
// Getters
getLineCount: () => number;
getTotal: () => number;
getLines: () => CheckoutLine[];
}
export const useSaleorCheckoutStore = create<SaleorCheckoutStore>()(
persist(
(set, get) => ({
checkout: null,
checkoutToken: null,
isOpen: false,
isLoading: false,
error: null,
initCheckout: async () => {
const { checkoutToken } = get();
if (checkoutToken) {
// Try to fetch existing checkout
try {
const { data } = await saleorClient.query({
query: GET_CHECKOUT,
variables: { token: checkoutToken },
});
if (data?.checkout) {
set({ checkout: data.checkout });
return;
}
} catch (e) {
// Checkout not found or expired, create new one
}
}
// Create new checkout
try {
const { data } = await saleorClient.mutate({
mutation: CHECKOUT_CREATE,
variables: {
input: {
channel: CHANNEL,
lines: [],
},
},
});
if (data?.checkoutCreate?.checkout) {
set({
checkout: data.checkoutCreate.checkout,
checkoutToken: data.checkoutCreate.checkout.token,
});
}
} catch (e: any) {
set({ error: e.message });
}
},
addLine: async (variantId: string, quantity: number) => {
set({ isLoading: true, error: null });
try {
let { checkout, checkoutToken } = get();
// Initialize checkout if needed
if (!checkout) {
await get().initCheckout();
checkout = get().checkout;
checkoutToken = get().checkoutToken;
}
if (!checkout) {
throw new Error("Failed to initialize checkout");
}
const { data } = await saleorClient.mutate({
mutation: CHECKOUT_LINES_ADD,
variables: {
checkoutId: checkout.id,
lines: [{ variantId, quantity }],
},
});
if (data?.checkoutLinesAdd?.checkout) {
set({
checkout: data.checkoutLinesAdd.checkout,
isOpen: true,
isLoading: false,
});
} else if (data?.checkoutLinesAdd?.errors?.length > 0) {
throw new Error(data.checkoutLinesAdd.errors[0].message);
}
} catch (e: any) {
set({ error: e.message, isLoading: false });
}
},
updateLine: async (lineId: string, quantity: number) => {
set({ isLoading: true, error: null });
try {
const { checkout } = get();
if (!checkout) {
throw new Error("No active checkout");
}
if (quantity <= 0) {
// Remove line if quantity is 0 or less
await get().removeLine(lineId);
return;
}
const { data } = await saleorClient.mutate({
mutation: CHECKOUT_LINES_UPDATE,
variables: {
checkoutId: checkout.id,
lines: [{ lineId, quantity }],
},
});
if (data?.checkoutLinesUpdate?.checkout) {
set({
checkout: data.checkoutLinesUpdate.checkout,
isLoading: false,
});
} else if (data?.checkoutLinesUpdate?.errors?.length > 0) {
throw new Error(data.checkoutLinesUpdate.errors[0].message);
}
} catch (e: any) {
set({ error: e.message, isLoading: false });
}
},
removeLine: async (lineId: string) => {
set({ isLoading: true, error: null });
try {
const { checkout } = get();
if (!checkout) {
throw new Error("No active checkout");
}
const { data } = await saleorClient.mutate({
mutation: CHECKOUT_LINES_DELETE,
variables: {
checkoutId: checkout.id,
lineIds: [lineId],
},
});
if (data?.checkoutLinesDelete?.checkout) {
set({
checkout: data.checkoutLinesDelete.checkout,
isLoading: false,
});
} else if (data?.checkoutLinesDelete?.errors?.length > 0) {
throw new Error(data.checkoutLinesDelete.errors[0].message);
}
} catch (e: any) {
set({ error: e.message, isLoading: false });
}
},
setEmail: async (email: string) => {
set({ isLoading: true, error: null });
try {
const { checkout } = get();
if (!checkout) {
throw new Error("No active checkout");
}
const { data } = await saleorClient.mutate({
mutation: CHECKOUT_EMAIL_UPDATE,
variables: {
checkoutId: checkout.id,
email,
},
});
if (data?.checkoutEmailUpdate?.checkout) {
set({
checkout: data.checkoutEmailUpdate.checkout,
isLoading: false,
});
} else if (data?.checkoutEmailUpdate?.errors?.length > 0) {
throw new Error(data.checkoutEmailUpdate.errors[0].message);
}
} catch (e: any) {
set({ error: e.message, isLoading: false });
}
},
refreshCheckout: async () => {
const { checkoutToken } = get();
if (!checkoutToken) return;
try {
const { data } = await saleorClient.query({
query: GET_CHECKOUT,
variables: { token: checkoutToken },
});
if (data?.checkout) {
set({ checkout: data.checkout });
}
} catch (e) {
// Checkout might be expired
set({ checkout: null, checkoutToken: null });
}
},
toggleCart: () => set((state) => ({ isOpen: !state.isOpen })),
openCart: () => set({ isOpen: true }),
closeCart: () => set({ isOpen: false }),
clearError: () => set({ error: null }),
getLineCount: () => {
const { checkout } = get();
if (!checkout?.lines) return 0;
return checkout.lines.reduce((count, line) => count + line.quantity, 0);
},
getTotal: () => {
const { checkout } = get();
return checkout?.totalPrice?.gross?.amount || 0;
},
getLines: () => {
const { checkout } = get();
return checkout?.lines || [];
},
}),
{
name: "manoonoils-saleor-checkout",
partialize: (state) => ({
checkoutToken: state.checkoutToken,
}),
}
)
);