Reemplaza los inputs de texto libre de Ciudad/Departamento por dos selects en cascada, poblados con el dataset oficial de DIVIPOLA (33 departamentos + 1123 municipios, fuente proyecto26/colombia, verificado contra la codificacion real del DANE antes de incorporarlo -- id 5001 = Medellin, departmentId 5 = Antioquia, etc.). Sin dependencia npm nueva (JSON estatico + helper propio). Se guarda el id DIVIPOLA seleccionado en el estado del formulario, no solo el nombre -- EnvioClick (la integracion de envios real que reemplazara la tarifa fija de este ADR) va a necesitar identificar la ciudad sin ambiguedad, y las transportadoras colombianas referencian ciudades por este codigo. El nombre derivado del id sigue siendo lo que se manda a Medusa (shipping_address espera texto, no cambia el contrato existente).
229 lines
12 KiB
TypeScript
229 lines
12 KiB
TypeScript
"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 { ciudadesPorDepartamento, departamentos } from "@/lib/data/colombia";
|
|
import { formatMoney } from "@/lib/utils";
|
|
import { useCartStore } from "@/store/cart-store";
|
|
|
|
const SELECT_CLASS =
|
|
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
|
|
|
// 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: "",
|
|
// Se guarda el id DIVIPOLA seleccionado, no el texto libre -- ver
|
|
// lib/data/colombia.ts. El nombre real se deriva de este id para
|
|
// mandarlo a Medusa (que solo espera texto en shipping_address).
|
|
departmentId: null as number | null,
|
|
cityId: null as number | null,
|
|
phone: "",
|
|
email: "",
|
|
});
|
|
const availableCities = form.departmentId ? ciudadesPorDepartamento(form.departmentId) : [];
|
|
const selectedDepartamento = departamentos.find((departamento) => departamento.id === form.departmentId);
|
|
const selectedCiudad = availableCities.find((ciudad) => ciudad.id === form.cityId);
|
|
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 || !selectedCiudad || !selectedDepartamento) return;
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const cart = await postJson("/api/cart/address", {
|
|
cartId,
|
|
firstName: form.firstName,
|
|
lastName: form.lastName,
|
|
address1: form.address1,
|
|
city: selectedCiudad.name,
|
|
province: selectedDepartamento.name,
|
|
phone: form.phone,
|
|
email: form.email,
|
|
});
|
|
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}, ${selectedCiudad?.name ?? ""}${selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}\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">
|
|
<select
|
|
required
|
|
value={form.departmentId ?? ""}
|
|
onChange={(event) => setForm({ ...form, departmentId: Number(event.target.value) || null, cityId: null })}
|
|
className={SELECT_CLASS}
|
|
>
|
|
<option value="" disabled>Departamento</option>
|
|
{departamentos.map((departamento) => <option key={departamento.id} value={departamento.id}>{departamento.name}</option>)}
|
|
</select>
|
|
<select
|
|
required
|
|
disabled={!form.departmentId}
|
|
value={form.cityId ?? ""}
|
|
onChange={(event) => setForm({ ...form, cityId: Number(event.target.value) || null })}
|
|
className={SELECT_CLASS}
|
|
>
|
|
<option value="" disabled>Ciudad</option>
|
|
{availableCities.map((ciudad) => <option key={ciudad.id} value={ciudad.id}>{ciudad.name}</option>)}
|
|
</select>
|
|
</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}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</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}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</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>
|
|
);
|
|
}
|