Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d05112ae65 | ||
|
|
bb2c0bbe85 | ||
|
|
cdab538cfb | ||
|
|
f124ae0bbd | ||
|
|
b8ce9ded87 | ||
|
|
b12dd848af | ||
|
|
d28ee4a49d |
No files matched your search
@@ -0,0 +1,14 @@
|
|||||||
|
import { setShippingAddress } from "@/lib/headless/providers/medusa-cart";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId, ...address } = await request.json();
|
||||||
|
if (!cartId || !address.firstName || !address.address1 || !address.city || !address.phone || !address.email) {
|
||||||
|
return Response.json({ error: "Faltan campos obligatorios de la dirección" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const cart = await setShippingAddress(cartId, address);
|
||||||
|
return Response.json(cart);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { addShippingMethod } from "@/lib/headless/providers/medusa-cart";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId, optionId } = await request.json();
|
||||||
|
if (!cartId || !optionId) {
|
||||||
|
return Response.json({ error: "cartId y optionId son obligatorios" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const cart = await addShippingMethod(cartId, optionId);
|
||||||
|
return Response.json(cart);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { getShippingOptions } from "@/lib/headless/providers/medusa-cart";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const cartId = new URL(request.url).searchParams.get("cartId");
|
||||||
|
if (!cartId) {
|
||||||
|
return Response.json({ error: "cartId es obligatorio" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const options = await getShippingOptions(cartId);
|
||||||
|
return Response.json({ options });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { CheckoutClient } from "@/components/checkout/checkout-client";
|
||||||
|
|
||||||
|
export default function CheckoutPage() {
|
||||||
|
return <CheckoutClient />;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
import { Minus, Plus, ShoppingBag, Trash2 } from "lucide-react";
|
import { Minus, Plus, ShoppingBag, Trash2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Progress } from "@/components/ui/progress";
|
import { Progress } from "@/components/ui/progress";
|
||||||
@@ -17,13 +18,6 @@ export function CartDrawer() {
|
|||||||
const progress = pricedItems ? Math.min(100, (subtotal / FREE_SHIPPING_THRESHOLD) * 100) : 0;
|
const progress = pricedItems ? Math.min(100, (subtotal / FREE_SHIPPING_THRESHOLD) * 100) : 0;
|
||||||
const count = items.reduce((sum, item) => sum + item.quantity, 0);
|
const count = items.reduce((sum, item) => sum + item.quantity, 0);
|
||||||
|
|
||||||
const checkout = () => {
|
|
||||||
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
|
||||||
const message = `Hola Ari Shopping 👋\nQuiero consultar disponibilidad para:\n\n${lines}\n\nNombre:\nCiudad:\nForma de entrega:`;
|
|
||||||
void navigator.clipboard?.writeText(message);
|
|
||||||
window.open(process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc", "_blank", "noopener,noreferrer");
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet open={isOpen} onOpenChange={(open) => { if (!open) closeCart(); }}>
|
<Sheet open={isOpen} onOpenChange={(open) => { if (!open) closeCart(); }}>
|
||||||
<SheetContent>
|
<SheetContent>
|
||||||
@@ -49,7 +43,15 @@ export function CartDrawer() {
|
|||||||
<div className="space-y-4 border-t border-slate-100 p-6">
|
<div className="space-y-4 border-t border-slate-100 p-6">
|
||||||
<div><div className="mb-2 flex justify-between text-xs font-bold text-slate-600"><span>{pricedItems ? "Progreso para envío gratis" : "Cotización personalizada"}</span><span>{pricedItems ? `${Math.round(progress)}%` : "Por confirmar"}</span></div><Progress value={progress} /></div>
|
<div><div className="mb-2 flex justify-between text-xs font-bold text-slate-600"><span>{pricedItems ? "Progreso para envío gratis" : "Cotización personalizada"}</span><span>{pricedItems ? `${Math.round(progress)}%` : "Por confirmar"}</span></div><Progress value={progress} /></div>
|
||||||
<div className="flex items-center justify-between"><span className="font-bold text-slate-600">Subtotal</span><strong className="text-xl font-black">{pricedItems ? formatMoney(subtotal) : "Por confirmar"}</strong></div>
|
<div className="flex items-center justify-between"><span className="font-bold text-slate-600">Subtotal</span><strong className="text-xl font-black">{pricedItems ? formatMoney(subtotal) : "Por confirmar"}</strong></div>
|
||||||
<Button variant="primary" size="lg" className="w-full" disabled={!items.length} onClick={checkout}>Continuar por WhatsApp</Button>
|
{/* Button asChild + disabled no funciona sobre un <a> (:disabled
|
||||||
|
es pseudo-clase de elementos de formulario, un Link nunca la
|
||||||
|
cumple) -- se ramifica en vez de confiar en el prop disabled
|
||||||
|
sobre un Link. */}
|
||||||
|
{items.length > 0 ? (
|
||||||
|
<Button asChild variant="primary" size="lg" className="w-full"><Link href="/checkout" onClick={closeCart}>Confirmar pedido</Link></Button>
|
||||||
|
) : (
|
||||||
|
<Button variant="primary" size="lg" className="w-full" disabled>Confirmar pedido</Button>
|
||||||
|
)}
|
||||||
<Button variant="ghost" className="w-full" disabled={!items.length} onClick={clearCart}>Vaciar carrito</Button>
|
<Button variant="ghost" className="w-full" disabled={!items.length} onClick={clearCart}>Vaciar carrito</Button>
|
||||||
</div>
|
</div>
|
||||||
</SheetContent>
|
</SheetContent>
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ArrowLeft, MapPin, MessageCircle, Truck } from "lucide-react";
|
||||||
|
import { type FormEvent, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { formatMoney } from "@/lib/utils";
|
||||||
|
import { useCartStore } from "@/store/cart-store";
|
||||||
|
|
||||||
|
// ADR 0009, siguiente corte tras el carrito real: direccion + seleccion de
|
||||||
|
// envio contra el Store API real (mismos endpoints ya verificados en vivo
|
||||||
|
// para las shipping options). El pago (PayU custom) todavia no existe --
|
||||||
|
// el ultimo paso sigue siendo WhatsApp, ahora con el pedido completo
|
||||||
|
// (direccion, envio, total real) en vez de solo la lista de productos.
|
||||||
|
|
||||||
|
interface ShippingOption {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Step = "address" | "shipping" | "review";
|
||||||
|
|
||||||
|
async function postJson(url: string, body: unknown) {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckoutClient() {
|
||||||
|
const { cartId, items, hasHydrated } = useCartStore();
|
||||||
|
const [step, setStep] = useState<Step>("address");
|
||||||
|
const [form, setForm] = useState({ firstName: "", lastName: "", address1: "", city: "", province: "", phone: "", email: "" });
|
||||||
|
const [shippingOptions, setShippingOptions] = useState<ShippingOption[]>([]);
|
||||||
|
const [selectedOptionId, setSelectedOptionId] = useState<string | null>(null);
|
||||||
|
const [shippingTotal, setShippingTotal] = useState(0);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const itemsSubtotal = items.reduce((sum, item) => sum + (item.product.price ?? 0) * item.quantity, 0);
|
||||||
|
const currency = items[0]?.product.currency;
|
||||||
|
|
||||||
|
async function submitAddress(event: FormEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!cartId) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const cart = await postJson("/api/cart/address", { cartId, ...form });
|
||||||
|
if (cart.error) throw new Error(cart.error);
|
||||||
|
const response = await fetch(`/api/cart/shipping-options?cartId=${cartId}`);
|
||||||
|
const data = await response.json();
|
||||||
|
const options: ShippingOption[] = data.options ?? [];
|
||||||
|
setShippingOptions(options);
|
||||||
|
setSelectedOptionId(options[0]?.id ?? null);
|
||||||
|
setStep("shipping");
|
||||||
|
} catch (submitError) {
|
||||||
|
setError((submitError as Error).message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitShipping() {
|
||||||
|
if (!cartId || !selectedOptionId) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const cart = await postJson("/api/cart/shipping-method", { cartId, optionId: selectedOptionId });
|
||||||
|
if (cart.error) throw new Error(cart.error);
|
||||||
|
setShippingTotal(cart.shippingTotal ?? 0);
|
||||||
|
setTotal(cart.total ?? itemsSubtotal);
|
||||||
|
setStep("review");
|
||||||
|
} catch (submitError) {
|
||||||
|
setError((submitError as Error).message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function continueOnWhatsApp() {
|
||||||
|
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
||||||
|
const message = `Hola Ari Shopping 👋\nQuiero confirmar mi pedido:\n\n${lines}\n\nSubtotal: ${formatMoney(itemsSubtotal, currency)}\nEnvío: ${formatMoney(shippingTotal, currency)}\nTotal: ${formatMoney(total, currency)}\n\nNombre: ${form.firstName} ${form.lastName}\nDirección: ${form.address1}, ${form.city}${form.province ? `, ${form.province}` : ""}\nTeléfono: ${form.phone}`;
|
||||||
|
void navigator.clipboard?.writeText(message);
|
||||||
|
window.open(process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc", "_blank", "noopener,noreferrer");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasHydrated) return null;
|
||||||
|
|
||||||
|
if (items.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg px-4 py-24 text-center">
|
||||||
|
<p className="text-lg font-bold">Tu carrito está vacío.</p>
|
||||||
|
<Button asChild variant="primary" className="mt-6"><Link href="/catalog">Ver catálogo</Link></Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto grid max-w-5xl gap-10 px-4 py-10 lg:grid-cols-[1fr_.8fr] lg:py-16">
|
||||||
|
<div>
|
||||||
|
<Link href="/" className="mb-6 inline-flex items-center gap-1.5 text-sm font-bold text-slate-500 hover:text-ari-marino"><ArrowLeft className="size-4" />Seguir comprando</Link>
|
||||||
|
<h1 className="text-3xl font-black tracking-tight sm:text-4xl">Confirmar pedido</h1>
|
||||||
|
|
||||||
|
{step === "address" && (
|
||||||
|
<form onSubmit={submitAddress} className="mt-8 space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Input placeholder="Nombre" required value={form.firstName} onChange={(event) => setForm({ ...form, firstName: event.target.value })} />
|
||||||
|
<Input placeholder="Apellido" required value={form.lastName} onChange={(event) => setForm({ ...form, lastName: event.target.value })} />
|
||||||
|
</div>
|
||||||
|
<Input placeholder="Dirección" required value={form.address1} onChange={(event) => setForm({ ...form, address1: event.target.value })} />
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Input placeholder="Ciudad" required value={form.city} onChange={(event) => setForm({ ...form, city: event.target.value })} />
|
||||||
|
<Input placeholder="Departamento" value={form.province} onChange={(event) => setForm({ ...form, province: event.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Input placeholder="Teléfono" required value={form.phone} onChange={(event) => setForm({ ...form, phone: event.target.value })} />
|
||||||
|
<Input type="email" placeholder="Correo" required value={form.email} onChange={(event) => setForm({ ...form, email: event.target.value })} />
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm font-bold text-rose-600">{error}</p>}
|
||||||
|
<Button type="submit" variant="primary" size="lg" className="w-full" disabled={loading}>{loading ? "Guardando…" : "Continuar a envío"}</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === "shipping" && (
|
||||||
|
<div className="mt-8 space-y-4">
|
||||||
|
<p className="flex items-center gap-2 text-sm font-bold text-slate-500"><MapPin className="size-4" />{form.address1}, {form.city}{form.province ? `, ${form.province}` : ""}</p>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{shippingOptions.map((option) => (
|
||||||
|
<label key={option.id} className={`flex cursor-pointer items-center justify-between rounded-2xl border-2 p-4 transition ${selectedOptionId === option.id ? "border-ari-marino bg-ari-marino/5" : "border-slate-200"}`}>
|
||||||
|
<span className="flex items-center gap-3 font-bold"><Truck className="size-5 text-ari-marino" />{option.name}</span>
|
||||||
|
<span className="flex items-center gap-3">
|
||||||
|
<span className="font-black">{formatMoney(option.amount, currency)}</span>
|
||||||
|
<input type="radio" name="shipping" checked={selectedOptionId === option.id} onChange={() => setSelectedOptionId(option.id)} />
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
{shippingOptions.length === 0 && <p className="text-sm text-slate-500">No hay opciones de envío disponibles para esta dirección.</p>}
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm font-bold text-rose-600">{error}</p>}
|
||||||
|
<Button variant="primary" size="lg" className="w-full" disabled={loading || !selectedOptionId} onClick={submitShipping}>{loading ? "Guardando…" : "Continuar"}</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === "review" && (
|
||||||
|
<div className="mt-8 space-y-4">
|
||||||
|
<div className="rounded-2xl border border-slate-200 p-5">
|
||||||
|
<p className="text-xs font-black uppercase tracking-wide text-slate-400">Entrega</p>
|
||||||
|
<p className="mt-1 font-bold">{form.firstName} {form.lastName}</p>
|
||||||
|
<p className="text-sm text-slate-500">{form.address1}, {form.city}{form.province ? `, ${form.province}` : ""}</p>
|
||||||
|
<p className="text-sm text-slate-500">{form.phone}</p>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-slate-500">El pago en línea todavía no está disponible — confirmamos tu pedido por WhatsApp con estos datos.</p>
|
||||||
|
<Button variant="primary" size="lg" className="w-full" onClick={continueOnWhatsApp}><MessageCircle className="size-5" />Confirmar por WhatsApp</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="h-fit rounded-3xl border border-slate-200 p-6">
|
||||||
|
<h2 className="font-black">Tu pedido</h2>
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
{items.map((item) => (
|
||||||
|
<div key={item.lineItemId} className="flex items-center gap-3">
|
||||||
|
<div className="relative size-14 shrink-0 overflow-hidden rounded-xl bg-slate-100"><Image src={item.product.thumbnail} alt={item.product.name} fill sizes="56px" className="object-cover" /></div>
|
||||||
|
<div className="flex-1"><p className="text-sm font-bold leading-5">{item.product.name}</p><p className="text-xs text-slate-500">Cantidad: {item.quantity}</p></div>
|
||||||
|
<p className="text-sm font-black">{formatMoney((item.product.price ?? 0) * item.quantity, item.product.currency)}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="mt-5 space-y-2 border-t border-slate-100 pt-4 text-sm">
|
||||||
|
<div className="flex justify-between"><span className="text-slate-500">Subtotal</span><span className="font-bold">{formatMoney(itemsSubtotal, currency)}</span></div>
|
||||||
|
{step === "review" && <div className="flex justify-between"><span className="text-slate-500">Envío</span><span className="font-bold">{formatMoney(shippingTotal, currency)}</span></div>}
|
||||||
|
<div className="flex justify-between text-base"><span className="font-black">Total</span><span className="font-black">{formatMoney(step === "review" ? total : itemsSubtotal, currency)}</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsUser: 1001
|
runAsUser: 1001
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.204
|
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.209
|
||||||
env:
|
env:
|
||||||
- name: HEADLESS_PROVIDER
|
- name: HEADLESS_PROVIDER
|
||||||
value: medusa
|
value: medusa
|
||||||
|
|||||||
@@ -33,9 +33,27 @@ export interface CartSummary {
|
|||||||
cartId: string;
|
cartId: string;
|
||||||
currency: string;
|
currency: string;
|
||||||
subtotal: number;
|
subtotal: number;
|
||||||
|
shippingTotal: number;
|
||||||
|
total: number;
|
||||||
items: CartLine[];
|
items: CartLine[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ShippingAddressInput {
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
address1: string;
|
||||||
|
city: string;
|
||||||
|
province?: string;
|
||||||
|
phone: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShippingOption {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
function backendUrl(): string {
|
function backendUrl(): string {
|
||||||
const value = process.env.MEDUSA_BACKEND_URL;
|
const value = process.env.MEDUSA_BACKEND_URL;
|
||||||
if (!value) {
|
if (!value) {
|
||||||
@@ -61,12 +79,15 @@ type MedusaLineItem = {
|
|||||||
thumbnail?: string | null;
|
thumbnail?: string | null;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
unit_price?: number | null;
|
unit_price?: number | null;
|
||||||
|
product?: { images?: Array<{ url?: string | null }> | null } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type MedusaCart = {
|
type MedusaCart = {
|
||||||
id: string;
|
id: string;
|
||||||
currency_code: string;
|
currency_code: string;
|
||||||
subtotal?: number | null;
|
subtotal?: number | null;
|
||||||
|
shipping_total?: number | null;
|
||||||
|
total?: number | null;
|
||||||
items?: MedusaLineItem[] | null;
|
items?: MedusaLineItem[] | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -75,6 +96,8 @@ function mapCart(cart: MedusaCart): CartSummary {
|
|||||||
cartId: cart.id,
|
cartId: cart.id,
|
||||||
currency: cart.currency_code,
|
currency: cart.currency_code,
|
||||||
subtotal: cart.subtotal ?? 0,
|
subtotal: cart.subtotal ?? 0,
|
||||||
|
shippingTotal: cart.shipping_total ?? 0,
|
||||||
|
total: cart.total ?? cart.subtotal ?? 0,
|
||||||
items: (cart.items ?? []).map((item) => ({
|
items: (cart.items ?? []).map((item) => ({
|
||||||
lineItemId: item.id,
|
lineItemId: item.id,
|
||||||
variantId: item.variant_id,
|
variantId: item.variant_id,
|
||||||
@@ -82,10 +105,13 @@ function mapCart(cart: MedusaCart): CartSummary {
|
|||||||
product: {
|
product: {
|
||||||
id: item.product_id,
|
id: item.product_id,
|
||||||
name: item.product_title || item.title || "Producto",
|
name: item.product_title || item.title || "Producto",
|
||||||
// La linea del carrito no trae el arreglo de imagenes del producto,
|
// item.thumbnail viene null en la practica para todo el catalogo
|
||||||
// solo este campo (a veces null) -- mismo fallback final que ya usa
|
// real (confirmado contra /store/products: product.thumbnail
|
||||||
// mapProduct() en medusa.ts.
|
// tambien es null ahi, incluso con fotos reales cargadas) -- el
|
||||||
thumbnail: item.thumbnail || "/images/brand/logo-ari.png",
|
// catalogo ya resuelve esto cayendo a images[0] (mapProduct() en
|
||||||
|
// medusa.ts), asi que la linea del carrito pide esa misma relacion
|
||||||
|
// explicita (no viene por defecto) y aplica el mismo fallback.
|
||||||
|
thumbnail: item.thumbnail || item.product?.images?.[0]?.url || "/images/brand/logo-ari.png",
|
||||||
price: typeof item.unit_price === "number" ? item.unit_price : null,
|
price: typeof item.unit_price === "number" ? item.unit_price : null,
|
||||||
currency: cart.currency_code,
|
currency: cart.currency_code,
|
||||||
},
|
},
|
||||||
@@ -117,6 +143,11 @@ async function medusaCartFetch(
|
|||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// *items.product.images no viene por defecto (verificado en vivo) y es
|
||||||
|
// lo unico que necesitamos ademas del set por defecto -- *items ya trae
|
||||||
|
// unit_price/product_title/variant_id/quantity sin pedirlos aparte.
|
||||||
|
const ITEMS_FIELDS = "fields=*items,*items.product.images";
|
||||||
|
|
||||||
export async function createCart(): Promise<CartSummary> {
|
export async function createCart(): Promise<CartSummary> {
|
||||||
const data = await medusaCartFetch("/store/carts", {
|
const data = await medusaCartFetch("/store/carts", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -126,7 +157,7 @@ export async function createCart(): Promise<CartSummary> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getCart(cartId: string): Promise<CartSummary> {
|
export async function getCart(cartId: string): Promise<CartSummary> {
|
||||||
const data = await medusaCartFetch(`/store/carts/${cartId}`);
|
const data = await medusaCartFetch(`/store/carts/${cartId}?${ITEMS_FIELDS}`);
|
||||||
return mapCart(data.cart as MedusaCart);
|
return mapCart(data.cart as MedusaCart);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,7 +166,7 @@ export async function addLineItem(
|
|||||||
variantId: string,
|
variantId: string,
|
||||||
quantity: number,
|
quantity: number,
|
||||||
): Promise<CartSummary> {
|
): Promise<CartSummary> {
|
||||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items`, {
|
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items?${ITEMS_FIELDS}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: { variant_id: variantId, quantity },
|
body: { variant_id: variantId, quantity },
|
||||||
});
|
});
|
||||||
@@ -147,7 +178,7 @@ export async function updateLineItemQuantity(
|
|||||||
lineItemId: string,
|
lineItemId: string,
|
||||||
quantity: number,
|
quantity: number,
|
||||||
): Promise<CartSummary> {
|
): Promise<CartSummary> {
|
||||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}`, {
|
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}?${ITEMS_FIELDS}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: { quantity },
|
body: { quantity },
|
||||||
});
|
});
|
||||||
@@ -155,10 +186,57 @@ export async function updateLineItemQuantity(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function removeLineItem(cartId: string, lineItemId: string): Promise<CartSummary> {
|
export async function removeLineItem(cartId: string, lineItemId: string): Promise<CartSummary> {
|
||||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}`, {
|
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}?${ITEMS_FIELDS}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
// Forma distinta a las demas: el carrito actualizado viene en
|
// Forma distinta a las demas: el carrito actualizado viene en
|
||||||
// "parent", no en "cart" -- verificado en vivo, no documentado.
|
// "parent", no en "cart" -- verificado en vivo, no documentado.
|
||||||
return mapCart(data.parent as MedusaCart);
|
return mapCart(data.parent as MedusaCart);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function setShippingAddress(
|
||||||
|
cartId: string,
|
||||||
|
address: ShippingAddressInput,
|
||||||
|
): Promise<CartSummary> {
|
||||||
|
const data = await medusaCartFetch(`/store/carts/${cartId}?${ITEMS_FIELDS}`, {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
email: address.email,
|
||||||
|
shipping_address: {
|
||||||
|
first_name: address.firstName,
|
||||||
|
last_name: address.lastName,
|
||||||
|
address_1: address.address1,
|
||||||
|
city: address.city,
|
||||||
|
province: address.province || undefined,
|
||||||
|
country_code: "co",
|
||||||
|
phone: address.phone,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return mapCart(data.cart as MedusaCart);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MedusaShippingOption = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
amount?: number | null;
|
||||||
|
calculated_price?: { calculated_amount?: number | null } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getShippingOptions(cartId: string): Promise<ShippingOption[]> {
|
||||||
|
const data = await medusaCartFetch(`/store/shipping-options?cart_id=${cartId}`);
|
||||||
|
const options = (data.shipping_options as MedusaShippingOption[] | undefined) ?? [];
|
||||||
|
return options.map((option) => ({
|
||||||
|
id: option.id,
|
||||||
|
name: option.name,
|
||||||
|
amount: option.calculated_price?.calculated_amount ?? option.amount ?? 0,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addShippingMethod(cartId: string, optionId: string): Promise<CartSummary> {
|
||||||
|
const data = await medusaCartFetch(`/store/carts/${cartId}/shipping-methods?${ITEMS_FIELDS}`, {
|
||||||
|
method: "POST",
|
||||||
|
body: { option_id: optionId },
|
||||||
|
});
|
||||||
|
return mapCart(data.cart as MedusaCart);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user