Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b7dc7b6de | ||
|
|
2601e5e83e | ||
|
|
fecac320d9 | ||
|
|
811e0e0887 | ||
|
|
aee6515890 | ||
|
|
2e47f7b55d | ||
|
|
54be99fa2c | ||
|
|
bc530c98e6 | ||
|
|
3b748cc014 | ||
|
|
73f9424331 | ||
|
|
0917c966cb | ||
|
|
61024b8f31 | ||
|
|
7dc54a1d20 | ||
|
|
d05112ae65 | ||
|
|
bb2c0bbe85 | ||
|
|
cdab538cfb | ||
|
|
f124ae0bbd | ||
|
|
b8ce9ded87 | ||
|
|
b12dd848af | ||
|
|
d28ee4a49d | ||
|
|
3fc77c6cdc | ||
|
|
14c473eb8b | ||
|
|
93e2401e3b | ||
|
|
615cf9ce77 | ||
|
|
5931e8933c | ||
|
|
52c628faa0 |
No files matched your search
@@ -23,7 +23,10 @@ ENV CI=true \
|
||||
S3_BUCKET=ari-shopping \
|
||||
S3_ENDPOINT=http://127.0.0.1:9000 \
|
||||
MEILISEARCH_HOST=http://127.0.0.1:7700 \
|
||||
MEILISEARCH_API_KEY=build-only-meili-key
|
||||
MEILISEARCH_API_KEY=build-only-meili-key \
|
||||
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
||||
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
||||
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback
|
||||
|
||||
COPY package.json package-lock.json .npmrc ./
|
||||
|
||||
|
||||
@@ -157,6 +157,30 @@ module.exports = defineConfig({
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
resolve: "@medusajs/medusa/auth",
|
||||
options: {
|
||||
providers: [
|
||||
// emailpass se declara explicito junto con google -- una vez
|
||||
// que el modulo auth se customiza, la doc no deja claro si el
|
||||
// provider default (emailpass) se sigue registrando solo.
|
||||
{
|
||||
resolve: "@medusajs/medusa/auth-emailpass",
|
||||
id: "emailpass",
|
||||
options: {},
|
||||
},
|
||||
{
|
||||
resolve: "@medusajs/medusa/auth-google",
|
||||
id: "google",
|
||||
options: {
|
||||
clientId: required("GOOGLE_CLIENT_ID"),
|
||||
clientSecret: required("GOOGLE_CLIENT_SECRET"),
|
||||
callbackUrl: required("GOOGLE_CALLBACK_URL"),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
// ADR 0006 Etapa 2. Sin required(): a diferencia de S3/DB, Meilisearch
|
||||
|
||||
@@ -126,28 +126,29 @@ Verificado contra fuentes reales el mismo día (no memoria):
|
||||
los métodos que se pidieron (PSE + Nequi "y demás bancos") sin que
|
||||
la cuenta bancaria propia del comercio sea Bancolombia.
|
||||
|
||||
**Decisión:** PayU, vía el plugin comunitario `@tax1driver/medusa-payu`
|
||||
(compatibilidad declarada con Medusa 2.4.0+, cubre nuestra versión
|
||||
2.18.0). Wompi queda descartado por el requisito de registro
|
||||
Bancolombia/Nequi, no por limitación técnica del plugin en sí.
|
||||
**Decisión:** PayU como proveedor de pago (negocio) se mantiene. La vía
|
||||
técnica cambió el 2026-08-29 — ver nota de implementación al final de
|
||||
este documento: ningún plugin comunitario de Medusa sirve para PayU
|
||||
LatAm, hace falta un módulo de pago custom. Wompi queda descartado por
|
||||
el requisito de registro Bancolombia/Nequi, no por limitación técnica.
|
||||
|
||||
**Pendiente antes de implementar (no resoluble en este ADR):**
|
||||
|
||||
- Registro real de comercio en PayU (persona natural o jurídica —
|
||||
jurídica pide NIT, representante legal y estados financieros
|
||||
básicos) y credenciales reales (API keys, merchant ID, webhook
|
||||
config) — nunca generadas ni asumidas por mí.
|
||||
- Verificar el código fuente real de `@tax1driver/medusa-payu` en el
|
||||
tag exacto a instalar antes de confiar en su documentación, misma
|
||||
disciplina que ya destapó desviaciones reales en el plugin de
|
||||
Meilisearch (ADR 0006).
|
||||
básicos) y credenciales reales (`apiLogin`, `apiKey`, `merchantId`,
|
||||
`accountId` — terminología real de la API de PayU LatAm, ver nota de
|
||||
implementación) — nunca generadas ni asumidas por mí.
|
||||
- Escribir el módulo de pago custom para PayU LatAm (no instalar un
|
||||
plugin — no existe ninguno real para esta API, ver nota de
|
||||
implementación).
|
||||
|
||||
## Opciones consideradas
|
||||
|
||||
| Opción | A favor | En contra |
|
||||
|---|---|---|
|
||||
| **Stripe** | Integración core de Medusa, mejor documentada, configuración mínima | No acepta comercios registrados en Colombia — bloqueador de negocio, no técnico |
|
||||
| **PayU** (`@tax1driver/medusa-payu`) — **elegido** | Compatibilidad declarada explícitamente con Medusa 2.4.0+ (cubre 2.18.0); solo exige cuenta bancaria colombiana a nombre del comercio, sin banco específico (encaja con Davivienda/Lulo Bank/Banco de Bogotá); soporta PSE + Nequi + Daviplata para el cliente sin importar el banco del comercio | Plugin comunitario, no de primera clase; requiere la misma verificación de código fuente que ya se le hizo al plugin de Meilisearch antes de confiar en él |
|
||||
| **PayU** — **elegido** (proveedor de negocio; integración técnica ahora es custom, ver nota de implementación) | Solo exige cuenta bancaria colombiana a nombre del comercio, sin banco específico (encaja con Davivienda/Lulo Bank/Banco de Bogotá); soporta PSE + Nequi + Daviplata para el cliente sin importar el banco del comercio | Ningún plugin de Medusa real sirve para su API LatAm (`apiLogin`/`apiKey`/`accountId`) — los dos paquetes que parecían encajar por nombre son en realidad para PayU Polonia/CEE (`clientId`/`posId`/`secondKey`), uno de ellos archivado; requiere módulo de pago custom |
|
||||
| **Wompi** (`medusa-payment-wompi-col`) | Liquidación directa en COP vía Bancolombia | Exige cuenta Bancolombia o, como mínimo, Nequi solo para **registrarse** como comercio — ninguno de los bancos disponibles (Davivienda/Lulo Bank/Banco de Bogotá) califica sin abrir una cuenta nueva; además, sin versión de Medusa documentada ni actividad reciente visible en el plugin |
|
||||
| **Seguir con WhatsApp** (no pago en línea) | Cero riesgo nuevo, cero dependencia externa | No resuelve el objetivo real (transacción completa sin intervención manual); no es checkout, es lo que ya existe hoy |
|
||||
|
||||
@@ -156,17 +157,14 @@ Bancolombia/Nequi, no por limitación técnica del plugin en sí.
|
||||
- Las shipping options son un prerequisito independiente del proveedor
|
||||
y deben configurarse primero — sin ellas ningún flujo de checkout
|
||||
completa, sea cual sea el pago.
|
||||
- Al ser `@tax1driver/medusa-payu` un plugin comunitario (no de
|
||||
primera clase como Stripe), exige la misma disciplina de
|
||||
verificación que ya destapó desviaciones reales en el plugin de
|
||||
Meilisearch (ADR 0006, nota de implementación): leer el código
|
||||
fuente en el tag exacto que se va a instalar, no el README genérico
|
||||
ni asumir que "compatibilidad declarada" significa "verificado en
|
||||
este proyecto".
|
||||
- Los webhooks de pago (registrados por el plugin en
|
||||
`/hooks/payment/payu`) deben validarse en vivo contra la cadena de
|
||||
red real del lab antes de confiar en el flujo, dado el precedente de
|
||||
`incidente-cloudflared-504-quic-2026-08.md`.
|
||||
- El pago de PayU se implementa como módulo custom (`AbstractPaymentProvider`
|
||||
de Medusa) contra la API real de PayU LatAm, no como instalación de
|
||||
un plugin de terceros — más superficie propia para mantener, mismo
|
||||
patrón de esfuerzo que ya se identificó para EnvíoClick en §2.
|
||||
- Los webhooks de pago (a definir en el módulo custom, apuntando a la
|
||||
URL de notificación real de PayU LatAm) deben validarse en vivo
|
||||
contra la cadena de red real del lab antes de confiar en el flujo,
|
||||
dado el precedente de `incidente-cloudflared-504-quic-2026-08.md`.
|
||||
- Se acepta como deuda: si en el futuro se abre una cuenta Bancolombia
|
||||
o Nequi, Wompi (liquidación más directa en COP) vuelve a ser una
|
||||
opción válida a reevaluar — no se descarta por limitación técnica,
|
||||
@@ -174,3 +172,56 @@ Bancolombia/Nequi, no por limitación técnica del plugin en sí.
|
||||
- Revertir esta decisión implica deshabilitar el provider en la región
|
||||
y volver al botón de WhatsApp — el carrito y el catálogo no cambian
|
||||
de forma, solo el paso final.
|
||||
|
||||
## Nota de implementación (2026-08-29): shipping options creadas
|
||||
|
||||
Bloqueador de §1 resuelto en producción, verificado extremo a extremo
|
||||
contra el Store API real (no solo creado en Admin):
|
||||
|
||||
- Stock location "Bodega principal ARI Shopping" (`sloc_01M15G3D1336V8WQW3VZQRP6AN`).
|
||||
- Fulfillment set + zona de servicio "Colombia" (`geo_zone` tipo país, `co`).
|
||||
- Provider `manual_manual` habilitado en la ubicación.
|
||||
- Shipping option "Envío nacional estándar", tarifa fija $15.000 COP
|
||||
(placeholder de negocio dentro del rango real de mercado
|
||||
$12.000–$18.000 que dio el usuario, no un cálculo por peso/volumen —
|
||||
eso es justamente lo que EnvíoClick resolvería más adelante),
|
||||
vinculada al Default Shipping Profile y a la región Colombia/COP.
|
||||
- **Paso no documentado en ningún lado y que rompía todo en silencio:**
|
||||
la stock location tiene que estar vinculada al Sales Channel
|
||||
(`/admin/stock-locations/{id}/sales-channels`) para que el Store API
|
||||
devuelva la shipping option — sin esto, `GET /store/shipping-options`
|
||||
devolvía `[]` vacío pese a que el fulfillment set, la zona de
|
||||
servicio y el provider ya estaban bien configurados. Confirmado con
|
||||
un carrito de prueba real (dirección `co` + `cart_id`) antes y
|
||||
después del vínculo.
|
||||
|
||||
## Nota de implementación 2 (2026-08-29): corrección — no existe plugin real para PayU LatAm
|
||||
|
||||
Antes de instalar nada se verificó el código/README real de los dos
|
||||
únicos paquetes de Medusa que aparecen buscando "PayU" — misma
|
||||
disciplina que ya aplicó ADR 0006 al plugin de Meilisearch, esta vez
|
||||
con un resultado distinto: **ninguno de los dos sirve.**
|
||||
|
||||
- `@tax1driver/medusa-payu`: opciones de configuración `clientId`,
|
||||
`clientSecret`, `merchantPosId`, `secondKey` — terminología exacta
|
||||
de la API de **PayU Polonia/CEE** (OAuth + `posId`), no de PayU
|
||||
LatAm.
|
||||
- `medusa-plugin-payu` (`rigby-sh/medusa-plugin-payu`): mismo problema
|
||||
(`clientId`, `posId`, sandbox en `secure.snd.payu.com`, dominio de
|
||||
PayU Europa) y además **archivado desde 2025-03-21** — sin
|
||||
mantenimiento.
|
||||
- La API real que se necesita, PayU LatAm
|
||||
(`developers.payulatam.com`, la que cubre Colombia junto con
|
||||
Argentina/Brasil/Chile/México/Panamá/Perú), autentica con
|
||||
`apiLogin`/`apiKey` en el objeto merchant y `accountId` en el
|
||||
objeto order — un modelo de autenticación distinto, no solo nombres
|
||||
de campo distintos.
|
||||
|
||||
"PayU" es una marca compartida por dos productos/API históricamente
|
||||
separados (LatAm vs. Europa/CEE); un paquete que dice "PayU" a secas
|
||||
sin especificar LatAm es, con alta probabilidad, para el producto
|
||||
europeo. **Consecuencia:** la integración de pago se implementa como
|
||||
módulo custom de Medusa (`AbstractPaymentProvider`) contra
|
||||
`developers.payulatam.com` directamente — mismo tipo de esfuerzo que
|
||||
ya se había anticipado para EnvíoClick en §2, no una instalación de
|
||||
plugin como asumía la decisión original de este ADR.
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
runAsNonRoot: false
|
||||
containers:
|
||||
- name: app
|
||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.205
|
||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.207
|
||||
# El base saca TODAS las capabilities. Probado en vivo y
|
||||
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
||||
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
||||
|
||||
@@ -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,31 @@
|
||||
import { removeLineItem, updateLineItemQuantity } from "@/lib/headless/providers/medusa-cart";
|
||||
|
||||
interface RouteParams { params: Promise<{ lineItemId: string }> }
|
||||
|
||||
export async function POST(request: Request, { params }: RouteParams) {
|
||||
const { lineItemId } = await params;
|
||||
const { cartId, quantity } = await request.json();
|
||||
if (!cartId || typeof quantity !== "number") {
|
||||
return Response.json({ error: "cartId y quantity son obligatorios" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const cart = await updateLineItemQuantity(cartId, lineItemId, quantity);
|
||||
return Response.json(cart);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { params }: RouteParams) {
|
||||
const { lineItemId } = await params;
|
||||
const cartId = new URL(request.url).searchParams.get("cartId");
|
||||
if (!cartId) {
|
||||
return Response.json({ error: "cartId es obligatorio" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const cart = await removeLineItem(cartId, lineItemId);
|
||||
return Response.json(cart);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { addLineItem } from "@/lib/headless/providers/medusa-cart";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { cartId, variantId, quantity } = await request.json();
|
||||
if (!cartId || !variantId) {
|
||||
return Response.json({ error: "cartId y variantId son obligatorios" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const cart = await addLineItem(cartId, variantId, quantity ?? 1);
|
||||
return Response.json(cart);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createCart, getCart } from "@/lib/headless/providers/medusa-cart";
|
||||
|
||||
// cart-store.ts es "use client" y no puede pegarle directo a Medusa
|
||||
// (MEDUSA_BACKEND_URL es DNS interno del cluster, no resuelve desde el
|
||||
// navegador) -- mismo motivo que /api/search. Nunca cachear: es
|
||||
// estado mutable por sesion, no catalogo.
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const cart = await createCart();
|
||||
return Response.json(cart);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
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 cart = await getCart(cartId);
|
||||
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,14 @@
|
||||
import { loginCustomer } from "@/lib/headless/providers/medusa-customer";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { email, password } = await request.json();
|
||||
if (!email || !password) {
|
||||
return Response.json({ error: "Correo y contraseña son obligatorios" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const customer = await loginCustomer(email, password);
|
||||
return Response.json(customer);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getCurrentCustomer } from "@/lib/headless/providers/medusa-customer";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = new URL(request.url).searchParams.get("token");
|
||||
if (!token) {
|
||||
return Response.json({ error: "token es obligatorio" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const customer = await getCurrentCustomer(token);
|
||||
return Response.json(customer);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 401 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { registerCustomer } from "@/lib/headless/providers/medusa-customer";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { email, password, firstName, lastName } = await request.json();
|
||||
if (!email || !password || !firstName || !lastName) {
|
||||
return Response.json({ error: "Faltan campos obligatorios" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const customer = await registerCustomer(email, password, firstName, lastName);
|
||||
return Response.json(customer);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { CheckoutClient } from "@/components/checkout/checkout-client";
|
||||
|
||||
export default function CheckoutPage() {
|
||||
return <CheckoutClient />;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { LogOut, MessageCircle, PackageCheck } from "lucide-react";
|
||||
import { type FormEvent, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useCustomerStore } from "@/store/customer-store";
|
||||
|
||||
type Mode = "login" | "register";
|
||||
|
||||
export function AccountDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
|
||||
const { customer, hasHydrated, loading, error, login, register, logout } = useCustomerStore();
|
||||
const [mode, setMode] = useState<Mode>("login");
|
||||
const [form, setForm] = useState({ email: "", password: "", firstName: "", lastName: "" });
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
const ok = mode === "login"
|
||||
? await login(form.email, form.password)
|
||||
: await register(form.email, form.password, form.firstName, form.lastName);
|
||||
if (ok) setForm({ email: "", password: "", firstName: "", lastName: "" });
|
||||
}
|
||||
|
||||
const isLoggedIn = hasHydrated && customer !== null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg p-7">
|
||||
<div className="pr-10">
|
||||
{isLoggedIn ? (
|
||||
<>
|
||||
<span className="text-xs font-black uppercase tracking-[.16em] text-ari-coral">Tu cuenta</span>
|
||||
<h2 className="mt-3 text-3xl font-black">Hola, {customer.firstName ?? customer.email}</h2>
|
||||
<p className="mt-3 text-sm leading-6 text-slate-600">{customer.email}</p>
|
||||
<div className="mt-6 grid gap-3">
|
||||
<Button asChild variant="outline"><Link href="/catalog" onClick={() => onOpenChange(false)}><PackageCheck />Ver mis opciones de compra</Link></Button>
|
||||
<Button variant="ghost" onClick={logout}><LogOut className="size-4" />Cerrar sesión</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-xs font-black uppercase tracking-[.16em] text-ari-coral">Atención personalizada</span>
|
||||
<h2 className="mt-3 text-3xl font-black">{mode === "login" ? "Inicia sesión" : "Crea tu cuenta"}</h2>
|
||||
<form onSubmit={submit} className="mt-5 space-y-3">
|
||||
{mode === "register" && (
|
||||
<div className="grid gap-3 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 type="email" placeholder="Correo" required value={form.email} onChange={(event) => setForm({ ...form, email: event.target.value })} />
|
||||
<Input type="password" placeholder="Contraseña" required minLength={8} value={form.password} onChange={(event) => setForm({ ...form, password: event.target.value })} />
|
||||
{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 ? "Un momento…" : mode === "login" ? "Iniciar sesión" : "Crear cuenta"}
|
||||
</Button>
|
||||
</form>
|
||||
<button
|
||||
type="button"
|
||||
className="mt-3 text-sm font-bold text-ari-marino hover:underline"
|
||||
onClick={() => setMode(mode === "login" ? "register" : "login")}
|
||||
>
|
||||
{mode === "login" ? "¿No tienes cuenta? Regístrate" : "¿Ya tienes cuenta? Inicia sesión"}
|
||||
</button>
|
||||
<div className="mt-6 border-t border-slate-100 pt-5">
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<a href={process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc"} target="_blank" rel="noopener noreferrer">
|
||||
<MessageCircle />Hablar con ARI
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { Minus, Plus, ShoppingBag, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
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 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 (
|
||||
<Sheet open={isOpen} onOpenChange={(open) => { if (!open) closeCart(); }}>
|
||||
<SheetContent>
|
||||
@@ -49,7 +43,15 @@ export function CartDrawer() {
|
||||
<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 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>
|
||||
</div>
|
||||
</SheetContent>
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { ChevronDown, Heart, LayoutGrid, Menu, MessageCircle, PackageCheck, ShoppingCart, UserRound } from "lucide-react";
|
||||
import { ChevronDown, Heart, LayoutGrid, Menu, ShoppingCart, UserRound } from "lucide-react";
|
||||
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { AccountDialog } from "@/components/account/account-dialog";
|
||||
import { PredictiveSearch } from "@/components/search/predictive-search";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import type { Category, Product } from "@/lib/headless/types";
|
||||
import { useCartStore } from "@/store/cart-store";
|
||||
import { useCustomerStore } from "@/store/customer-store";
|
||||
import { useWishlistStore } from "@/store/wishlist-store";
|
||||
|
||||
type CategoryNode = Category & { children: Category[] };
|
||||
@@ -34,6 +35,9 @@ export function Navbar({ products, categories }: { products: Product[]; categori
|
||||
const openWishlist = useWishlistStore((state) => state.openWishlist);
|
||||
const count = cartHydrated ? items.reduce((sum, item) => sum + item.quantity, 0) : 0;
|
||||
const wishlistCount = wishlistHydrated ? wishlistProducts.length : 0;
|
||||
const customer = useCustomerStore((state) => state.customer);
|
||||
const customerHydrated = useCustomerStore((state) => state.hasHydrated);
|
||||
const isLoggedIn = customerHydrated && customer !== null;
|
||||
|
||||
const tree = useMemo(() => buildCategoryTree(categories), [categories]);
|
||||
// Derivado de los productos reales (no de un endpoint de colecciones):
|
||||
@@ -62,7 +66,15 @@ export function Navbar({ products, categories }: { products: Product[]; categori
|
||||
</Link>
|
||||
<PredictiveSearch />
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="icon" aria-label="Mi cuenta" className="hidden border-slate-300 bg-white text-slate-900 hover:border-ari-coral hover:bg-ari-coral/10 sm:inline-flex" onClick={() => setAccountOpen(true)}><UserRound /></Button>
|
||||
{/* Antes escondido en mobile (solo alcanzable desde el menu
|
||||
hamburguesa) -- pedido explicito del usuario: visible
|
||||
siempre en el header, con un punto verde cuando hay sesion
|
||||
iniciada (mismo patron que el badge de cantidad del
|
||||
carrito/favoritos, pero de presencia, no de conteo). */}
|
||||
<Button variant="outline" size="icon" aria-label={isLoggedIn ? "Mi cuenta (sesión iniciada)" : "Mi cuenta"} className="relative inline-flex border-slate-300 bg-white text-slate-900 hover:border-ari-coral hover:bg-ari-coral/10" onClick={() => setAccountOpen(true)}>
|
||||
<UserRound />
|
||||
{isLoggedIn && <span className="absolute -right-1 -top-1 size-3 rounded-full border-2 border-white bg-emerald-500" />}
|
||||
</Button>
|
||||
<Button variant="outline" size="icon" aria-label={`Favoritos: ${wishlistCount}`} className="relative hidden border-slate-300 bg-white text-slate-900 hover:border-ari-coral hover:bg-ari-coral/10 sm:inline-flex" onClick={openWishlist}>
|
||||
<Heart />
|
||||
{wishlistCount > 0 && <span className="absolute -right-1.5 -top-1.5 grid size-5 place-items-center rounded-full bg-ari-marino text-[10px] font-black text-white">{wishlistCount}</span>}
|
||||
@@ -108,19 +120,7 @@ export function Navbar({ products, categories }: { products: Product[]; categori
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<Dialog open={accountOpen} onOpenChange={setAccountOpen}>
|
||||
<DialogContent className="max-w-lg p-7">
|
||||
<div className="pr-10">
|
||||
<span className="text-xs font-black uppercase tracking-[.16em] text-ari-coral">Atención personalizada</span>
|
||||
<h2 className="mt-3 text-3xl font-black">Tu cuenta ARI</h2>
|
||||
<p className="mt-3 text-sm leading-6 text-slate-600">El inicio de sesión quedará conectado al backend headless. Mientras tanto, puedes gestionar pedidos y disponibilidad directamente por WhatsApp.</p>
|
||||
<div className="mt-6 grid gap-3">
|
||||
<Button asChild variant="primary" size="lg"><a href={process.env.NEXT_PUBLIC_WHATSAPP_URL ?? "https://wa.link/rvcqqc"} target="_blank" rel="noopener noreferrer"><MessageCircle />Hablar con ARI</a></Button>
|
||||
<Button asChild variant="outline"><Link href="/catalog" onClick={() => setAccountOpen(false)}><PackageCheck />Ver mis opciones de compra</Link></Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<AccountDialog open={accountOpen} onOpenChange={setAccountOpen} />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
runAsUser: 1001
|
||||
containers:
|
||||
- name: app
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.204
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.213
|
||||
env:
|
||||
- name: HEADLESS_PROVIDER
|
||||
value: medusa
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
// ADR 0009: carrito real conectado a Medusa (Store API), en vez del
|
||||
// estado 100% local que existia antes. Archivo separado de medusa.ts
|
||||
// a proposito -- ese es de solo lectura (catalogo, cacheado con
|
||||
// revalidate/tags), este es de escritura (carrito, siempre no-store,
|
||||
// nunca debe cachearse).
|
||||
//
|
||||
// Formas de respuesta verificadas en vivo contra la API real
|
||||
// (2026-08-29), no asumidas contra documentacion:
|
||||
// - crear/agregar/actualizar linea: { cart: {...} }
|
||||
// - eliminar linea: { id, object, deleted, parent: {...} } -- el
|
||||
// carrito actualizado viene en "parent", no en "cart".
|
||||
// - agregar el mismo variant_id dos veces hace merge de cantidad en la
|
||||
// misma linea (confirmado con un carrito de prueba real), no crea
|
||||
// una linea duplicada -- por eso addLineItem siempre manda
|
||||
// quantity=1 sin revisar antes si ya existe.
|
||||
|
||||
export interface CartLineProduct {
|
||||
id: string;
|
||||
name: string;
|
||||
thumbnail: string;
|
||||
price: number | null;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export interface CartLine {
|
||||
lineItemId: string;
|
||||
product: CartLineProduct;
|
||||
quantity: number;
|
||||
variantId: string;
|
||||
}
|
||||
|
||||
export interface CartSummary {
|
||||
cartId: string;
|
||||
currency: string;
|
||||
subtotal: number;
|
||||
shippingTotal: number;
|
||||
total: number;
|
||||
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 {
|
||||
const value = process.env.MEDUSA_BACKEND_URL;
|
||||
if (!value) {
|
||||
throw new Error("MEDUSA_BACKEND_URL no está configurado.");
|
||||
}
|
||||
return value.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function regionId(): string {
|
||||
const value = process.env.MEDUSA_REGION_ID;
|
||||
if (!value) {
|
||||
throw new Error("MEDUSA_REGION_ID no está configurado.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
type MedusaLineItem = {
|
||||
id: string;
|
||||
product_id: string;
|
||||
variant_id: string;
|
||||
title?: string | null;
|
||||
product_title?: string | null;
|
||||
thumbnail?: string | null;
|
||||
quantity: number;
|
||||
unit_price?: number | null;
|
||||
product?: { images?: Array<{ url?: string | null }> | null } | null;
|
||||
};
|
||||
|
||||
type MedusaCart = {
|
||||
id: string;
|
||||
currency_code: string;
|
||||
subtotal?: number | null;
|
||||
shipping_total?: number | null;
|
||||
total?: number | null;
|
||||
items?: MedusaLineItem[] | null;
|
||||
};
|
||||
|
||||
function mapCart(cart: MedusaCart): CartSummary {
|
||||
return {
|
||||
cartId: cart.id,
|
||||
currency: cart.currency_code,
|
||||
subtotal: cart.subtotal ?? 0,
|
||||
shippingTotal: cart.shipping_total ?? 0,
|
||||
total: cart.total ?? cart.subtotal ?? 0,
|
||||
items: (cart.items ?? []).map((item) => ({
|
||||
lineItemId: item.id,
|
||||
variantId: item.variant_id,
|
||||
quantity: item.quantity,
|
||||
product: {
|
||||
id: item.product_id,
|
||||
name: item.product_title || item.title || "Producto",
|
||||
// item.thumbnail viene null en la practica para todo el catalogo
|
||||
// real (confirmado contra /store/products: product.thumbnail
|
||||
// tambien es null ahi, incluso con fotos reales cargadas) -- el
|
||||
// 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,
|
||||
currency: cart.currency_code,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async function medusaCartFetch(
|
||||
path: string,
|
||||
init?: { method?: string; body?: unknown },
|
||||
): Promise<Record<string, unknown>> {
|
||||
const publishableKey = process.env.MEDUSA_PUBLISHABLE_KEY;
|
||||
|
||||
const response = await fetch(`${backendUrl()}${path}`, {
|
||||
method: init?.method ?? "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(publishableKey ? { "x-publishable-api-key": publishableKey } : {}),
|
||||
},
|
||||
body: init?.body ? JSON.stringify(init.body) : undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new Error(`Medusa cart API ${response.status}: ${text.slice(0, 300)}`);
|
||||
}
|
||||
|
||||
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> {
|
||||
const data = await medusaCartFetch("/store/carts", {
|
||||
method: "POST",
|
||||
body: { region_id: regionId() },
|
||||
});
|
||||
return mapCart(data.cart as MedusaCart);
|
||||
}
|
||||
|
||||
export async function getCart(cartId: string): Promise<CartSummary> {
|
||||
const data = await medusaCartFetch(`/store/carts/${cartId}?${ITEMS_FIELDS}`);
|
||||
return mapCart(data.cart as MedusaCart);
|
||||
}
|
||||
|
||||
export async function addLineItem(
|
||||
cartId: string,
|
||||
variantId: string,
|
||||
quantity: number,
|
||||
): Promise<CartSummary> {
|
||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items?${ITEMS_FIELDS}`, {
|
||||
method: "POST",
|
||||
body: { variant_id: variantId, quantity },
|
||||
});
|
||||
return mapCart(data.cart as MedusaCart);
|
||||
}
|
||||
|
||||
export async function updateLineItemQuantity(
|
||||
cartId: string,
|
||||
lineItemId: string,
|
||||
quantity: number,
|
||||
): Promise<CartSummary> {
|
||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}?${ITEMS_FIELDS}`, {
|
||||
method: "POST",
|
||||
body: { quantity },
|
||||
});
|
||||
return mapCart(data.cart as MedusaCart);
|
||||
}
|
||||
|
||||
export async function removeLineItem(cartId: string, lineItemId: string): Promise<CartSummary> {
|
||||
const data = await medusaCartFetch(`/store/carts/${cartId}/line-items/${lineItemId}?${ITEMS_FIELDS}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
// Forma distinta a las demas: el carrito actualizado viene en
|
||||
// "parent", no en "cart" -- verificado en vivo, no documentado.
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// Cuentas de cliente reales conectadas a Medusa (Store API), mismo patron
|
||||
// que medusa-cart.ts -- server-side, nunca cacheado (auth es estado
|
||||
// mutable por sesion, no catalogo).
|
||||
//
|
||||
// Flujo verificado en vivo (2026-08-29) antes de escribir este archivo,
|
||||
// no asumido contra documentacion: registro (auth/customer/emailpass/
|
||||
// register) da un token de registro; ese token crea el customer real
|
||||
// (POST /store/customers); pero ese token de registro NO sirve como
|
||||
// sesion del customer -- hay que loguear de nuevo para obtener el token
|
||||
// de sesion real. Mensajes de error exactos confirmados: registro con
|
||||
// correo repetido -> 401 "Identity with email already exists"; login con
|
||||
// credenciales invalidas -> 401 "Invalid email or password".
|
||||
|
||||
export interface CustomerSummary {
|
||||
token: string;
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
}
|
||||
|
||||
function backendUrl(): string {
|
||||
const value = process.env.MEDUSA_BACKEND_URL;
|
||||
if (!value) {
|
||||
throw new Error("MEDUSA_BACKEND_URL no está configurado.");
|
||||
}
|
||||
return value.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function medusaAuthFetch(
|
||||
path: string,
|
||||
init?: { method?: string; body?: unknown; token?: string },
|
||||
): Promise<Record<string, unknown>> {
|
||||
const publishableKey = process.env.MEDUSA_PUBLISHABLE_KEY;
|
||||
|
||||
const response = await fetch(`${backendUrl()}${path}`, {
|
||||
method: init?.method ?? "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(publishableKey ? { "x-publishable-api-key": publishableKey } : {}),
|
||||
...(init?.token ? { Authorization: `Bearer ${init.token}` } : {}),
|
||||
},
|
||||
body: init?.body ? JSON.stringify(init.body) : undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const message = typeof data.message === "string" ? data.message : `Error ${response.status}`;
|
||||
throw new Error(message);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
type MedusaCustomer = {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
};
|
||||
|
||||
export async function getCurrentCustomer(token: string): Promise<CustomerSummary> {
|
||||
const data = await medusaAuthFetch("/store/customers/me", { token });
|
||||
const customer = data.customer as MedusaCustomer;
|
||||
return {
|
||||
token,
|
||||
id: customer.id,
|
||||
email: customer.email,
|
||||
firstName: customer.first_name ?? null,
|
||||
lastName: customer.last_name ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loginCustomer(email: string, password: string): Promise<CustomerSummary> {
|
||||
let data: Record<string, unknown>;
|
||||
try {
|
||||
data = await medusaAuthFetch("/auth/customer/emailpass", {
|
||||
method: "POST",
|
||||
body: { email, password },
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as Error).message === "Invalid email or password") {
|
||||
throw new Error("Correo o contraseña incorrectos.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return getCurrentCustomer(data.token as string);
|
||||
}
|
||||
|
||||
export async function registerCustomer(
|
||||
email: string,
|
||||
password: string,
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
): Promise<CustomerSummary> {
|
||||
let data: Record<string, unknown>;
|
||||
try {
|
||||
data = await medusaAuthFetch("/auth/customer/emailpass/register", {
|
||||
method: "POST",
|
||||
body: { email, password },
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as Error).message === "Identity with email already exists") {
|
||||
throw new Error("Ese correo ya está registrado — inicia sesión en vez de crear una cuenta nueva.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await medusaAuthFetch("/store/customers", {
|
||||
method: "POST",
|
||||
token: data.token as string,
|
||||
body: { email, first_name: firstName, last_name: lastName },
|
||||
});
|
||||
// El token de registro crea el customer pero no queda como sesion real
|
||||
// -- se loguea de nuevo para obtener el token de sesion (confirmado en
|
||||
// vivo, no documentado explicitamente).
|
||||
return loginCustomer(email, password);
|
||||
}
|
||||
@@ -2,60 +2,117 @@
|
||||
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import type { Product } from "@/lib/headless/types";
|
||||
import type { CartLine } from "@/lib/headless/providers/medusa-cart";
|
||||
|
||||
export interface CartItem {
|
||||
product: Product;
|
||||
quantity: number;
|
||||
variantId?: string;
|
||||
}
|
||||
// ADR 0009: carrito real conectado a un cart_id de Medusa (Store API,
|
||||
// via /api/cart/*) en vez de estado 100% local -- precios y existencia
|
||||
// de linea son los que confirma el servidor, no un calculo optimista
|
||||
// en el cliente. Primer corte a proposito: sin UI de direccion/envio
|
||||
// todavia, el checkout sigue cerrando por WhatsApp (CartDrawer).
|
||||
export type CartItem = CartLine;
|
||||
|
||||
interface CartState {
|
||||
cartId: string | null;
|
||||
items: CartItem[];
|
||||
isOpen: boolean;
|
||||
hasHydrated: boolean;
|
||||
openCart: () => void;
|
||||
closeCart: () => void;
|
||||
setHasHydrated: (value: boolean) => void;
|
||||
addItem: (product: Product, variantId?: string) => void;
|
||||
removeItem: (productId: string) => void;
|
||||
updateQuantity: (productId: string, quantity: number) => void;
|
||||
clearCart: () => void;
|
||||
addItem: (product: { id: string }, variantId?: string) => Promise<void>;
|
||||
removeItem: (productId: string) => Promise<void>;
|
||||
updateQuantity: (productId: string, quantity: number) => Promise<void>;
|
||||
clearCart: () => Promise<void>;
|
||||
syncCart: () => Promise<void>;
|
||||
}
|
||||
|
||||
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 const useCartStore = create<CartState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
(set, get) => ({
|
||||
cartId: null,
|
||||
items: [],
|
||||
isOpen: false,
|
||||
hasHydrated: false,
|
||||
openCart: () => set({ isOpen: true }),
|
||||
closeCart: () => set({ isOpen: false }),
|
||||
setHasHydrated: (value) => set({ hasHydrated: value }),
|
||||
addItem: (product, variantId) => set((state) => {
|
||||
const existing = state.items.find(
|
||||
(item) => item.product.id === product.id && item.variantId === variantId,
|
||||
|
||||
addItem: async (product, variantId) => {
|
||||
set({ isOpen: true });
|
||||
if (!variantId) return;
|
||||
|
||||
let cartId = get().cartId;
|
||||
if (!cartId) {
|
||||
const cart = await (await fetch("/api/cart", { method: "POST" })).json();
|
||||
if (!cart.cartId) return;
|
||||
cartId = cart.cartId;
|
||||
set({ cartId, items: cart.items ?? [] });
|
||||
}
|
||||
|
||||
const cart = await postJson("/api/cart/items", { cartId, variantId, quantity: 1 });
|
||||
if (cart.items) set({ items: cart.items });
|
||||
},
|
||||
|
||||
removeItem: async (productId) => {
|
||||
const { cartId, items } = get();
|
||||
const line = items.find((item) => item.product.id === productId);
|
||||
if (!cartId || !line) return;
|
||||
const response = await fetch(`/api/cart/items/${line.lineItemId}?cartId=${cartId}`, { method: "DELETE" });
|
||||
const cart = await response.json();
|
||||
if (cart.items) set({ items: cart.items });
|
||||
},
|
||||
|
||||
updateQuantity: async (productId, quantity) => {
|
||||
if (quantity <= 0) return get().removeItem(productId);
|
||||
const { cartId, items } = get();
|
||||
const line = items.find((item) => item.product.id === productId);
|
||||
if (!cartId || !line) return;
|
||||
const cart = await postJson(`/api/cart/items/${line.lineItemId}`, { cartId, quantity });
|
||||
if (cart.items) set({ items: cart.items });
|
||||
},
|
||||
|
||||
clearCart: async () => {
|
||||
const { cartId, items } = get();
|
||||
if (!cartId) return;
|
||||
await Promise.all(
|
||||
items.map((item) => fetch(`/api/cart/items/${item.lineItemId}?cartId=${cartId}`, { method: "DELETE" })),
|
||||
);
|
||||
const items = existing
|
||||
? state.items.map((item) => item === existing ? { ...item, quantity: item.quantity + 1 } : item)
|
||||
: [...state.items, { product, quantity: 1, variantId }];
|
||||
return { items, isOpen: true };
|
||||
}),
|
||||
removeItem: (productId) => set((state) => ({
|
||||
items: state.items.filter((item) => item.product.id !== productId),
|
||||
})),
|
||||
updateQuantity: (productId, quantity) => set((state) => ({
|
||||
items: quantity <= 0
|
||||
? state.items.filter((item) => item.product.id !== productId)
|
||||
: state.items.map((item) => item.product.id === productId ? { ...item, quantity } : item),
|
||||
})),
|
||||
clearCart: () => set({ items: [] }),
|
||||
set({ items: [] });
|
||||
},
|
||||
|
||||
// Al recargar la pagina, el cart_id guardado en localStorage puede
|
||||
// llevar dias -- se refresca contra el servidor en vez de confiar en
|
||||
// el ultimo snapshot local (precios/stock pudieron cambiar).
|
||||
syncCart: async () => {
|
||||
const cartId = get().cartId;
|
||||
if (!cartId) return;
|
||||
try {
|
||||
const response = await fetch(`/api/cart?cartId=${cartId}`);
|
||||
if (!response.ok) return;
|
||||
const cart = await response.json();
|
||||
if (cart.items) set({ items: cart.items });
|
||||
} catch {
|
||||
// Sin red: se queda con el ultimo estado local conocido.
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "ari-shopping-cart-v4",
|
||||
name: "ari-shopping-cart-v5",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({ items: state.items }),
|
||||
onRehydrateStorage: () => (state) => state?.setHasHydrated(true),
|
||||
partialize: (state) => ({ cartId: state.cartId, items: state.items }),
|
||||
onRehydrateStorage: () => (state) => {
|
||||
state?.setHasHydrated(true);
|
||||
void state?.syncCart();
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
// Cuenta de cliente real conectada a Medusa (Store API, via
|
||||
// /api/customer/*), mismo patron que cart-store.ts: token + datos basicos
|
||||
// persistidos en localStorage, resincronizados contra el servidor al
|
||||
// rehidratar (el token puede llevar dias, o haber sido revocado).
|
||||
export interface Customer {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
}
|
||||
|
||||
interface CustomerState {
|
||||
token: string | null;
|
||||
customer: Customer | null;
|
||||
hasHydrated: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
setHasHydrated: (value: boolean) => void;
|
||||
register: (email: string, password: string, firstName: string, lastName: string) => Promise<boolean>;
|
||||
login: (email: string, password: string) => Promise<boolean>;
|
||||
logout: () => void;
|
||||
syncCustomer: () => Promise<void>;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
function toCustomer(data: Record<string, unknown>): Customer {
|
||||
return {
|
||||
id: data.id as string,
|
||||
email: data.email as string,
|
||||
firstName: (data.firstName as string | null) ?? null,
|
||||
lastName: (data.lastName as string | null) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const useCustomerStore = create<CustomerState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: null,
|
||||
customer: null,
|
||||
hasHydrated: false,
|
||||
loading: false,
|
||||
error: null,
|
||||
setHasHydrated: (value) => set({ hasHydrated: value }),
|
||||
|
||||
register: async (email, password, firstName, lastName) => {
|
||||
set({ loading: true, error: null });
|
||||
const result = await postJson("/api/customer/register", { email, password, firstName, lastName });
|
||||
if (result.error) {
|
||||
set({ loading: false, error: result.error });
|
||||
return false;
|
||||
}
|
||||
set({ loading: false, token: result.token, customer: toCustomer(result) });
|
||||
return true;
|
||||
},
|
||||
|
||||
login: async (email, password) => {
|
||||
set({ loading: true, error: null });
|
||||
const result = await postJson("/api/customer/login", { email, password });
|
||||
if (result.error) {
|
||||
set({ loading: false, error: result.error });
|
||||
return false;
|
||||
}
|
||||
set({ loading: false, token: result.token, customer: toCustomer(result) });
|
||||
return true;
|
||||
},
|
||||
|
||||
logout: () => set({ token: null, customer: null, error: null }),
|
||||
|
||||
// El token guardado en localStorage puede llevar dias o haber sido
|
||||
// revocado -- se refresca contra el servidor en vez de confiar en el
|
||||
// ultimo snapshot local.
|
||||
syncCustomer: async () => {
|
||||
const token = get().token;
|
||||
if (!token) return;
|
||||
try {
|
||||
const response = await fetch(`/api/customer/me?token=${encodeURIComponent(token)}`);
|
||||
if (!response.ok) {
|
||||
set({ token: null, customer: null });
|
||||
return;
|
||||
}
|
||||
const result = await response.json();
|
||||
if (result.id) set({ customer: toCustomer(result) });
|
||||
} catch {
|
||||
// Sin red: se queda con el ultimo estado local conocido.
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "ari-shopping-customer-v1",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({ token: state.token, customer: state.customer }),
|
||||
onRehydrateStorage: () => (state) => {
|
||||
state?.setHasHydrated(true);
|
||||
void state?.syncCustomer();
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
Reference in new issue
Block a user