feat(ecommerce): selector Departamento/Ciudad con DIVIPOLA real en checkout
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).
This commit is contained in:
1 parent
7dc54a1d20
commit
61024b8f31
4 files changed
+1251
-8
No files matched your search
@@ -6,9 +6,13 @@ import { ArrowLeft, MapPin, MessageCircle, Truck } from "lucide-react";
|
|||||||
import { type FormEvent, useState } from "react";
|
import { type FormEvent, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ciudadesPorDepartamento, departamentos } from "@/lib/data/colombia";
|
||||||
import { formatMoney } from "@/lib/utils";
|
import { formatMoney } from "@/lib/utils";
|
||||||
import { useCartStore } from "@/store/cart-store";
|
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
|
// ADR 0009, siguiente corte tras el carrito real: direccion + seleccion de
|
||||||
// envio contra el Store API real (mismos endpoints ya verificados en vivo
|
// envio contra el Store API real (mismos endpoints ya verificados en vivo
|
||||||
// para las shipping options). El pago (PayU custom) todavia no existe --
|
// para las shipping options). El pago (PayU custom) todavia no existe --
|
||||||
@@ -35,7 +39,21 @@ async function postJson(url: string, body: unknown) {
|
|||||||
export function CheckoutClient() {
|
export function CheckoutClient() {
|
||||||
const { cartId, items, hasHydrated } = useCartStore();
|
const { cartId, items, hasHydrated } = useCartStore();
|
||||||
const [step, setStep] = useState<Step>("address");
|
const [step, setStep] = useState<Step>("address");
|
||||||
const [form, setForm] = useState({ firstName: "", lastName: "", address1: "", city: "", province: "", phone: "", email: "" });
|
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 [shippingOptions, setShippingOptions] = useState<ShippingOption[]>([]);
|
||||||
const [selectedOptionId, setSelectedOptionId] = useState<string | null>(null);
|
const [selectedOptionId, setSelectedOptionId] = useState<string | null>(null);
|
||||||
const [shippingTotal, setShippingTotal] = useState(0);
|
const [shippingTotal, setShippingTotal] = useState(0);
|
||||||
@@ -48,11 +66,20 @@ export function CheckoutClient() {
|
|||||||
|
|
||||||
async function submitAddress(event: FormEvent) {
|
async function submitAddress(event: FormEvent) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!cartId) return;
|
if (!cartId || !selectedCiudad || !selectedDepartamento) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const cart = await postJson("/api/cart/address", { cartId, ...form });
|
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);
|
if (cart.error) throw new Error(cart.error);
|
||||||
const response = await fetch(`/api/cart/shipping-options?cartId=${cartId}`);
|
const response = await fetch(`/api/cart/shipping-options?cartId=${cartId}`);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
@@ -86,7 +113,7 @@ export function CheckoutClient() {
|
|||||||
|
|
||||||
function continueOnWhatsApp() {
|
function continueOnWhatsApp() {
|
||||||
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
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}`;
|
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);
|
void navigator.clipboard?.writeText(message);
|
||||||
window.open(process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc", "_blank", "noopener,noreferrer");
|
window.open(process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc", "_blank", "noopener,noreferrer");
|
||||||
}
|
}
|
||||||
@@ -116,8 +143,25 @@ export function CheckoutClient() {
|
|||||||
</div>
|
</div>
|
||||||
<Input placeholder="Dirección" required value={form.address1} onChange={(event) => setForm({ ...form, address1: event.target.value })} />
|
<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">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<Input placeholder="Ciudad" required value={form.city} onChange={(event) => setForm({ ...form, city: event.target.value })} />
|
<select
|
||||||
<Input placeholder="Departamento" value={form.province} onChange={(event) => setForm({ ...form, province: event.target.value })} />
|
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>
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<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 placeholder="Teléfono" required value={form.phone} onChange={(event) => setForm({ ...form, phone: event.target.value })} />
|
||||||
@@ -130,7 +174,7 @@ export function CheckoutClient() {
|
|||||||
|
|
||||||
{step === "shipping" && (
|
{step === "shipping" && (
|
||||||
<div className="mt-8 space-y-4">
|
<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>
|
<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">
|
<div className="space-y-3">
|
||||||
{shippingOptions.map((option) => (
|
{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"}`}>
|
<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"}`}>
|
||||||
@@ -153,7 +197,7 @@ export function CheckoutClient() {
|
|||||||
<div className="rounded-2xl border border-slate-200 p-5">
|
<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="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="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.address1}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</p>
|
||||||
<p className="text-sm text-slate-500">{form.phone}</p>
|
<p className="text-sm text-slate-500">{form.phone}</p>
|
||||||
</div>
|
</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>
|
<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>
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{ "id": 5, "name": "Antioquia" },
|
||||||
|
{ "id": 8, "name": "Atlántico" },
|
||||||
|
{ "id": 11, "name": "Bogotá D.C." },
|
||||||
|
{ "id": 13, "name": "Bolívar" },
|
||||||
|
{ "id": 15, "name": "Boyacá" },
|
||||||
|
{ "id": 17, "name": "Caldas" },
|
||||||
|
{ "id": 18, "name": "Caquetá" },
|
||||||
|
{ "id": 19, "name": "Cauca" },
|
||||||
|
{ "id": 20, "name": "Cesar" },
|
||||||
|
{ "id": 23, "name": "Córdoba" },
|
||||||
|
{ "id": 25, "name": "Cundinamarca" },
|
||||||
|
{ "id": 27, "name": "Chocó" },
|
||||||
|
{ "id": 41, "name": "Huila" },
|
||||||
|
{ "id": 44, "name": "La Guajira" },
|
||||||
|
{ "id": 47, "name": "Magdalena" },
|
||||||
|
{ "id": 50, "name": "Meta" },
|
||||||
|
{ "id": 52, "name": "Nariño" },
|
||||||
|
{ "id": 54, "name": "Norte de Santander" },
|
||||||
|
{ "id": 63, "name": "Quindío" },
|
||||||
|
{ "id": 66, "name": "Risaralda" },
|
||||||
|
{ "id": 68, "name": "Santander" },
|
||||||
|
{ "id": 70, "name": "Sucre" },
|
||||||
|
{ "id": 73, "name": "Tolima" },
|
||||||
|
{ "id": 76, "name": "Valle del Cauca" },
|
||||||
|
{ "id": 81, "name": "Arauca" },
|
||||||
|
{ "id": 85, "name": "Casanare" },
|
||||||
|
{ "id": 86, "name": "Putumayo" },
|
||||||
|
{
|
||||||
|
"id": 88,
|
||||||
|
"name": "Archipiélago de San Andrés, Providencia y Santa Catalina"
|
||||||
|
},
|
||||||
|
{ "id": 91, "name": "Amazonas" },
|
||||||
|
{ "id": 94, "name": "Guainía" },
|
||||||
|
{ "id": 95, "name": "Guaviare" },
|
||||||
|
{ "id": 97, "name": "Vaupés" },
|
||||||
|
{ "id": 99, "name": "Vichada" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import departamentosData from "./co-departamentos.json";
|
||||||
|
import ciudadesData from "./co-ciudades.json";
|
||||||
|
|
||||||
|
// Dataset real de DIVIPOLA (Division Politico-Administrativa de Colombia,
|
||||||
|
// codigos oficiales del DANE) -- 33 departamentos + 1123 municipios,
|
||||||
|
// fuente: proyecto26/colombia (github.com/proyecto26/colombia), verificado
|
||||||
|
// contra la codificacion oficial antes de incorporarlo (ej. id 5001 =
|
||||||
|
// Medellin, departmentId 5 = Antioquia).
|
||||||
|
//
|
||||||
|
// Se usan los codigos (no solo los nombres) porque EnvioClick -- la
|
||||||
|
// integracion de envios real que reemplazara la tarifa fija de ADR 0009 --
|
||||||
|
// va a necesitar identificar la ciudad de forma inequivoca, y las
|
||||||
|
// transportadoras colombianas en general referencian ciudades por su
|
||||||
|
// codigo DIVIPOLA, no por texto libre.
|
||||||
|
|
||||||
|
export interface Departamento {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Ciudad {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
departmentId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const departamentos: Departamento[] = departamentosData.data;
|
||||||
|
export const ciudades: Ciudad[] = ciudadesData.data;
|
||||||
|
|
||||||
|
export function ciudadesPorDepartamento(departmentId: number): Ciudad[] {
|
||||||
|
return ciudades.filter((ciudad) => ciudad.departmentId === departmentId);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user