Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d28ee4a49d | ||
|
|
3fc77c6cdc | ||
|
|
14c473eb8b | ||
|
|
93e2401e3b | ||
|
|
615cf9ce77 | ||
|
|
5931e8933c | ||
|
|
52c628faa0 | ||
|
|
f88b72d781 | ||
|
|
525ebde5ce | ||
|
|
0f98fa286e | ||
|
|
33f510dcdd | ||
|
|
52295e2c6d | ||
|
|
fe0387cc4c | ||
|
|
cfec1543ab | ||
|
|
49a6645378 | ||
|
|
11ef812f64 | ||
|
|
4b2e6477e5 | ||
|
|
e5f9ec5f1d | ||
|
|
11b97b9178 | ||
|
|
229999fa5a | ||
|
|
8e0053ab84 | ||
|
|
e837c55de8 | ||
|
|
4994d063eb | ||
|
|
a974e738eb | ||
|
|
15483e7a5b | ||
|
|
a4dd1c444a | ||
|
|
a3913ce457 | ||
|
|
503d714ea4 | ||
|
|
afd6991519 | ||
|
|
7d27b527e2 | ||
|
|
3ad6951f44 | ||
|
|
0e57bb04d1 | ||
|
|
e631672804 | ||
|
|
ca26c6ebea | ||
|
|
12d3c692d3 | ||
|
|
9c441032de | ||
|
|
603f4b963d | ||
|
|
ac37774245 | ||
|
|
7aa9f40abc | ||
|
|
617a69d58a | ||
|
|
09a8698f7e | ||
|
|
23700c5b1d | ||
|
|
5c173d5f40 | ||
|
|
d0a3554959 | ||
|
|
75dedc4e67 | ||
|
|
801db95aa8 | ||
|
|
6df24abcb9 | ||
|
|
a6291ffe14 | ||
|
|
030bf2712a | ||
|
|
f5ddb63c8a | ||
|
|
d536b0bb8b | ||
|
|
260c7076e2 | ||
|
|
59024cd6e5 | ||
|
|
ebd341c060 | ||
|
|
e7349f34c3 | ||
|
|
c94ad5f651 | ||
|
|
ce929188ac | ||
|
|
98e0d331e9 | ||
|
|
d299fc1201 |
No files matched your search
@@ -0,0 +1,227 @@
|
|||||||
|
# ADR 0009 — Checkout real (pago en línea + envíos) para ARI Shopping
|
||||||
|
|
||||||
|
**Estado:** aceptada — proveedor de pago decidido (PayU, §3);
|
||||||
|
implementación real (credenciales, shipping options, código) pendiente
|
||||||
|
**Fecha:** 2026-08-28
|
||||||
|
|
||||||
|
## Contexto
|
||||||
|
|
||||||
|
El carrito hoy no completa una transacción real: arma el pedido en el
|
||||||
|
cliente y lo cierra con un botón "Continuar por WhatsApp"
|
||||||
|
(`components/layout/navbar.tsx`, `mobile-add-to-cart.tsx`) — un
|
||||||
|
placeholder intencional, no un bug. El diálogo de cuenta ya lo admite
|
||||||
|
explícitamente ("El inicio de sesión quedará conectado al backend
|
||||||
|
headless. Mientras tanto..."). Ni checkout ni auth de clientes tienen
|
||||||
|
ADR previo ni intento de implementación en el historial de git de
|
||||||
|
ningún repo del lab — este es terreno nuevo.
|
||||||
|
|
||||||
|
Investigación previa a este ADR (2026-08-28, confirmado contra código
|
||||||
|
real y documentación oficial vigente, no memoria de entrenamiento —
|
||||||
|
misma disciplina que ADR 0006):
|
||||||
|
|
||||||
|
- **Pagos:** `commerce-backend/medusa-config.ts` no registra ningún
|
||||||
|
provider de pago — el único módulo configurado hoy es
|
||||||
|
`@medusajs/medusa/file` (storage S3).
|
||||||
|
- **Envíos:** existe una sola región ("Colombia", COP), creada a mano
|
||||||
|
vía Admin API durante el incidente de precios de agosto
|
||||||
|
(`incidente-medusa-precios-region-id-2026-08.md`), no vía ningún
|
||||||
|
script de seed — no existe ningún script de seed en el repo. **No
|
||||||
|
hay ninguna shipping option configurada en ningún lado.** Sin esto
|
||||||
|
el checkout no puede completarse aunque el pago ya funcione — es un
|
||||||
|
prerequisito invisible, independiente del proveedor de pago elegido.
|
||||||
|
- **Auth:** cero código de cliente/login en todo el storefront (grep
|
||||||
|
sobre `lib/`, `app/`, `components/` sin resultados para
|
||||||
|
`customer`/`login`/`useAuth`/`/store/customers`). El módulo de
|
||||||
|
auth/customer de Medusa viene incluido en el core — falta
|
||||||
|
enteramente el lado del storefront, no el backend. **Medusa soporta
|
||||||
|
checkout como invitado**, así que auth no bloquea checkout y puede
|
||||||
|
secuenciarse por separado — fuera de alcance de este ADR.
|
||||||
|
|
||||||
|
## 1. Flujo de checkout real en Medusa v2 (Store API)
|
||||||
|
|
||||||
|
Confirmado contra `docs.medusajs.com` (2026-08-28): el flujo son 7
|
||||||
|
pasos encadenados — crear carrito → agregar items → dirección de envío
|
||||||
|
→ **seleccionar método de envío** (`POST` a la ruta de shipping method
|
||||||
|
del carrito, requiere que ya exista al menos una shipping option) →
|
||||||
|
payment collection → payment session → completar orden. Ningún paso
|
||||||
|
es opcional; el paso de método de envío es exactamente el que hoy no
|
||||||
|
tiene ninguna shipping option que ofrecer.
|
||||||
|
|
||||||
|
## 2. Estado real de soporte de pago en Medusa 2.18.0
|
||||||
|
|
||||||
|
- **Stripe es de primera clase** (`@medusajs/medusa/payment-stripe`,
|
||||||
|
incluido en el core, no un plugin de terceros — a diferencia de la
|
||||||
|
situación de Meilisearch en ADR 0006). Configuración mínima
|
||||||
|
verificada:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/payment",
|
||||||
|
options: {
|
||||||
|
providers: [{
|
||||||
|
resolve: "@medusajs/medusa/payment-stripe",
|
||||||
|
id: "stripe",
|
||||||
|
options: { apiKey: process.env.STRIPE_API_KEY },
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Env vars: `STRIPE_API_KEY` (siempre) y `STRIPE_WEBHOOK_SECRET`
|
||||||
|
(obligatorio en producción). Tras configurar, hay que habilitar el
|
||||||
|
provider **en la región** desde el Admin — un paso manual aparte,
|
||||||
|
igual que ya pasó con la región misma.
|
||||||
|
|
||||||
|
- **Bloqueador real de negocio, no técnico: Stripe no acepta cuentas
|
||||||
|
de comercio registradas en Colombia.** Confirmado contra
|
||||||
|
`stripe.com/global` (2026-08-28) — Brasil y México sí están en la
|
||||||
|
lista de países soportados para abrir cuenta, Colombia no aparece.
|
||||||
|
La única vía sería registrar una entidad de negocio en un país
|
||||||
|
soportado, fuera de alcance realista para este lab. Esto invalida a
|
||||||
|
Stripe como opción pese a ser la integración técnicamente más
|
||||||
|
simple y mejor documentada.
|
||||||
|
- **Alternativas con presencia real en Colombia y algún plugin de
|
||||||
|
Medusa existente:**
|
||||||
|
- **PayU** (`@tax1driver/medusa-payu`): el propio repo declara
|
||||||
|
compatibilidad explícita con Medusa `v2.4.0+` — cubre nuestra
|
||||||
|
versión (2.18.0). Webhook auto-registrado en `/hooks/payment/payu`.
|
||||||
|
- **Wompi** (`medusa-payment-wompi-col`, respaldado por Bancolombia,
|
||||||
|
liquidación directa en COP): revisé el repo directamente
|
||||||
|
(2026-08-28) y **no documenta contra qué versión de Medusa se
|
||||||
|
probó, ni tiene releases/actividad reciente visible** — mayor
|
||||||
|
riesgo de compatibilidad no verificada que PayU, aunque el
|
||||||
|
encaje de negocio (banco local, moneda nativa) sea el más
|
||||||
|
directo. Antes de elegirlo habría que repetir el nivel de
|
||||||
|
verificación que ADR 0006 le hizo al plugin de Meilisearch: leer
|
||||||
|
el código fuente real, no confiar en el README.
|
||||||
|
- **Riesgo de red ya conocido, no nuevo:** cualquier webhook de pago
|
||||||
|
entra por la misma cadena Cloudflare → NPM → Traefik que ya causó
|
||||||
|
un incidente real con otro servicio
|
||||||
|
(`incidente-cloudflared-504-quic-2026-08.md`). Validar la entrega de
|
||||||
|
webhooks en vivo antes de confiar en el flujo, no asumir que
|
||||||
|
"funciona igual que todo lo demás".
|
||||||
|
|
||||||
|
## 3. Decisión de proveedor — PayU
|
||||||
|
|
||||||
|
Dato de negocio real que decidió esto (aportado por el usuario,
|
||||||
|
2026-08-28): las cuentas bancarias disponibles son Davivienda, Lulo
|
||||||
|
Bank y Banco de Bogotá — **ninguna es Bancolombia ni Nequi**.
|
||||||
|
|
||||||
|
Verificado contra fuentes reales el mismo día (no memoria):
|
||||||
|
|
||||||
|
- **Wompi exige cuenta Bancolombia o, como mínimo, cuenta Nequi para
|
||||||
|
poder registrarse como comercio** (modelo Agregador) — confirmado
|
||||||
|
contra el reglamento de comercios de Wompi y su centro de soporte.
|
||||||
|
La liquidación de ventas sí puede ir después a cualquier banco
|
||||||
|
colombiano, pero la puerta de entrada al registro sigue siendo
|
||||||
|
Bancolombia/Nequi. Con los bancos disponibles hoy, esto exigiría
|
||||||
|
abrir una cuenta Nequi nueva solo para poder registrarse — paso
|
||||||
|
extra evitable.
|
||||||
|
- **PayU solo exige "cuenta bancaria colombiana a nombre del
|
||||||
|
comercio"**, sin banco específico — Davivienda, Lulo Bank o Banco de
|
||||||
|
Bogotá califican igual, sin pasos previos. Además ya soporta **PSE**
|
||||||
|
(transferencia desde cualquier banco colombiano del cliente, sin
|
||||||
|
relación con el banco del comercio), **Nequi** y **Daviplata** como
|
||||||
|
métodos de pago para los clientes vía redirección — cubre exactamente
|
||||||
|
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 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 (`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** — **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 |
|
||||||
|
|
||||||
|
## Consecuencias
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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,
|
||||||
|
solo por el requisito de registro actual.
|
||||||
|
- 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.
|
||||||
@@ -96,6 +96,7 @@ nav:
|
|||||||
- "0006 · Motor de búsqueda y facetas": decisiones/0006-motor-busqueda-facetas.md
|
- "0006 · Motor de búsqueda y facetas": decisiones/0006-motor-busqueda-facetas.md
|
||||||
- "0007 · Identidad visual propia": decisiones/0007-identidad-visual-propia.md
|
- "0007 · Identidad visual propia": decisiones/0007-identidad-visual-propia.md
|
||||||
- "0008 · Identidad Navy & Coral": decisiones/0008-identidad-navy-coral.md
|
- "0008 · Identidad Navy & Coral": decisiones/0008-identidad-navy-coral.md
|
||||||
|
- "0009 · Checkout real": decisiones/0009-checkout-real.md
|
||||||
- Plantilla ADR: decisiones/plantilla-adr.md
|
- Plantilla ADR: decisiones/plantilla-adr.md
|
||||||
- Playbooks:
|
- Playbooks:
|
||||||
- Crashloop Medusa: playbooks/incidente-crashloop-medusa.md
|
- Crashloop Medusa: playbooks/incidente-crashloop-medusa.md
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsNonRoot: false
|
runAsNonRoot: false
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.187
|
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.207
|
||||||
# El base saca TODAS las capabilities. Probado en vivo y
|
# El base saca TODAS las capabilities. Probado en vivo y
|
||||||
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
||||||
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ArrowRight } from "lucide-react";
|
import { ArrowRight } from "lucide-react";
|
||||||
import { CategoryTiles } from "@/components/home/category-tiles";
|
import { CategoryTiles } from "@/components/home/category-tiles";
|
||||||
import { HeroBento } from "@/components/home/hero-bento";
|
import { HeroCarousel } from "@/components/home/hero-carousel";
|
||||||
import { TrustBar } from "@/components/home/trust-bar";
|
import { TrustBar } from "@/components/home/trust-bar";
|
||||||
import { ProductCarousel } from "@/components/product/product-carousel";
|
import { ProductCarousel } from "@/components/product/product-carousel";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -17,5 +18,24 @@ export const dynamic = "force-dynamic";
|
|||||||
export default async function HomePage() {
|
export default async function HomePage() {
|
||||||
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
|
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
|
||||||
const treasures = products.filter((product) => product.isNew || product.featured).slice(0, 8);
|
const treasures = products.filter((product) => product.isNew || product.featured).slice(0, 8);
|
||||||
return <><HeroBento /><TrustBar /><div className="content-auto"><CategoryTiles categories={categories} /></div><section className="content-auto mx-auto max-w-7xl px-4 py-14"><div className="mb-8 flex items-end justify-between gap-5"><div><span className="text-xs font-black uppercase tracking-[.18em] text-fuchsia-600">Novedades</span><h2 className="mt-2 text-4xl font-black tracking-tight sm:text-5xl">Tesoros recién llegados</h2><p className="mt-3 text-slate-500">Desliza y encuentra nuevos favoritos.</p></div><Button asChild variant="outline" className="hidden sm:inline-flex"><Link href="/catalog">Ver catálogo <ArrowRight className="size-4" /></Link></Button></div><ProductCarousel products={treasures} /></section><section className="content-auto mx-auto max-w-7xl px-4 pb-20"><div className="grid overflow-hidden rounded-[2rem] bg-gradient-to-r from-cyan-500 via-blue-600 to-violet-600 text-white shadow-2xl lg:grid-cols-[1fr_.7fr]"><div className="p-8 sm:p-12"><span className="text-xs font-black uppercase tracking-[.18em] text-yellow-300">Club ARI</span><h2 className="mt-3 text-4xl font-black tracking-tight sm:text-6xl">Promociones, lanzamientos y mucha diversión.</h2><p className="mt-5 max-w-xl text-white/80">Únete a nuestra comunidad y recibe primero las novedades del catálogo.</p><Button variant="yellow" size="lg" className="mt-7">Quiero unirme</Button></div><div className="min-h-64 bg-[url('/images/promo/promo-backpacks.webp')] bg-cover bg-center" /></div></section></>;
|
return <><HeroCarousel /><TrustBar /><div className="content-auto"><CategoryTiles categories={categories} /></div><section className="content-auto mx-auto max-w-7xl px-4 py-14"><div className="mb-8 flex items-end justify-between gap-5"><div><span className="text-xs font-black uppercase tracking-[.18em] text-ari-coral">Novedades</span><h2 className="mt-2 text-4xl font-black tracking-tight sm:text-5xl">Tesoros recién llegados</h2><p className="mt-3 text-slate-500">Desliza y encuentra nuevos favoritos.</p></div><Button asChild variant="outline" className="hidden sm:inline-flex"><Link href="/catalog">Ver catálogo <ArrowRight className="size-4" /></Link></Button></div><ProductCarousel products={treasures} /></section><section className="content-auto mx-auto max-w-7xl px-4 pb-20"><div className="grid overflow-hidden rounded-[2rem] bg-ari-marino text-white shadow-2xl lg:grid-cols-[1fr_.7fr]"><div className="p-8 sm:p-12"><span className="text-xs font-black uppercase tracking-[.18em] text-ari-coral-claro">Club ARI</span><h2 className="mt-3 text-4xl font-black tracking-tight sm:text-6xl">Promociones, lanzamientos y mucha diversión.</h2><p className="mt-5 max-w-xl text-white/80">Únete a nuestra comunidad y recibe primero las novedades del catálogo.</p><Button variant="yellow" size="lg" className="mt-7">Quiero unirme</Button></div>{/* No hay herramienta de generacion de imagenes disponible para crear un
|
||||||
|
asset nuevo -- se reconstruye el mismo efecto (fondo punteado +
|
||||||
|
fotos estilo polaroid) con CSS y fotos reales de producto ya
|
||||||
|
existentes, en azul/amarillo de marca en vez del violeta original
|
||||||
|
de promo-backpacks.webp. */}
|
||||||
|
<div className="relative min-h-64 overflow-hidden bg-ari-coral-claro">
|
||||||
|
<div className="absolute inset-0 [background-image:radial-gradient(rgba(0,85,184,0.35)_1.5px,transparent_1.5px)] [background-size:18px_18px]" />
|
||||||
|
<div className="absolute -bottom-12 -left-12 size-52 rounded-full bg-ari-marino" />
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center gap-3 p-6">
|
||||||
|
<div className="relative size-28 -rotate-6 overflow-hidden rounded-xl border-4 border-white bg-white shadow-xl sm:size-32">
|
||||||
|
<Image src="/images/products/ari-011-mochila-escolar-de-spider-man-de-disney-.webp" alt="" fill sizes="128px" className="object-cover" />
|
||||||
|
</div>
|
||||||
|
<div className="relative size-28 rotate-3 overflow-hidden rounded-xl border-4 border-white bg-white shadow-xl sm:size-32">
|
||||||
|
<Image src="/images/products/ari-016-disney-mochila-iron-man-de-poliester-ult.webp" alt="" fill sizes="128px" className="object-cover" />
|
||||||
|
</div>
|
||||||
|
<div className="relative hidden size-28 -rotate-3 overflow-hidden rounded-xl border-4 border-white bg-white shadow-xl sm:block sm:size-32">
|
||||||
|
<Image src="/images/products/ari-009-mochilas-disney-coleccion-marvel.webp" alt="" fill sizes="128px" className="object-cover" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div></div></section></>;
|
||||||
}
|
}
|
||||||
@@ -33,5 +33,5 @@ export default async function ProductPage({ params }: ProductPageProps) {
|
|||||||
if (!product) notFound();
|
if (!product) notFound();
|
||||||
const products = await getProducts();
|
const products = await getProducts();
|
||||||
const recommended = products.filter((candidate) => candidate.id !== product.id && (candidate.category === product.category || candidate.collection === product.collection)).slice(0, 8);
|
const recommended = products.filter((candidate) => candidate.id !== product.id && (candidate.category === product.category || candidate.collection === product.collection)).slice(0, 8);
|
||||||
return <><section className="mx-auto grid max-w-7xl gap-10 px-4 py-10 lg:grid-cols-[1.08fr_.92fr] lg:py-16"><ProductGallery images={product.images} name={product.name} /><div><span className="text-xs font-black uppercase tracking-[.18em] text-fuchsia-600">{product.category} · {product.collection}</span><h1 className="mt-3 text-4xl font-black tracking-tight sm:text-6xl">{product.name}</h1><p className="mt-5 text-lg leading-8 text-slate-600">{product.description}</p><div className="mt-8"><ProductPurchase product={product} /></div><Accordion type="single" collapsible className="mt-8"><AccordionItem value="details"><AccordionTrigger>Detalles del producto</AccordionTrigger><AccordionContent>Marca: {product.brand}. Edad recomendada: {product.ageRange}. La disponibilidad y presentación final se confirman con Ari Shopping.</AccordionContent></AccordionItem><AccordionItem value="shipping"><AccordionTrigger>Envíos y entregas</AccordionTrigger><AccordionContent>Coordinamos envíos nacionales y entrega según ubicación. Los tiempos se confirman durante la cotización.</AccordionContent></AccordionItem></Accordion></div></section>{recommended.length > 0 && <section className="mx-auto max-w-7xl px-4 pb-24"><h2 className="mb-7 text-3xl font-black">También te puede gustar</h2><ProductCarousel products={recommended} /></section>}<MobileAddToCart product={product} /></>;
|
return <><section className="mx-auto grid max-w-7xl gap-10 px-4 py-10 lg:grid-cols-[1.08fr_.92fr] lg:py-16"><ProductGallery images={product.images} name={product.name} /><div><span className="text-xs font-black uppercase tracking-[.18em] text-ari-coral">{product.category} · {product.collection}</span><h1 className="mt-3 text-4xl font-black tracking-tight sm:text-6xl">{product.name}</h1><p className="mt-5 text-lg leading-8 text-slate-600">{product.description}</p><div className="mt-8"><ProductPurchase product={product} /></div><Accordion type="single" collapsible className="mt-8"><AccordionItem value="details"><AccordionTrigger>Detalles del producto</AccordionTrigger><AccordionContent>Marca: {product.brand}. Edad recomendada: {product.ageRange}. La disponibilidad y presentación final se confirman con Ari Shopping.</AccordionContent></AccordionItem><AccordionItem value="shipping"><AccordionTrigger>Envíos y entregas</AccordionTrigger><AccordionContent>Coordinamos envíos nacionales y entrega según ubicación. Los tiempos se confirman durante la cotización.</AccordionContent></AccordionItem></Accordion></div></section>{recommended.length > 0 && <section className="mx-auto max-w-7xl px-4 pb-24"><h2 className="mb-7 text-3xl font-black">También te puede gustar</h2><ProductCarousel products={recommended} /></section>}<MobileAddToCart product={product} /></>;
|
||||||
}
|
}
|
||||||
@@ -10,16 +10,20 @@ type TileContent = { subtitle: string; image?: string; color: string };
|
|||||||
// (ver ADR 0005) -- solo se mapean imagen/subtitulo para las que ya tienen
|
// (ver ADR 0005) -- solo se mapean imagen/subtitulo para las que ya tienen
|
||||||
// un asset en public/images/categories/. Las demas caen al tile de solo
|
// un asset en public/images/categories/. Las demas caen al tile de solo
|
||||||
// gradiente en vez de mostrar una imagen que no les corresponde.
|
// gradiente en vez de mostrar una imagen que no les corresponde.
|
||||||
|
// Fondos pastel solidos (patron Walmart-inspirado, ADR 0008 sub-fase 4)
|
||||||
|
// en vez de los gradientes saturados originales del esquema arcoiris --
|
||||||
|
// un tono pastel distinto por categoria, no una escala de marca (serian
|
||||||
|
// todos casi iguales), pero coordinados en la misma temperatura suave.
|
||||||
const tileContent: Record<string, TileContent> = {
|
const tileContent: Record<string, TileContent> = {
|
||||||
juguetes: { subtitle: "Personajes que inspiran", image: "/images/categories/figuras.webp", color: "from-yellow-300 to-orange-400" },
|
juguetes: { subtitle: "Personajes que inspiran", image: "/images/categories/figuras.webp", color: "bg-amber-100" },
|
||||||
"mochilas-y-morrales": { subtitle: "Estilo para cada aventura", image: "/images/categories/mochilas.webp", color: "from-cyan-400 to-blue-500" },
|
"mochilas-y-morrales": { subtitle: "Estilo para cada aventura", image: "/images/categories/mochilas.webp", color: "bg-sky-100" },
|
||||||
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "from-pink-300 to-fuchsia-400" },
|
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "bg-rose-100" },
|
||||||
educativos: { subtitle: "Aprender jugando", color: "from-emerald-400 to-teal-600" },
|
educativos: { subtitle: "Aprender jugando", color: "bg-emerald-100" },
|
||||||
"accion-y-aventura": { subtitle: "Para explorar sin límites", color: "from-red-500 to-rose-700" },
|
"accion-y-aventura": { subtitle: "Para explorar sin límites", color: "bg-orange-100" },
|
||||||
variedades: { subtitle: "Un poco de todo", color: "from-violet-400 to-purple-600" },
|
variedades: { subtitle: "Un poco de todo", color: "bg-violet-100" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultTile: TileContent = { subtitle: "Explora esta categoría", color: "from-slate-400 to-slate-600" };
|
const defaultTile: TileContent = { subtitle: "Explora esta categoría", color: "bg-slate-100" };
|
||||||
|
|
||||||
// Tile individual reutilizado tanto por la seccion de mundos del home
|
// Tile individual reutilizado tanto por la seccion de mundos del home
|
||||||
// como por el grid del catalogo (tiles promocionales intercalados,
|
// como por el grid del catalogo (tiles promocionales intercalados,
|
||||||
@@ -31,20 +35,24 @@ export function PromoTile({ category, className = "" }: { category: Category; cl
|
|||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
href={`/catalog?category=${encodeURIComponent(category.name)}`}
|
href={`/catalog?category=${encodeURIComponent(category.name)}`}
|
||||||
className={cn(`group relative min-h-64 overflow-hidden rounded-[2rem] bg-gradient-to-br ${content.color} shadow-xl`, className)}
|
className={cn(`group relative min-h-64 overflow-hidden rounded-[2rem] ${content.color} shadow-sm ring-1 ring-slate-900/5`, className)}
|
||||||
>
|
>
|
||||||
|
{/* Patron Walmart: foto recortada (object-cover) llenando casi toda
|
||||||
|
la tarjeta, con solo un margen delgado del pastel como marco --
|
||||||
|
no flotando chica con espacio muerto alrededor (object-contain,
|
||||||
|
intento anterior, reportado como "no aprovecha el espacio"), ni
|
||||||
|
a pantalla completa sin marco (el intento antes de ese). */}
|
||||||
{content.image && (
|
{content.image && (
|
||||||
<>
|
<div className="absolute inset-3 bottom-24 overflow-hidden rounded-2xl">
|
||||||
<Image src={content.image} alt={category.name} fill sizes="(max-width: 640px) 100vw, (max-width: 1024px) 33vw, 16vw" className="object-cover transition duration-500 group-hover:scale-105" />
|
<Image src={content.image} alt="" fill sizes="(max-width: 640px) 45vw, (max-width: 1024px) 25vw, 14vw" className="object-cover transition duration-500 group-hover:scale-105" />
|
||||||
<div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-white/5" />
|
</div>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between p-6 text-white">
|
<div className="absolute inset-x-0 bottom-0 flex items-end justify-between p-6 text-slate-900">
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-xl font-black">{category.name}</h3>
|
<h3 className="text-xl font-black">{category.name}</h3>
|
||||||
<p className="mt-1 text-sm font-semibold text-white/80">{content.subtitle}</p>
|
<p className="mt-1 text-sm font-semibold text-slate-600">{content.subtitle}</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="grid size-11 shrink-0 place-items-center rounded-full bg-white text-slate-950 transition group-hover:rotate-45">
|
<span className="grid size-11 shrink-0 place-items-center rounded-full bg-ari-marino text-white transition group-hover:rotate-45">
|
||||||
<ArrowUpRight />
|
<ArrowUpRight />
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -61,10 +69,10 @@ export function CategoryTiles({ categories }: { categories: Category[] }) {
|
|||||||
<section className="mx-auto max-w-7xl px-4 py-14">
|
<section className="mx-auto max-w-7xl px-4 py-14">
|
||||||
<div className="mb-8 flex items-end justify-between gap-4">
|
<div className="mb-8 flex items-end justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-xs font-black uppercase tracking-[.18em] text-fuchsia-600">Explora por mundos</span>
|
<span className="text-xs font-black uppercase tracking-[.18em] text-ari-coral">Explora por mundos</span>
|
||||||
<h2 className="mt-2 text-4xl font-black tracking-tight sm:text-5xl">Encuentra tu próximo tesoro</h2>
|
<h2 className="mt-2 text-4xl font-black tracking-tight sm:text-5xl">Encuentra tu próximo tesoro</h2>
|
||||||
</div>
|
</div>
|
||||||
<Link href="/catalog" className="hidden font-black text-cyan-700 sm:block">Ver todo →</Link>
|
<Link href="/catalog" className="hidden font-black text-ari-marino sm:block">Ver todo →</Link>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
||||||
{roots.map((category) => (
|
{roots.map((category) => (
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import Image from "next/image";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { ArrowRight, BadgePercent, Sparkles } from "lucide-react";
|
|
||||||
import { motion, useReducedMotion } from "motion/react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
|
|
||||||
export function HeroBento() {
|
|
||||||
const reduceMotion = useReducedMotion();
|
|
||||||
const initial = reduceMotion ? false : { opacity: 0, y: 20 };
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className="mx-auto max-w-7xl px-4 py-7 lg:py-10">
|
|
||||||
<div className="grid gap-5 lg:grid-cols-[1.55fr_.8fr]">
|
|
||||||
<motion.article initial={initial} animate={{ opacity: 1, y: 0 }} className="grid min-h-[470px] overflow-hidden rounded-[2rem] bg-fuchsia-500 text-white shadow-2xl lg:min-h-[560px] lg:grid-cols-[.82fr_1.18fr]">
|
|
||||||
<div className="relative z-10 flex flex-col justify-center bg-gradient-to-br from-fuchsia-600 via-pink-500 to-rose-500 p-7 lg:p-11">
|
|
||||||
<div className="mb-5 inline-flex w-fit items-center gap-2 rounded-full bg-yellow-300 px-4 py-2 text-xs font-black uppercase tracking-wider text-slate-950"><Sparkles className="size-4" />Celebración ARI</div>
|
|
||||||
<h1 className="text-5xl font-black leading-[.92] tracking-[-.06em] sm:text-6xl lg:text-7xl"><span className="block">Hasta</span><span className="text-yellow-300">50% OFF</span><span className="mt-3 block text-3xl tracking-tight sm:text-4xl">en tesoros seleccionados</span></h1>
|
|
||||||
<p className="mt-6 max-w-md text-base font-semibold text-white/95 sm:text-lg">Personajes, mochilas y regalos que convierten cualquier día en una celebración.</p>
|
|
||||||
<Button asChild variant="yellow" size="lg" className="mt-8 w-fit"><Link href="/catalog">Comprar ahora <ArrowRight className="size-5" /></Link></Button>
|
|
||||||
</div>
|
|
||||||
<div className="relative min-h-[360px] bg-white lg:min-h-full">
|
|
||||||
<Image src="/images/promo/hero-vibrant.webp" alt="Promoción principal de Ari Shopping" fill priority sizes="(max-width: 1024px) 100vw, 42vw" className="object-cover object-center" />
|
|
||||||
</div>
|
|
||||||
</motion.article>
|
|
||||||
|
|
||||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-1">
|
|
||||||
<motion.article initial={reduceMotion ? false : { opacity: 0, x: 18 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: .08 }} className="grid min-h-60 overflow-hidden rounded-[2rem] bg-red-600 text-white shadow-xl sm:grid-cols-[.9fr_1.1fr] lg:min-h-0">
|
|
||||||
<div className="relative z-10 flex flex-col justify-center bg-gradient-to-br from-red-600 to-rose-700 p-6"><span className="text-xs font-black uppercase tracking-wider text-yellow-300">Héroes favoritos</span><h2 className="mt-2 text-3xl font-black leading-none">Acción y aventura</h2><Button asChild variant="yellow" size="sm" className="mt-5 w-fit"><Link href="/catalog?collection=Marvel">Comprar ahora</Link></Button></div>
|
|
||||||
<div className="relative min-h-56 bg-white"><Image src="/images/promo/promo-marvel.webp" alt="Colección Marvel" fill sizes="(max-width: 1024px) 50vw, 18vw" className="object-cover object-center" /></div>
|
|
||||||
</motion.article>
|
|
||||||
|
|
||||||
<motion.article initial={reduceMotion ? false : { opacity: 0, x: 18 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: .14 }} className="grid min-h-60 overflow-hidden rounded-[2rem] bg-violet-600 text-white shadow-xl sm:grid-cols-[.9fr_1.1fr] lg:min-h-0">
|
|
||||||
<div className="relative z-10 flex flex-col justify-center bg-gradient-to-br from-violet-600 to-cyan-600 p-6"><div className="inline-flex w-fit items-center gap-1 rounded-full bg-white px-3 py-1 text-xs font-black text-fuchsia-600"><BadgePercent className="size-4" />Novedad</div><h2 className="mt-3 text-3xl font-black leading-none">Tesoros para regalar</h2><Button asChild variant="outline" size="sm" className="mt-5 w-fit border-white bg-white"><Link href="/catalog">Descubrir</Link></Button></div>
|
|
||||||
<div className="relative min-h-56 bg-white"><Image src="/images/promo/promo-characters.webp" alt="Personajes y peluches" fill sizes="(max-width: 1024px) 50vw, 18vw" className="object-cover object-center" /></div>
|
|
||||||
</motion.article>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ArrowRight, BadgePercent, Sparkles } from "lucide-react";
|
||||||
|
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
// ADR 0008 sub-fase 4: hero azul con dots de paginacion (carrusel), en vez
|
||||||
|
// del bento estatico de 3 tarjetas en fucsia/rojo/violeta del esquema
|
||||||
|
// arcoiris original. Un slide a la vez, fondo azul de marca en los tres,
|
||||||
|
// para leerse como una sola pieza de marca en vez de 3 bloques de colores
|
||||||
|
// distintos.
|
||||||
|
const slides = [
|
||||||
|
{
|
||||||
|
id: "celebracion",
|
||||||
|
badge: "Celebración ARI",
|
||||||
|
icon: Sparkles,
|
||||||
|
title: "Hasta 50% OFF",
|
||||||
|
subtitle: "en tesoros seleccionados",
|
||||||
|
description: "Personajes, mochilas y regalos que convierten cualquier día en una celebración.",
|
||||||
|
href: "/catalog",
|
||||||
|
image: "/images/promo/hero-vibrant.webp",
|
||||||
|
imageAlt: "Promoción principal de Ari Shopping",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "marvel",
|
||||||
|
badge: "Héroes favoritos",
|
||||||
|
icon: BadgePercent,
|
||||||
|
title: "Acción y aventura",
|
||||||
|
subtitle: "colección Marvel",
|
||||||
|
description: "Figuras, mochilas y sets listos para la próxima misión.",
|
||||||
|
href: "/catalog?collection=Marvel",
|
||||||
|
image: "/images/promo/promo-marvel.webp",
|
||||||
|
imageAlt: "Colección Marvel",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "regalos",
|
||||||
|
badge: "Novedad",
|
||||||
|
icon: Sparkles,
|
||||||
|
title: "Tesoros para regalar",
|
||||||
|
subtitle: "",
|
||||||
|
description: "Personajes y peluches para sorprender en cualquier ocasión.",
|
||||||
|
href: "/catalog",
|
||||||
|
image: "/images/promo/promo-characters.webp",
|
||||||
|
imageAlt: "Personajes y peluches",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const AUTOPLAY_MS = 6000;
|
||||||
|
|
||||||
|
export function HeroCarousel() {
|
||||||
|
const reduceMotion = useReducedMotion();
|
||||||
|
const [index, setIndex] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (reduceMotion) return;
|
||||||
|
const timer = setInterval(() => setIndex((current) => (current + 1) % slides.length), AUTOPLAY_MS);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [reduceMotion]);
|
||||||
|
|
||||||
|
const slide = slides[index];
|
||||||
|
if (!slide) return null;
|
||||||
|
const Icon = slide.icon;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="mx-auto max-w-7xl px-4 py-7 lg:py-10">
|
||||||
|
<div className="relative overflow-hidden rounded-[2rem] bg-ari-marino text-white shadow-2xl">
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
<motion.article
|
||||||
|
key={slide.id}
|
||||||
|
initial={reduceMotion ? false : { opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={reduceMotion ? undefined : { opacity: 0 }}
|
||||||
|
transition={{ duration: 0.4 }}
|
||||||
|
className="grid min-h-[420px] lg:min-h-[500px] lg:grid-cols-2"
|
||||||
|
>
|
||||||
|
<div className="relative z-10 flex flex-col justify-center p-7 lg:p-14">
|
||||||
|
<div className="mb-5 inline-flex w-fit items-center gap-2 rounded-full bg-ari-coral-claro px-4 py-2 text-xs font-black uppercase tracking-wider text-ari-marino">
|
||||||
|
<Icon className="size-4" />
|
||||||
|
{slide.badge}
|
||||||
|
</div>
|
||||||
|
<h1 className="text-5xl font-black leading-[.95] tracking-[-.04em] sm:text-6xl">{slide.title}</h1>
|
||||||
|
{slide.subtitle && <p className="mt-2 text-2xl font-bold text-ari-coral-claro">{slide.subtitle}</p>}
|
||||||
|
<p className="mt-6 max-w-md text-base font-semibold text-white/90 sm:text-lg">{slide.description}</p>
|
||||||
|
<Button asChild variant="yellow" size="lg" className="mt-8 w-fit">
|
||||||
|
<Link href={slide.href}>
|
||||||
|
Comprar ahora <ArrowRight className="size-5" />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="relative min-h-[280px] bg-white lg:min-h-full">
|
||||||
|
<Image src={slide.image} alt={slide.imageAlt} fill priority={index === 0} sizes="(max-width: 1024px) 100vw, 50vw" className="object-cover object-center" />
|
||||||
|
</div>
|
||||||
|
</motion.article>
|
||||||
|
</AnimatePresence>
|
||||||
|
|
||||||
|
<div className="absolute inset-x-0 bottom-5 z-20 flex justify-center gap-2">
|
||||||
|
{slides.map((item, itemIndex) => (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
aria-label={`Ir a la diapositiva ${itemIndex + 1}: ${item.badge}`}
|
||||||
|
aria-current={itemIndex === index ? "true" : undefined}
|
||||||
|
onClick={() => setIndex(itemIndex)}
|
||||||
|
className={`h-2.5 rounded-full transition-all ${itemIndex === index ? "w-7 bg-ari-coral-claro" : "w-2.5 bg-white/50 hover:bg-white/80"}`}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -52,9 +52,13 @@ export function Navbar({ products, categories }: { products: Product[]; categori
|
|||||||
<div className="relative overflow-visible bg-white">
|
<div className="relative overflow-visible bg-white">
|
||||||
<div className="pointer-events-none absolute inset-x-0 top-0 h-1 bg-ari-coral-claro" />
|
<div className="pointer-events-none absolute inset-x-0 top-0 h-1 bg-ari-coral-claro" />
|
||||||
<div className="mx-auto grid max-w-7xl grid-cols-[auto_1fr_auto] items-center gap-4 px-4 py-4 lg:gap-8">
|
<div className="mx-auto grid max-w-7xl grid-cols-[auto_1fr_auto] items-center gap-4 px-4 py-4 lg:gap-8">
|
||||||
|
{/* Isotipo circular con icono + wordmark integrados (como en la
|
||||||
|
version previa a ADR 0008), pedido explicito del usuario en
|
||||||
|
vez del lockup rectangular. logo-ari.svg (rectangular) se
|
||||||
|
mantiene para el footer. */}
|
||||||
<Link href="/" aria-label="ARI shopping" className="shrink-0">
|
<Link href="/" aria-label="ARI shopping" className="shrink-0">
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element -- vector propio, next/image no optimiza SVG sin habilitar dangerouslyAllowSVG */}
|
{/* eslint-disable-next-line @next/next/no-img-element -- vector propio, next/image no optimiza SVG sin habilitar dangerouslyAllowSVG */}
|
||||||
<img src="/images/brand/logo-ari.svg" alt="ARI shopping" className="h-11 w-auto lg:h-14" width={200} height={64} />
|
<img src="/images/brand/logo-ari-circular.svg" alt="ARI shopping" className="size-16 lg:size-20" width={200} height={200} />
|
||||||
</Link>
|
</Link>
|
||||||
<PredictiveSearch />
|
<PredictiveSearch />
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|||||||
@@ -18,5 +18,5 @@ export function ProductPurchase({ product }: { product: Product }) {
|
|||||||
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
||||||
? selectedVariant.inventoryQuantity
|
? selectedVariant.inventoryQuantity
|
||||||
: null;
|
: null;
|
||||||
return <div><div className="mb-5 flex flex-wrap gap-2">{product.variants.map((variant) => <button key={variant.id} onClick={() => setVariantId(variant.id)} className={`rounded-full border px-4 py-2 text-sm font-bold ${variantId === variant.id ? "border-fuchsia-500 bg-fuchsia-50 text-fuchsia-700" : "border-slate-200"}`}>{variant.value}</button>)}</div><div className="mb-6 flex items-end gap-3"><strong className="text-3xl font-black">{formatMoney(product.price, product.currency)}</strong>{product.compareAtPrice && <del className="text-slate-400">{formatMoney(product.compareAtPrice, product.currency)}</del>}</div><Button variant="primary" size="lg" className="w-full" onClick={() => addItem(product, variantId)}><ShoppingBag />Añadir al carrito</Button><div className="mt-5 grid gap-3 rounded-2xl bg-slate-50 p-4 text-sm">{lowStock !== null ? <span className="flex items-center gap-2 font-bold text-amber-600"><TriangleAlert className="size-4" />Quedan {lowStock} unidades</span> : <span className="flex items-center gap-2 font-bold"><CheckCircle2 className="size-4 text-emerald-500" />Disponibilidad por confirmar</span>}<span className="flex items-center gap-2 font-bold"><Truck className="size-4 text-cyan-600" />Envíos nacionales</span></div></div>;
|
return <div><div className="mb-5 flex flex-wrap gap-2">{product.variants.map((variant) => <button key={variant.id} onClick={() => setVariantId(variant.id)} className={`rounded-full border px-4 py-2 text-sm font-bold ${variantId === variant.id ? "border-ari-marino bg-ari-marino text-white" : "border-slate-200"}`}>{variant.value}</button>)}</div><div className="mb-6 flex items-end gap-3"><strong className="text-3xl font-black">{formatMoney(product.price, product.currency)}</strong>{product.compareAtPrice && <del className="text-slate-400">{formatMoney(product.compareAtPrice, product.currency)}</del>}</div>{/* oculto en mobile: MobileAddToCart (barra fija abajo, lg:hidden) ya cubre esa misma accion ahi -- sin el hidden aqui, ambos se mostraban a la vez. */}<Button variant="primary" size="lg" className="hidden w-full lg:inline-flex" onClick={() => addItem(product, variantId)}><ShoppingBag />Añadir al carrito</Button><div className="mt-5 grid gap-3 rounded-2xl bg-slate-50 p-4 text-sm">{lowStock !== null ? <span className="flex items-center gap-2 font-bold text-amber-600"><TriangleAlert className="size-4" />Quedan {lowStock} unidades</span> : <span className="flex items-center gap-2 font-bold"><CheckCircle2 className="size-4 text-emerald-500" />Disponibilidad por confirmar</span>}<span className="flex items-center gap-2 font-bold"><Truck className="size-4 text-cyan-600" />Envíos nacionales</span></div></div>;
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ import Link from "next/link";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Search, X } from "lucide-react";
|
import { Search, X } from "lucide-react";
|
||||||
import { FormEvent, useEffect, useState } from "react";
|
import { FormEvent, useEffect, useState } from "react";
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import type { Product } from "@/lib/headless/types";
|
import type { Product } from "@/lib/headless/types";
|
||||||
|
|
||||||
export function PredictiveSearch() {
|
export function PredictiveSearch() {
|
||||||
@@ -54,12 +53,34 @@ export function PredictiveSearch() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={submit} className="relative w-full">
|
<form onSubmit={submit} className="relative w-full">
|
||||||
<div className="rounded-full bg-gradient-to-r from-cyan-400 via-violet-500 to-fuchsia-500 p-[2px] shadow-lg shadow-violet-500/10">
|
<div className="flex items-center rounded-full border-2 border-slate-200 bg-white pl-5 pr-1.5 shadow-sm transition focus-within:border-ari-marino focus-within:ring-4 focus-within:ring-ari-coral-claro/30">
|
||||||
<div className="relative rounded-full bg-white">
|
{/* input propio (no el <Input> compartido) -- ese componente trae su
|
||||||
<Search className="pointer-events-none absolute left-5 top-1/2 z-10 size-5 -translate-y-1/2 text-violet-600" />
|
propio focus:ring-4 focus:ring-cyan-300/30 hardcodeado que no se
|
||||||
<Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Busca juguetes, mochilas, personajes…" className="h-[52px] border-0 bg-transparent pl-[52px] pr-12 shadow-none focus-visible:ring-violet-300/30" />
|
anulaba de forma confiable via tailwind-merge dentro de este
|
||||||
{query && <button type="button" aria-label="Limpiar búsqueda" className="absolute right-4 top-1/2 -translate-y-1/2 rounded-full p-1 text-slate-400 hover:bg-slate-100" onClick={() => setQuery("")}><X className="size-4" /></button>}
|
contenedor compuesto (input + boton circular), causando un
|
||||||
</div>
|
segundo ring visible al hacer foco. Mas simple y robusto no
|
||||||
|
heredar clases de foco que hay que pelear despues.
|
||||||
|
|
||||||
|
focus-visible:outline-none (no outline-none a secas): globals.css
|
||||||
|
define un outline de accesibilidad global por teclado
|
||||||
|
(input:focus-visible, azul de marca) que le gana en
|
||||||
|
especificidad a un outline-none plano. El wrapper de este
|
||||||
|
componente ya tiene su propio indicador de foco visible
|
||||||
|
(focus-within:border-ari-marino + ring amarillo, mismo patron
|
||||||
|
que button.tsx) que cumple el mismo proposito de accesibilidad
|
||||||
|
sin duplicarlo -- variante focus-visible: en vez de la base
|
||||||
|
iguala la especificidad de la regla global (mismo truco que ya
|
||||||
|
usa button.tsx) y evita el doble indicador de foco. */}
|
||||||
|
<input
|
||||||
|
value={query}
|
||||||
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
|
placeholder="Busca juguetes, mochilas, personajes…"
|
||||||
|
className="h-[48px] w-full border-0 bg-transparent p-0 text-sm text-slate-950 focus-visible:outline-none"
|
||||||
|
/>
|
||||||
|
{query && <button type="button" aria-label="Limpiar búsqueda" className="mr-1 shrink-0 rounded-full p-1.5 text-slate-400 hover:bg-slate-100" onClick={() => setQuery("")}><X className="size-4" /></button>}
|
||||||
|
<button type="submit" aria-label="Buscar" className="grid size-10 shrink-0 place-items-center rounded-full bg-ari-marino text-white transition hover:brightness-110">
|
||||||
|
<Search className="size-4.5" />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{loading && normalized.length >= 2 && matches.length === 0 && (
|
{loading && normalized.length >= 2 && matches.length === 0 && (
|
||||||
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 rounded-2xl border border-slate-200 bg-white p-4 text-center text-sm text-slate-500 shadow-2xl">
|
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 rounded-2xl border border-slate-200 bg-white p-4 text-center text-sm text-slate-500 shadow-2xl">
|
||||||
@@ -69,12 +90,12 @@ export function PredictiveSearch() {
|
|||||||
{matches.length > 0 && (
|
{matches.length > 0 && (
|
||||||
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 overflow-hidden rounded-2xl border border-slate-200 bg-white p-2 shadow-2xl">
|
<div className="absolute left-0 right-0 top-[calc(100%+10px)] z-50 overflow-hidden rounded-2xl border border-slate-200 bg-white p-2 shadow-2xl">
|
||||||
{matches.map((product) => (
|
{matches.map((product) => (
|
||||||
<Link key={product.id} href={`/product/${product.slug}`} prefetch={false} className="grid grid-cols-[54px_1fr] items-center gap-3 rounded-xl p-2 hover:bg-violet-50" onClick={() => setQuery("")}>
|
<Link key={product.id} href={`/product/${product.slug}`} prefetch={false} className="grid grid-cols-[54px_1fr] items-center gap-3 rounded-xl p-2 hover:bg-ari-marino/5" onClick={() => setQuery("")}>
|
||||||
<div className="relative aspect-square overflow-hidden rounded-lg bg-slate-100"><Image src={product.thumbnail} alt="" fill sizes="54px" className="object-cover" /></div>
|
<div className="relative aspect-square overflow-hidden rounded-lg bg-slate-100"><Image src={product.thumbnail} alt="" fill sizes="54px" className="object-cover" /></div>
|
||||||
<div><strong className="line-clamp-1 text-sm">{product.name}</strong><span className="text-xs text-slate-500">{product.category} · {product.collection}</span></div>
|
<div><strong className="line-clamp-1 text-sm">{product.name}</strong><span className="text-xs text-slate-500">{product.category} · {product.collection}</span></div>
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
<button type="submit" className="mt-1 w-full rounded-xl bg-slate-950 px-4 py-3 text-sm font-black text-white hover:bg-violet-700">Buscar “{query.trim()}” en todo el catálogo</button>
|
<button type="submit" className="mt-1 w-full rounded-xl bg-ari-marino px-4 py-3 text-sm font-black text-white hover:brightness-110">Buscar “{query.trim()}” en todo el catálogo</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsUser: 1001
|
runAsUser: 1001
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.185
|
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.204
|
||||||
env:
|
env:
|
||||||
- name: HEADLESS_PROVIDER
|
- name: HEADLESS_PROVIDER
|
||||||
value: medusa
|
value: medusa
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
// 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;
|
||||||
|
items: CartLine[];
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
type MedusaCart = {
|
||||||
|
id: string;
|
||||||
|
currency_code: string;
|
||||||
|
subtotal?: number | null;
|
||||||
|
items?: MedusaLineItem[] | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function mapCart(cart: MedusaCart): CartSummary {
|
||||||
|
return {
|
||||||
|
cartId: cart.id,
|
||||||
|
currency: cart.currency_code,
|
||||||
|
subtotal: 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",
|
||||||
|
// La linea del carrito no trae el arreglo de imagenes del producto,
|
||||||
|
// solo este campo (a veces null) -- mismo fallback final que ya usa
|
||||||
|
// mapProduct() en medusa.ts.
|
||||||
|
thumbnail: item.thumbnail || "/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();
|
||||||
|
}
|
||||||
|
|
||||||
|
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}`);
|
||||||
|
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`, {
|
||||||
|
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}`, {
|
||||||
|
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}`, {
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -42,6 +42,22 @@ const nextConfig: NextConfig = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
// Assets de marca (logo, favicon) cambian con cada iteracion de
|
||||||
|
// identidad visual, a diferencia de las fotos de producto -- el
|
||||||
|
// cache de 7 dias de la regla anterior dejaba servido el logo
|
||||||
|
// viejo en Cloudflare/navegador durante toda una semana despues de
|
||||||
|
// cada deploy (ver ADR 0008). Next.js aplica el ultimo header que
|
||||||
|
// matchee un mismo path, asi que esta regla, al ir despues,
|
||||||
|
// sobreescribe el Cache-Control solo para /images/brand/*.
|
||||||
|
{
|
||||||
|
source: "/images/brand/:path*",
|
||||||
|
headers: [
|
||||||
|
{
|
||||||
|
key: "Cache-Control",
|
||||||
|
value: "public, max-age=300, must-revalidate",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!-- ADR 0008, paleta "Azul & Amarillo". Isotipo circular (formato de la
|
||||||
|
version previa a ADR 0008, pedido explicito del usuario en vez del
|
||||||
|
lockup rectangular de logo-ari.svg): mariposa geometrica de 4 elipses
|
||||||
|
+ wordmark "ARI shopping", todo dentro del mismo circulo azul.
|
||||||
|
Ver docs-portal/docs/decisiones/0008-identidad-navy-coral.md -->
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="ARI shopping">
|
||||||
|
<circle cx="100" cy="100" r="98" fill="#0055B8"/>
|
||||||
|
<g transform="translate(100 68) scale(2.6) translate(-17 -11)">
|
||||||
|
<ellipse cx="10" cy="8" rx="9" ry="7" transform="rotate(-18 10 8)" fill="#FFC220"/>
|
||||||
|
<ellipse cx="24" cy="8" rx="9" ry="7" transform="rotate(18 24 8)" fill="#FFC220"/>
|
||||||
|
<ellipse cx="12" cy="16" rx="6" ry="5" transform="rotate(-10 12 16)" fill="#FFDD73"/>
|
||||||
|
<ellipse cx="22" cy="16" rx="6" ry="5" transform="rotate(10 22 16)" fill="#FFDD73"/>
|
||||||
|
<rect x="16" y="3" width="2" height="18" rx="1" fill="#0055B8"/>
|
||||||
|
</g>
|
||||||
|
<text x="100" y="132" text-anchor="middle" font-family="Poppins, ui-sans-serif, system-ui, sans-serif" font-weight="700" font-size="38" fill="#FFFFFF">ARI</text>
|
||||||
|
<text x="100" y="153" text-anchor="middle" font-family="Poppins, ui-sans-serif, system-ui, sans-serif" font-weight="700" font-size="14" letter-spacing="3" fill="#FFC220">shopping</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -2,60 +2,117 @@
|
|||||||
|
|
||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { createJSONStorage, persist } from "zustand/middleware";
|
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 {
|
// ADR 0009: carrito real conectado a un cart_id de Medusa (Store API,
|
||||||
product: Product;
|
// via /api/cart/*) en vez de estado 100% local -- precios y existencia
|
||||||
quantity: number;
|
// de linea son los que confirma el servidor, no un calculo optimista
|
||||||
variantId?: string;
|
// 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 {
|
interface CartState {
|
||||||
|
cartId: string | null;
|
||||||
items: CartItem[];
|
items: CartItem[];
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
hasHydrated: boolean;
|
hasHydrated: boolean;
|
||||||
openCart: () => void;
|
openCart: () => void;
|
||||||
closeCart: () => void;
|
closeCart: () => void;
|
||||||
setHasHydrated: (value: boolean) => void;
|
setHasHydrated: (value: boolean) => void;
|
||||||
addItem: (product: Product, variantId?: string) => void;
|
addItem: (product: { id: string }, variantId?: string) => Promise<void>;
|
||||||
removeItem: (productId: string) => void;
|
removeItem: (productId: string) => Promise<void>;
|
||||||
updateQuantity: (productId: string, quantity: number) => void;
|
updateQuantity: (productId: string, quantity: number) => Promise<void>;
|
||||||
clearCart: () => 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>()(
|
export const useCartStore = create<CartState>()(
|
||||||
persist(
|
persist(
|
||||||
(set) => ({
|
(set, get) => ({
|
||||||
|
cartId: null,
|
||||||
items: [],
|
items: [],
|
||||||
isOpen: false,
|
isOpen: false,
|
||||||
hasHydrated: false,
|
hasHydrated: false,
|
||||||
openCart: () => set({ isOpen: true }),
|
openCart: () => set({ isOpen: true }),
|
||||||
closeCart: () => set({ isOpen: false }),
|
closeCart: () => set({ isOpen: false }),
|
||||||
setHasHydrated: (value) => set({ hasHydrated: value }),
|
setHasHydrated: (value) => set({ hasHydrated: value }),
|
||||||
addItem: (product, variantId) => set((state) => {
|
|
||||||
const existing = state.items.find(
|
addItem: async (product, variantId) => {
|
||||||
(item) => item.product.id === product.id && item.variantId === 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
|
set({ items: [] });
|
||||||
? state.items.map((item) => item === existing ? { ...item, quantity: item.quantity + 1 } : item)
|
},
|
||||||
: [...state.items, { product, quantity: 1, variantId }];
|
|
||||||
return { items, isOpen: true };
|
// Al recargar la pagina, el cart_id guardado en localStorage puede
|
||||||
}),
|
// llevar dias -- se refresca contra el servidor en vez de confiar en
|
||||||
removeItem: (productId) => set((state) => ({
|
// el ultimo snapshot local (precios/stock pudieron cambiar).
|
||||||
items: state.items.filter((item) => item.product.id !== productId),
|
syncCart: async () => {
|
||||||
})),
|
const cartId = get().cartId;
|
||||||
updateQuantity: (productId, quantity) => set((state) => ({
|
if (!cartId) return;
|
||||||
items: quantity <= 0
|
try {
|
||||||
? state.items.filter((item) => item.product.id !== productId)
|
const response = await fetch(`/api/cart?cartId=${cartId}`);
|
||||||
: state.items.map((item) => item.product.id === productId ? { ...item, quantity } : item),
|
if (!response.ok) return;
|
||||||
})),
|
const cart = await response.json();
|
||||||
clearCart: () => set({ items: [] }),
|
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),
|
storage: createJSONStorage(() => localStorage),
|
||||||
partialize: (state) => ({ items: state.items }),
|
partialize: (state) => ({ cartId: state.cartId, items: state.items }),
|
||||||
onRehydrateStorage: () => (state) => state?.setHasHydrated(true),
|
onRehydrateStorage: () => (state) => {
|
||||||
|
state?.setHasHydrated(true);
|
||||||
|
void state?.syncCart();
|
||||||
|
},
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
Reference in new issue
Block a user