Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce4842f375 | ||
|
|
2cce671049 | ||
|
|
22f97ee12e | ||
|
|
42c90d8534 | ||
|
|
cd8d2edd8f | ||
|
|
77389aea19 | ||
|
|
7ce11ecbb4 | ||
|
|
da10a4b688 | ||
|
|
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 | ||
|
|
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 | ||
|
|
72a2715502 | ||
|
|
1ed06edbdd | ||
|
|
ffcadc5dca | ||
|
|
61c57fbf28 | ||
|
|
a31a0d96b6 | ||
|
|
ba2b290523 | ||
|
|
cf9d642764 | ||
|
|
48ef980910 | ||
|
|
53b65965f3 | ||
|
|
77044130aa | ||
|
|
2b3768bfb4 | ||
|
|
c9e8641bfb | ||
|
|
99ddebcc8d | ||
|
|
d3745c8617 | ||
|
|
b123a5a9c9 | ||
|
|
b5c2c36749 | ||
|
|
f147f4c42c | ||
|
|
d44ef5c35e |
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
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import Medusa from "@medusajs/js-sdk";
|
||||
|
||||
// baseUrl "/" -- esta pagina se sirve dentro del mismo dashboard admin
|
||||
// (mismo origen que la API), no hace falta apuntar a otra URL. auth
|
||||
// "session" reusa la cookie de sesion ya autenticada del dashboard.
|
||||
export const sdk = new Medusa({
|
||||
baseUrl: "/",
|
||||
auth: { type: "session" },
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { defineRouteConfig } from "@medusajs/admin-sdk";
|
||||
import { Buildings } from "@medusajs/icons";
|
||||
import { Badge, Button, Checkbox, Container, Heading, Input, Switch, Text, toast } from "@medusajs/ui";
|
||||
import { useEffect, useState } from "react";
|
||||
import { sdk } from "../../lib/sdk";
|
||||
|
||||
// Panel simplificado para alguien no tecnico (la esposa del dueno del
|
||||
// negocio) -- una fila por producto (este catalogo es 1 variante por
|
||||
// producto, confirmado en vivo), switch para activar seguimiento de
|
||||
// stock y un input de cantidad que guarda solo. La vista nativa de
|
||||
// Medusa Admin (Inventory) sigue disponible para el dueno, esto no la
|
||||
// reemplaza, es un atajo.
|
||||
|
||||
const LOW_STOCK_THRESHOLD = 5;
|
||||
|
||||
type Row = {
|
||||
productId: string;
|
||||
variantId: string | null;
|
||||
title: string;
|
||||
thumbnail: string | null;
|
||||
sku: string | null;
|
||||
managed: boolean;
|
||||
quantity: number;
|
||||
};
|
||||
|
||||
async function fetchRows(): Promise<Row[]> {
|
||||
const data = await sdk.client.fetch<{ rows: Row[] }>("/admin/inventory-panel");
|
||||
return data.rows;
|
||||
}
|
||||
|
||||
async function saveRow(row: { productId: string; variantId: string; managed?: boolean; quantity?: number }) {
|
||||
await sdk.client.fetch("/admin/inventory-panel", { method: "post", body: row });
|
||||
}
|
||||
|
||||
const InventoryPanel = () => {
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [savingId, setSavingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchRows().then((data) => {
|
||||
setRows(data);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
function toggleSelected(productId: string, checked: boolean) {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (checked) next.add(productId);
|
||||
else next.delete(productId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function updateManaged(row: Row, managed: boolean) {
|
||||
if (!row.variantId) return;
|
||||
setSavingId(row.productId);
|
||||
try {
|
||||
await saveRow({ productId: row.productId, variantId: row.variantId, managed });
|
||||
setRows((prev) =>
|
||||
prev.map((r) => (r.productId === row.productId ? { ...r, managed } : r)),
|
||||
);
|
||||
} catch {
|
||||
toast.error("No se pudo guardar", { description: row.title });
|
||||
} finally {
|
||||
setSavingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateQuantity(row: Row, quantity: number) {
|
||||
if (!row.variantId || Number.isNaN(quantity) || quantity < 0) return;
|
||||
setSavingId(row.productId);
|
||||
try {
|
||||
await saveRow({ productId: row.productId, variantId: row.variantId, quantity });
|
||||
setRows((prev) =>
|
||||
prev.map((r) => (r.productId === row.productId ? { ...r, quantity } : r)),
|
||||
);
|
||||
toast.success("Stock actualizado", { description: row.title });
|
||||
} catch {
|
||||
toast.error("No se pudo guardar", { description: row.title });
|
||||
} finally {
|
||||
setSavingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkSetManaged(managed: boolean) {
|
||||
const targets = rows.filter((r) => selected.has(r.productId) && r.variantId);
|
||||
for (const row of targets) {
|
||||
await updateManaged(row, managed);
|
||||
}
|
||||
setSelected(new Set());
|
||||
}
|
||||
|
||||
return (
|
||||
<Container className="divide-y p-0">
|
||||
<div className="flex items-center justify-between px-6 py-4">
|
||||
<div>
|
||||
<Heading level="h2">Inventario</Heading>
|
||||
<Text size="small" className="text-ui-fg-subtle">
|
||||
Activa el seguimiento de stock y ajusta la cantidad disponible por producto.
|
||||
</Text>
|
||||
</div>
|
||||
{selected.size > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="small" variant="secondary" onClick={() => bulkSetManaged(true)}>
|
||||
Activar seguimiento ({selected.size})
|
||||
</Button>
|
||||
<Button size="small" variant="secondary" onClick={() => bulkSetManaged(false)}>
|
||||
Desactivar seguimiento
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="px-6 py-8">
|
||||
<Text className="text-ui-fg-subtle">Cargando…</Text>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b text-left text-ui-fg-subtle">
|
||||
<th className="w-10 px-6 py-3" />
|
||||
<th className="px-3 py-3 font-medium">Producto</th>
|
||||
<th className="px-3 py-3 font-medium">SKU</th>
|
||||
<th className="px-3 py-3 font-medium">Trackear stock</th>
|
||||
<th className="px-3 py-3 font-medium">Cantidad disponible</th>
|
||||
<th className="px-3 py-3 font-medium" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.productId} className="border-b last:border-0">
|
||||
<td className="px-6 py-3">
|
||||
<Checkbox
|
||||
checked={selected.has(row.productId)}
|
||||
onCheckedChange={(checked) => toggleSelected(row.productId, checked === true)}
|
||||
/>
|
||||
</td>
|
||||
<td className="flex items-center gap-3 px-3 py-3">
|
||||
{row.thumbnail ? (
|
||||
<img src={row.thumbnail} alt="" className="size-8 rounded object-cover" />
|
||||
) : (
|
||||
<div className="size-8 rounded bg-ui-bg-subtle" />
|
||||
)}
|
||||
<Text>{row.title}</Text>
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<Text className="text-ui-fg-subtle">{row.sku ?? "—"}</Text>
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<Switch
|
||||
checked={row.managed}
|
||||
disabled={savingId === row.productId}
|
||||
onCheckedChange={(checked) => updateManaged(row, checked)}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
defaultValue={row.quantity}
|
||||
disabled={!row.managed || savingId === row.productId}
|
||||
className="w-24"
|
||||
onBlur={(event) => {
|
||||
const value = Number(event.target.value);
|
||||
if (value !== row.quantity) updateQuantity(row, value);
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
{row.managed && row.quantity <= LOW_STOCK_THRESHOLD && (
|
||||
<Badge color="red">Stock bajo</Badge>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export const config = defineRouteConfig({
|
||||
label: "Inventario",
|
||||
icon: Buildings,
|
||||
});
|
||||
|
||||
export default InventoryPanel;
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
|
||||
import {
|
||||
createInventoryItemsWorkflow,
|
||||
updateInventoryLevelsWorkflow,
|
||||
updateProductVariantsWorkflow,
|
||||
} from "@medusajs/medusa/core-flows";
|
||||
import { attachInventoryItemToVariantWorkflow } from "../../../workflows/attach-inventory-item-to-variant";
|
||||
|
||||
// Panel simplificado de inventario (pensado para un usuario no tecnico,
|
||||
// no reemplaza la vista nativa de Medusa Admin -- ver ADR/memoria del
|
||||
// bug de Firefox Android, tema aparte). Un producto = una variante en
|
||||
// este catalogo real (confirmado en vivo contra /store/products antes
|
||||
// de asumirlo), asi que la tabla trabaja a nivel de producto.
|
||||
|
||||
const PRODUCT_FIELDS = [
|
||||
"id",
|
||||
"title",
|
||||
"thumbnail",
|
||||
"status",
|
||||
"variants.id",
|
||||
"variants.sku",
|
||||
"variants.manage_inventory",
|
||||
"variants.inventory_items.inventory_item_id",
|
||||
"variants.inventory_items.inventory.location_levels.id",
|
||||
"variants.inventory_items.inventory.location_levels.location_id",
|
||||
"variants.inventory_items.inventory.location_levels.stocked_quantity",
|
||||
];
|
||||
|
||||
async function defaultLocationId(req: MedusaRequest): Promise<string | null> {
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||
const { data: locations = [] } = await query.graph({
|
||||
entity: "stock_location",
|
||||
fields: ["id"],
|
||||
});
|
||||
return locations[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||
const locationId = await defaultLocationId(req);
|
||||
|
||||
const { data: products = [] } = await query.graph({
|
||||
entity: "product",
|
||||
fields: PRODUCT_FIELDS,
|
||||
});
|
||||
|
||||
const rows = products.map((product) => {
|
||||
const variant = product.variants?.[0];
|
||||
const inventoryItem = variant?.inventory_items?.[0];
|
||||
const level = inventoryItem?.inventory?.location_levels?.find(
|
||||
(candidate) => candidate?.location_id === locationId,
|
||||
);
|
||||
return {
|
||||
productId: product.id,
|
||||
variantId: variant?.id ?? null,
|
||||
title: product.title,
|
||||
thumbnail: product.thumbnail,
|
||||
status: product.status,
|
||||
sku: variant?.sku ?? null,
|
||||
managed: variant?.manage_inventory ?? false,
|
||||
quantity: level?.stocked_quantity ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
res.json({ rows, locationId });
|
||||
}
|
||||
|
||||
type PanelUpdateBody = {
|
||||
productId: string;
|
||||
variantId: string;
|
||||
managed?: boolean;
|
||||
quantity?: number;
|
||||
};
|
||||
|
||||
export async function POST(req: MedusaRequest<PanelUpdateBody>, res: MedusaResponse) {
|
||||
const { productId, variantId, managed, quantity } = req.body;
|
||||
if (!productId || !variantId) {
|
||||
res.status(400).json({ error: "productId y variantId son obligatorios" });
|
||||
return;
|
||||
}
|
||||
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
|
||||
const locationId = await defaultLocationId(req);
|
||||
if (!locationId) {
|
||||
res.status(400).json({ error: "No hay una bodega (stock location) configurada" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: products = [] } = await query.graph({
|
||||
entity: "product",
|
||||
fields: PRODUCT_FIELDS,
|
||||
filters: { id: productId },
|
||||
});
|
||||
const variant = products[0]?.variants?.find((v: { id: string }) => v.id === variantId);
|
||||
const inventoryItem = variant?.inventory_items?.[0];
|
||||
let inventoryItemId: string | undefined = inventoryItem?.inventory_item_id;
|
||||
|
||||
if (managed === true && !inventoryItemId) {
|
||||
// Primera vez que se activa el seguimiento para esta variante -- no
|
||||
// trae InventoryItem todavia (confirmado en vivo: togglear
|
||||
// manage_inventory=true en una variante existente NO crea uno solo,
|
||||
// a diferencia de crear un producto nuevo con manage_inventory
|
||||
// desde el inicio). Se crea con el nivel de stock inicial y se
|
||||
// vincula aparte.
|
||||
const { result: items } = await createInventoryItemsWorkflow(req.scope).run({
|
||||
input: {
|
||||
items: [
|
||||
{
|
||||
title: variant?.sku ? undefined : products[0]?.title,
|
||||
sku: variant?.sku ?? undefined,
|
||||
location_levels: [{ location_id: locationId, stocked_quantity: quantity ?? 0 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
inventoryItemId = items[0]?.id;
|
||||
if (inventoryItemId) {
|
||||
await attachInventoryItemToVariantWorkflow(req.scope).run({
|
||||
input: { inventoryItemId, variantId },
|
||||
});
|
||||
}
|
||||
await updateProductVariantsWorkflow(req.scope).run({
|
||||
input: { product_variants: [{ id: variantId, manage_inventory: true }] },
|
||||
});
|
||||
} else {
|
||||
if (typeof managed === "boolean") {
|
||||
await updateProductVariantsWorkflow(req.scope).run({
|
||||
input: { product_variants: [{ id: variantId, manage_inventory: managed }] },
|
||||
});
|
||||
}
|
||||
if (typeof quantity === "number" && inventoryItemId) {
|
||||
const level = inventoryItem?.inventory?.location_levels?.find(
|
||||
(candidate) => candidate?.location_id === locationId,
|
||||
);
|
||||
await updateInventoryLevelsWorkflow(req.scope).run({
|
||||
input: {
|
||||
updates: [
|
||||
{
|
||||
id: level?.id,
|
||||
inventory_item_id: inventoryItemId,
|
||||
location_id: locationId,
|
||||
stocked_quantity: quantity,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk";
|
||||
import { attachInventoryItemToVariants } from "@medusajs/medusa/core-flows";
|
||||
|
||||
// attachInventoryItemToVariants es un step suelto (no un workflow
|
||||
// exportado) -- confirmado leyendo el .js real instalado
|
||||
// (@medusajs/core-flows/dist/inventory/steps/attach-inventory-items.js):
|
||||
// internamente resuelve ContainerRegistrationKeys.LINK y crea el link
|
||||
// Product<->Inventory. El campo "tag" del input es el variant_id (nombre
|
||||
// generico del step, no documentado con ese detalle).
|
||||
type Input = { inventoryItemId: string; variantId: string };
|
||||
|
||||
export const attachInventoryItemToVariantWorkflow = createWorkflow(
|
||||
"attach-inventory-item-to-variant",
|
||||
(input: Input) => {
|
||||
return new WorkflowResponse(
|
||||
attachInventoryItemToVariants([
|
||||
{ inventoryItemId: input.inventoryItemId, tag: input.variantId },
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,225 @@
|
||||
# Sesión persistente de Claude Code (tmux en Docker)
|
||||
|
||||
## Problema que resuelve
|
||||
|
||||
Correr Claude Code directo en una shell SSH sobre el NAS lo ata al
|
||||
ciclo de vida de esa conexión: un corte de red, cambiar de laptop a
|
||||
tablet, o cerrar la terminal por accidente mata el proceso y con él
|
||||
todo el contexto de trabajo en curso — no hay forma de "retomar
|
||||
donde quedó" porque el proceso ya no existe.
|
||||
|
||||
**Esto es un problema distinto al de los límites de uso/cuota de
|
||||
Claude Code.** Este setup no aumenta cuota de mensajes ni tokens —
|
||||
eso lo controla el backend de Anthropic sin importar dónde corra el
|
||||
CLI. Lo único que resuelve es que la *sesión de terminal* sobreviva
|
||||
a cortes de red o cambios de dispositivo; si la cuota se agota, sigue
|
||||
agotada exactamente igual dentro de este setup.
|
||||
|
||||
## Por qué Docker y no instalación nativa
|
||||
|
||||
ZimaOS no tiene gestor de paquetes tradicional utilizable para esto:
|
||||
`/` está montado como `squashfs` de solo lectura (imagen del SO
|
||||
inmutable), y `/usr` es un overlay de solo lectura sobre eso —
|
||||
`/usr/local/bin` ni siquiera existe y no se puede crear, tampoco como
|
||||
root (`mkdir` falla con "Read-only file system"). No hay dónde
|
||||
instalar Node.js, npm ni tmux directamente sobre el host.
|
||||
|
||||
Un contenedor Docker sortea esto por completo: tiene su propio
|
||||
filesystem de escritura (overlay2), independiente del `squashfs` del
|
||||
host — ahí es donde `npm install -g` deja el binario de `claude` sin
|
||||
tocar el host en absoluto. Lo único que el contenedor toma del host
|
||||
es lo que se monta explícitamente como volumen.
|
||||
|
||||
## Arquitectura
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
SSH["Cliente SSH<br/>(laptop / tablet / lo que sea)"] -->|docker exec| C["Contenedor tmux-host<br/>--network host, --restart unless-stopped"]
|
||||
C --> T["tmux server<br/>sesión 'lab'"]
|
||||
T --> CC["proceso claude<br/>(Claude Code)"]
|
||||
C -.->|bind mount| DATA["/DATA (host)<br/>repos y configs del lab"]
|
||||
C -.->|bind mount| SOCK["/var/run/docker.sock (host)<br/>control de Docker/k3d"]
|
||||
C -.->|bind mount| HOME["/DATA/AppData/k3d-lab-v3/claude-code-home (host)<br/>-> /root/.claude"]
|
||||
```
|
||||
|
||||
El contenedor sigue vivo aunque la conexión SSH se corte — es el
|
||||
servidor tmux, no la shell del cliente, el que sostiene el proceso de
|
||||
Claude Code. `--restart unless-stopped` además lo revive si el NAS
|
||||
reinicia.
|
||||
|
||||
## Contenedor: `tmux-host`
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name tmux-host \
|
||||
--restart unless-stopped \
|
||||
-v /DATA:/DATA \
|
||||
-v /media/HDD-Storage:/media/HDD-Storage \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home:/root/.claude \
|
||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home.json:/root/.claude.json \
|
||||
--network host \
|
||||
alpine sh -c "apk add --no-cache tmux docker-cli bash curl git kubectl nodejs npm && npm install -g @anthropic-ai/claude-code && git config --global --add safe.directory '*' && tail -f /dev/null"
|
||||
```
|
||||
|
||||
| Volumen | Destino | Por qué |
|
||||
|---|---|---|
|
||||
| `/DATA` | `/DATA` | Acceso a los repos (`apps-registry`, `platform-infra`, `scripts`) y configs del lab, mismos paths que en el host |
|
||||
| `/media/HDD-Storage` | `/media/HDD-Storage` | Ver "Gotcha: el symlink `/DATA/AppData`" abajo — sin esto, los repos no se ven dentro del contenedor pese a montar `/DATA` |
|
||||
| `/var/run/docker.sock` | `/var/run/docker.sock` | Seguir controlando Docker y k3d (contenedores, `k3d node`, etc.) desde dentro del contenedor |
|
||||
| `/DATA/AppData/k3d-lab-v3/claude-code-home` | `/root/.claude` | Persistir login/config de Claude Code — sobrevive no solo a un `docker restart`, sino a recrear el contenedor entero |
|
||||
| `/DATA/AppData/k3d-lab-v3/claude-code-home.json` | `/root/.claude.json` | Ver "Gotcha: la confianza del folder no persistía" abajo — es un archivo suelto, no vive dentro de `~/.claude/` |
|
||||
|
||||
## Gotcha: el symlink `/DATA/AppData`
|
||||
|
||||
Montar `-v /DATA:/DATA` **no alcanza** para ver los repos dentro del
|
||||
contenedor. `/DATA/AppData` en el host es un symlink *absoluto*:
|
||||
|
||||
```
|
||||
/DATA/AppData -> /media/HDD-Storage/AppData
|
||||
```
|
||||
|
||||
Los repos del lab (`lab-cruzcloud`) viven físicamente en el disco
|
||||
btrfs `/media/HDD-Storage`, no en el ext4 de `/DATA` — ZimaOS lo
|
||||
expone dentro de `/DATA` como submount (`/DATA/.media/HDD-Storage/...`,
|
||||
que sí viaja al contenedor porque Docker hace bind recursivo por
|
||||
defecto) pero el path "bonito" `/DATA/AppData/...` que usan `CLAUDE.md`
|
||||
y todos los scripts del lab llega ahí vía ese symlink absoluto, no vía
|
||||
el submount. Un symlink absoluto que apunta fuera del árbol montado
|
||||
queda roto dentro del contenedor aunque el submount subyacente esté
|
||||
perfectamente accesible por otra ruta.
|
||||
|
||||
**Cómo se detectó:** todo el trabajo de configuración inicial de este
|
||||
mismo setup se hizo con `git`/`docker exec` corriendo *en el host*, no
|
||||
dentro del contenedor — nadie había probado `cd
|
||||
/DATA/AppData/k3d-lab-v3/lab-cruzcloud` desde una sesión `lab` real
|
||||
hasta que se preguntó explícitamente por esto. `ls` devolvía "No such
|
||||
file or directory" pese a que el volumen de `/DATA` estaba montado y
|
||||
"andando".
|
||||
|
||||
**Fix:** montar también `-v /media/HDD-Storage:/media/HDD-Storage`,
|
||||
para que el symlink resuelva exactamente igual que en el host.
|
||||
|
||||
## Gotcha: git "dubious ownership" dentro del contenedor
|
||||
|
||||
Con el mount anterior ya arreglado, `git status`/`git log` dentro del
|
||||
contenedor fallan con:
|
||||
|
||||
```
|
||||
fatal: detected dubious ownership in repository at '/media/HDD-Storage/...'
|
||||
```
|
||||
|
||||
Los archivos en `/DATA`/`/media/HDD-Storage` pertenecen al usuario
|
||||
`devops` del host (via samba), pero los procesos dentro del
|
||||
contenedor corren como `root` (UID 0) — git, desde la versión que
|
||||
introdujo la protección CVE-2022-24765, rechaza operar sobre un repo
|
||||
cuyo dueño no coincide con el UID del proceso, a menos que el path
|
||||
esté explícitamente marcado como seguro.
|
||||
|
||||
**Fix:** `git config --global --add safe.directory '*'` dentro del
|
||||
contenedor. El wildcard (en vez de listar cada repo) es intencional
|
||||
acá: este contenedor ya tiene acceso root-equivalente al host vía el
|
||||
volumen de `/var/run/docker.sock`, así que restringir `safe.directory`
|
||||
por repo no suma aislamiento real.
|
||||
|
||||
**Por qué está en el comando de arranque y no como paso manual
|
||||
aparte:** igual que los paquetes `apk`, esta configuración vive en el
|
||||
filesystem efímero del contenedor (`/root/.gitconfig`, que no está
|
||||
bajo el volumen de `/root/.claude`) — se perdería si el contenedor se
|
||||
recrea. Ponerla en el `sh -c` de arranque la deja recreándose sola
|
||||
cada vez, sin pasos manuales que recordar.
|
||||
|
||||
## Gotcha: la confianza del folder no persistía
|
||||
|
||||
Al abrir `claude` por primera vez en un directorio, pide confirmar un
|
||||
diálogo de "¿confiás en este folder?" (más aún acá, porque este repo
|
||||
trae un `.claude/settings.local.json` con permisos pre-aprobados). Esa
|
||||
confirmación se guarda en `~/.claude.json` — un **archivo suelto en
|
||||
`/root`**, no dentro de la carpeta `~/.claude/` que ya estaba montada
|
||||
como volumen. Resultado: aunque el login (`~/.claude/.credentials.json`)
|
||||
sí persistía, el diálogo de confianza volvía a aparecer cada vez que
|
||||
se recreaba el contenedor — justo el tipo de "reconfigurar de nuevo"
|
||||
que este setup existe para evitar.
|
||||
|
||||
**Cómo se detectó:** al confirmar el diálogo por primera vez, se
|
||||
comparó `/root/.claude.json` dentro del contenedor contra sí mismo
|
||||
antes y después — mismo tamaño y mismo `mtime`, es decir, la
|
||||
confirmación en pantalla nunca se había registrado. La causa real:
|
||||
la primera vez se movió el selector con las flechas pero nunca se
|
||||
presionó Enter, así que en rigor el diálogo seguía sin confirmar; una
|
||||
vez confirmado *de verdad* (`tmux send-keys` moviendo el cursor a
|
||||
"Yes, I trust this folder" + Enter), el archivo saltó de 2.2 KB a
|
||||
40 KB y apareció la clave `projects` con la ruta del repo adentro.
|
||||
|
||||
**Fix:** copiar ese `.claude.json` ya confirmado a
|
||||
`/DATA/AppData/k3d-lab-v3/claude-code-home.json` en el host, y
|
||||
montarlo **archivo a archivo** (no como carpeta) en
|
||||
`-v .../claude-code-home.json:/root/.claude.json`. A diferencia de
|
||||
los demás volúmenes de este setup, este necesitó sembrarse con
|
||||
contenido real primero — un bind mount de archivo con un origen que
|
||||
no existe todavía en el host termina creando un directorio vacío en
|
||||
su lugar, no un archivo, y rompe el arranque del contenedor.
|
||||
Verificado en vivo: tras recrear el contenedor con este mount, `claude`
|
||||
arrancó directo en la sesión normal, sin volver a pedir el diálogo de
|
||||
confianza.
|
||||
|
||||
Sobre paquetes: alpine (imagen `alpine` sin pin de versión, la misma
|
||||
que uso este setup) sí trae `kubectl` en sus repos — no hizo falta
|
||||
cambiar de imagen base ni instalarlo por binario aparte, contrario a
|
||||
lo que se sospechaba inicialmente. `nodejs`/`npm` (v24/v11 al momento
|
||||
de escribir esto) también están en los repos de alpine y cumplen de
|
||||
sobra el mínimo que pide Claude Code.
|
||||
|
||||
**Nota sobre `--network host` + `docker.sock`:** el contenedor tiene,
|
||||
en la práctica, control equivalente a root sobre el NAS (puede lanzar
|
||||
cualquier otro contenedor con cualquier mount). Es una concesión
|
||||
deliberada — es exactamente lo que hace falta para seguir operando
|
||||
Docker/k3d desde dentro — no un descuido.
|
||||
|
||||
## Reconexión: un solo comando
|
||||
|
||||
```bash
|
||||
/media/HDD-Storage/AppData/k3d-lab-v3/lab-cruzcloud/scripts/lab-session.sh
|
||||
```
|
||||
|
||||
El script (`scripts/lab-session.sh`) es intencionalmente el mismo
|
||||
comando sin importar el estado previo:
|
||||
|
||||
```bash
|
||||
docker exec -it "$CONTAINER" tmux attach -t "$SESSION" || \
|
||||
docker exec -it "$CONTAINER" tmux new -s "$SESSION"
|
||||
```
|
||||
|
||||
Si la sesión `lab` existe, se adjunta a ella (mismo shell, mismo
|
||||
`claude` corriendo, mismo directorio de trabajo). Si no existe —por
|
||||
ejemplo justo después de que el contenedor se recreó desde cero— la
|
||||
crea. No hay que recordar cuál de los dos casos aplica.
|
||||
|
||||
## Qué sobrevive a qué
|
||||
|
||||
| Evento | ¿Sobrevive la sesión tmux (`lab`)? | ¿Sobrevive el login de Claude Code? |
|
||||
|---|---|---|
|
||||
| Corte de SSH / cerrar la terminal / cambiar de dispositivo | Sí — es exactamente el caso que este setup resuelve | Sí |
|
||||
| `docker restart tmux-host` (reinicio del NAS) | **No** — el proceso `tmux server` muere con el contenedor; `lab-session.sh` crea una sesión nueva automáticamente | Sí, vía el volumen montado en `/root/.claude` |
|
||||
| `docker rm` + recrear el contenedor desde cero | No | Sí, vía el mismo volumen — no hace falta volver a autenticar ni reconfirmar el diálogo de confianza del folder (ver el mount de `claude-code-home.json`) |
|
||||
|
||||
## Validación en vivo
|
||||
|
||||
Confirmado en este mismo lab (2026-08-27): se dejó una variable de
|
||||
entorno (`export MARCA_PERSISTENCIA=ok_<timestamp>`) corriendo dentro
|
||||
de la sesión `lab` vía `tmux send-keys`, y una invocación
|
||||
*completamente separada* de `docker exec` (equivalente a una nueva
|
||||
conexión) leyó de vuelta el mismo valor — confirma que el estado vive
|
||||
en el servidor tmux del contenedor, no en el cliente que se conecta.
|
||||
`claude --version` respondió `2.1.250` dentro de esa misma sesión, y
|
||||
un archivo de prueba escrito en `/root/.claude` dentro del contenedor
|
||||
apareció de inmediato en
|
||||
`/DATA/AppData/k3d-lab-v3/claude-code-home` en el host, confirmando
|
||||
el bind mount de credenciales.
|
||||
|
||||
Después de agregar el mount de `/media/HDD-Storage` y el
|
||||
`safe.directory`, se validó además: `md5sum` de `CLAUDE.md` idéntico
|
||||
leído desde el host y desde dentro del contenedor (vía el path con
|
||||
symlink `/DATA/AppData/...`), y `git log`/`git status` corriendo sin
|
||||
error sobre `apps-registry` y `scripts` desde una shell dentro de
|
||||
`tmux-host`.
|
||||
@@ -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.
|
||||
@@ -85,6 +85,7 @@ nav:
|
||||
- Red y exposición: arquitectura/red-y-exposicion.md
|
||||
- Flujo GitOps: arquitectura/gitops-flujo.md
|
||||
- Agente de monitoreo: arquitectura/agente-monitoreo.md
|
||||
- Sesión tmux persistente: arquitectura/sesion-tmux-persistente.md
|
||||
- Glosario: arquitectura/glosario.md
|
||||
- Decisiones (ADRs):
|
||||
- "0001 · Por qué k3d": decisiones/0001-por-que-k3d.md
|
||||
@@ -95,6 +96,7 @@ nav:
|
||||
- "0006 · Motor de búsqueda y facetas": decisiones/0006-motor-busqueda-facetas.md
|
||||
- "0007 · Identidad visual propia": decisiones/0007-identidad-visual-propia.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
|
||||
- Playbooks:
|
||||
- Crashloop Medusa: playbooks/incidente-crashloop-medusa.md
|
||||
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
runAsNonRoot: false
|
||||
containers:
|
||||
- name: app
|
||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.181
|
||||
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 { handleGoogleCallback } from "@/lib/headless/providers/medusa-customer";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { code, state } = await request.json();
|
||||
if (!code || !state) {
|
||||
return Response.json({ error: "Faltan parámetros de Google" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const customer = await handleGoogleCallback(code, state);
|
||||
return Response.json(customer);
|
||||
} catch (error) {
|
||||
return Response.json({ error: (error as Error).message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getGoogleAuthUrl } from "@/lib/headless/providers/medusa-customer";
|
||||
|
||||
// Navegacion de pagina completa (no fetch/XHR) -- el boton "Continuar
|
||||
// con Google" enlaza directo aca, el browser sigue el 302 hasta la
|
||||
// pantalla real de consentimiento de Google.
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const location = await getGoogleAuthUrl();
|
||||
return Response.redirect(location);
|
||||
} catch (error) {
|
||||
const message = encodeURIComponent((error as Error).message);
|
||||
return Response.redirect(new URL(`/?googleAuthError=${message}`, request.url));
|
||||
}
|
||||
}
|
||||
@@ -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,10 @@
|
||||
import { Suspense } from "react";
|
||||
import { GoogleCallbackClient } from "@/components/account/google-callback-client";
|
||||
|
||||
export default function GoogleCallbackPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<GoogleCallbackClient />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { CheckoutClient } from "@/components/checkout/checkout-client";
|
||||
|
||||
export default function CheckoutPage() {
|
||||
return <CheckoutClient />;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
/* ADR 0008 ("Navy & Coral") -- reemplaza ADR 0007 (Opcion 2, "Atelier
|
||||
calido"). Ver docs-portal/docs/decisiones/0008-identidad-navy-coral.md */
|
||||
--color-ari-marino: #122844; /* ancla: header, footer, badge "Nuevo", fondo de hero */
|
||||
--color-ari-coral: #D85A30; /* acento unico de accion: CTA, precio destacado */
|
||||
--color-ari-coral-claro: #F0997B; /* acento secundario: subtitulos sobre marino, ala inferior del isotipo */
|
||||
/* ADR 0008 -- paleta final "Azul & Amarillo" (inspirada en Walmart),
|
||||
iteracion sobre "Navy & Coral". Ver
|
||||
docs-portal/docs/decisiones/0008-identidad-navy-coral.md */
|
||||
--color-ari-marino: #0055B8; /* ancla: header, footer, badge "Nuevo", fondo de hero */
|
||||
--color-ari-coral: #0055B8; /* boton de accion (CTA): azul solido, nunca amarillo */
|
||||
--color-ari-coral-claro: #FFC220; /* acento: badges de oferta/descuento/urgencia, detalles del isotipo -- nunca en botones */
|
||||
|
||||
/* Alias de compatibilidad -- ADR 0007 definio estos nombres y hoy los
|
||||
siguen consumiendo catalog-client.tsx, product-card.tsx y button.tsx
|
||||
@@ -33,8 +34,8 @@
|
||||
html { scroll-behavior: smooth; }
|
||||
body { margin: 0; background: #FFFFFF; color: var(--color-slate-900); font-family: var(--font-inter), ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; text-rendering: optimizeLegibility; }
|
||||
button, a { -webkit-tap-highlight-color: transparent; }
|
||||
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible { outline: 3px solid rgb(216 90 48 / .5); outline-offset: 3px; }
|
||||
::selection { background: rgb(216 90 48 / .15); color: var(--color-slate-900); }
|
||||
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible { outline: 3px solid rgb(0 85 184 / .5); outline-offset: 3px; }
|
||||
::selection { background: rgb(0 85 184 / .15); color: var(--color-slate-900); }
|
||||
|
||||
.content-auto {
|
||||
content-visibility: auto;
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
<!-- ADR 0008 ("Navy & Coral"). Version reducida del isotipo para favicon/
|
||||
app icon: solo circulo marino + mariposa, sin wordmark (no cabe
|
||||
legible a este tamano). Convencion de Next.js App Router: este
|
||||
archivo se sirve automaticamente como favicon/app icon. -->
|
||||
<!-- ADR 0008, paleta final "Azul & Amarillo" (Walmart-inspirada). Version
|
||||
reducida del isotipo para favicon/app icon: solo circulo azul +
|
||||
mariposa, sin wordmark (no cabe legible a este tamano). Convencion de
|
||||
Next.js App Router: este archivo se sirve automaticamente como
|
||||
favicon/app icon. -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 34 34" role="img" aria-label="ARI shopping">
|
||||
<circle cx="17" cy="17" r="17" fill="#122844"/>
|
||||
<circle cx="17" cy="17" r="17" fill="#0055B8"/>
|
||||
<g transform="translate(0 5)">
|
||||
<ellipse cx="10" cy="8" rx="9" ry="7" transform="rotate(-18 10 8)" fill="#D85A30"/>
|
||||
<ellipse cx="24" cy="8" rx="9" ry="7" transform="rotate(18 24 8)" fill="#D85A30"/>
|
||||
<ellipse cx="12" cy="16" rx="6" ry="5" transform="rotate(-10 12 16)" fill="#F0997B"/>
|
||||
<ellipse cx="22" cy="16" rx="6" ry="5" transform="rotate(10 22 16)" fill="#F0997B"/>
|
||||
<rect x="16" y="3" width="2" height="18" rx="1" fill="#122844"/>
|
||||
<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>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 895 B After Width: | Height: | Size: 932 B |
@@ -21,7 +21,7 @@ export const metadata: Metadata = {
|
||||
openGraph: { title: "ARI Shopping", description: "Tesoros para cada aventura.", type: "website", locale: "es_CO" },
|
||||
};
|
||||
|
||||
export const viewport: Viewport = { width: "device-width", initialScale: 1, themeColor: "#122844" };
|
||||
export const viewport: Viewport = { width: "device-width", initialScale: 1, themeColor: "#0055B8" };
|
||||
|
||||
// ADR 0008 ("Navy & Coral"): Poppins peso 700 para los "momentos de marca"
|
||||
// (wordmark, h1/h2, precio, CTA) + Inter para body/UI -- solo se carga el
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { ArrowRight } from "lucide-react";
|
||||
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 { ProductCarousel } from "@/components/product/product-carousel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -17,5 +18,24 @@ export const dynamic = "force-dynamic";
|
||||
export default async function HomePage() {
|
||||
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
|
||||
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();
|
||||
const products = await getProducts();
|
||||
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} /></>;
|
||||
}
|
||||
@@ -65,7 +65,7 @@ spec:
|
||||
memory: 64Mi
|
||||
|
||||
- name: migrations
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.215
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- node
|
||||
@@ -86,7 +86,7 @@ spec:
|
||||
|
||||
containers:
|
||||
- name: app
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.215
|
||||
imagePullPolicy: IfNotPresent
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"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";
|
||||
|
||||
function GoogleIcon() {
|
||||
return (
|
||||
<svg viewBox="0 0 48 48" className="size-4" aria-hidden="true">
|
||||
<path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.1 8 3l6-6C34 5.1 29.3 3 24 3 12.4 3 3 12.4 3 24s9.4 21 21 21 21-9.4 21-21c0-1.4-.1-2.7-.4-3.5z" />
|
||||
<path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.6 15.9 18.9 13 24 13c3.1 0 5.8 1.1 8 3l6-6C34 5.1 29.3 3 24 3 16.1 3 9.3 7.6 6.3 14.7z" />
|
||||
<path fill="#4CAF50" d="M24 45c5.2 0 9.9-2 13.4-5.2l-6.2-5.2c-2 1.5-4.6 2.4-7.2 2.4-5.2 0-9.6-3.3-11.3-8l-6.5 5C9.2 40.3 16 45 24 45z" />
|
||||
<path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.2 4.3-4.1 5.6l6.2 5.2C41.4 35.9 45 30.5 45 24c0-1.4-.1-2.7-.4-3.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
<div className="mt-3 flex items-center gap-3 text-xs font-bold uppercase tracking-wide text-slate-400">
|
||||
<span className="h-px flex-1 bg-slate-100" />o<span className="h-px flex-1 bg-slate-100" />
|
||||
</div>
|
||||
<Button asChild variant="outline" size="lg" className="mt-3 w-full">
|
||||
<a href="/api/customer/google/start">
|
||||
<GoogleIcon />Continuar con Google
|
||||
</a>
|
||||
</Button>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useCustomerStore } from "@/store/customer-store";
|
||||
|
||||
export function GoogleCallbackClient() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const loginWithGoogle = useCustomerStore((state) => state.loginWithGoogle);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const ran = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Guard contra el doble-mount de StrictMode -- el code de Google es
|
||||
// de un solo uso, un segundo intento con el mismo code fallaria.
|
||||
if (ran.current) return;
|
||||
ran.current = true;
|
||||
|
||||
const code = searchParams.get("code");
|
||||
const state = searchParams.get("state");
|
||||
if (!code || !state) {
|
||||
setError("Faltan parámetros de Google en la URL de retorno.");
|
||||
return;
|
||||
}
|
||||
|
||||
loginWithGoogle(code, state).then((ok) => {
|
||||
router.replace(ok ? "/" : "/?googleAuthError=1");
|
||||
});
|
||||
}, [searchParams, loginWithGoogle, router]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 text-center">
|
||||
{error ? (
|
||||
<>
|
||||
<p className="text-lg font-black text-rose-600">No se pudo iniciar sesión con Google</p>
|
||||
<p className="text-sm text-slate-600">{error}</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm font-bold text-slate-600">Conectando con Google…</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -323,18 +323,18 @@ export function CatalogClient({
|
||||
<div className="mb-8">
|
||||
{breadcrumb.length > 0 && (
|
||||
<nav aria-label="Breadcrumb" className="mb-4 flex flex-wrap items-center gap-1.5 text-xs font-bold text-slate-500">
|
||||
<Link href="/catalog" prefetch={false} className="hover:text-ari-ciruela">
|
||||
<Link href="/catalog" prefetch={false} className="hover:text-ari-coral">
|
||||
Inicio
|
||||
</Link>
|
||||
{breadcrumb.map((node, index) => (
|
||||
<span key={node.id} className="flex items-center gap-1.5">
|
||||
<ChevronRight className="size-3" />
|
||||
{index === breadcrumb.length - 1 ? (
|
||||
<span aria-current="page" className="text-ari-carbon">
|
||||
<span aria-current="page" className="text-ari-marino">
|
||||
{node.name}
|
||||
</span>
|
||||
) : (
|
||||
<Link href={`/catalog?category=${encodeURIComponent(node.name)}`} prefetch={false} className="hover:text-ari-ciruela">
|
||||
<Link href={`/catalog?category=${encodeURIComponent(node.name)}`} prefetch={false} className="hover:text-ari-coral">
|
||||
{node.name}
|
||||
</Link>
|
||||
)}
|
||||
@@ -342,23 +342,23 @@ export function CatalogClient({
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
<span className="text-xs font-black uppercase tracking-[.18em] text-ari-ciruela">
|
||||
<span className="text-xs font-black uppercase tracking-[.18em] text-ari-coral">
|
||||
Catálogo completo
|
||||
</span>
|
||||
<h1 className="font-display mt-2 text-5xl font-bold tracking-tight text-ari-carbon">Todos los tesoros</h1>
|
||||
<h1 className="font-display mt-2 text-5xl font-bold tracking-tight text-ari-marino">Todos los tesoros</h1>
|
||||
<p className="mt-3 text-slate-500">
|
||||
Filtra por categoría, marca o edad sin recargar la página.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-8 lg:grid-cols-[260px_1fr]">
|
||||
<aside className="h-fit space-y-6 rounded-lg border border-slate-100 bg-white p-6 shadow-lg shadow-ari-carbon-oscuro/5 lg:sticky lg:top-44">
|
||||
<aside className="h-fit space-y-6 rounded-lg border border-slate-100 bg-white p-6 shadow-lg shadow-ari-marino/5 lg:sticky lg:top-44">
|
||||
<div className="flex items-center justify-between">
|
||||
<strong className="flex items-center gap-2 text-lg font-black">
|
||||
<SlidersHorizontal className="size-5 text-ari-cobre" />
|
||||
<SlidersHorizontal className="size-5 text-ari-coral-claro" />
|
||||
Filtros
|
||||
</strong>
|
||||
<button onClick={reset} className="text-xs font-black text-ari-ciruela">
|
||||
<button onClick={reset} className="text-xs font-black text-ari-coral">
|
||||
<X className="mr-1 inline size-3" />
|
||||
Limpiar
|
||||
</button>
|
||||
@@ -392,7 +392,7 @@ export function CatalogClient({
|
||||
step={5000}
|
||||
value={maxPrice}
|
||||
onChange={(event) => setMaxPrice(Number(event.target.value))}
|
||||
className="w-full accent-ari-ciruela"
|
||||
className="w-full accent-ari-coral"
|
||||
/>
|
||||
<p className="mt-2 text-xs font-bold text-slate-500">
|
||||
Hasta ${maxPrice.toLocaleString("es-CO")}
|
||||
@@ -470,8 +470,8 @@ function Filter({
|
||||
onClick={() => onChange(value)}
|
||||
className={`rounded-md px-3 py-2 text-xs font-bold transition ${
|
||||
selected === value
|
||||
? "bg-ari-carbon-oscuro text-white"
|
||||
: "bg-slate-100 text-slate-600 hover:bg-ari-cobre/10"
|
||||
? "bg-ari-marino text-white"
|
||||
: "bg-slate-100 text-slate-600 hover:bg-ari-coral-claro/10"
|
||||
}`}
|
||||
>
|
||||
{value}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
// un asset en public/images/categories/. Las demas caen al tile de solo
|
||||
// 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> = {
|
||||
juguetes: { subtitle: "Personajes que inspiran", image: "/images/categories/figuras.webp", color: "from-yellow-300 to-orange-400" },
|
||||
"mochilas-y-morrales": { subtitle: "Estilo para cada aventura", image: "/images/categories/mochilas.webp", color: "from-cyan-400 to-blue-500" },
|
||||
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "from-pink-300 to-fuchsia-400" },
|
||||
educativos: { subtitle: "Aprender jugando", color: "from-emerald-400 to-teal-600" },
|
||||
"accion-y-aventura": { subtitle: "Para explorar sin límites", color: "from-red-500 to-rose-700" },
|
||||
variedades: { subtitle: "Un poco de todo", color: "from-violet-400 to-purple-600" },
|
||||
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: "bg-sky-100" },
|
||||
"bebes-y-primera-infancia": { subtitle: "Primeros descubrimientos", color: "bg-rose-100" },
|
||||
educativos: { subtitle: "Aprender jugando", color: "bg-emerald-100" },
|
||||
"accion-y-aventura": { subtitle: "Para explorar sin límites", color: "bg-orange-100" },
|
||||
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
|
||||
// como por el grid del catalogo (tiles promocionales intercalados,
|
||||
@@ -31,20 +35,24 @@ export function PromoTile({ category, className = "" }: { category: Category; cl
|
||||
return (
|
||||
<Link
|
||||
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 && (
|
||||
<>
|
||||
<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" />
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-transparent to-white/5" />
|
||||
</>
|
||||
<div className="absolute inset-3 bottom-24 overflow-hidden rounded-2xl">
|
||||
<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>
|
||||
)}
|
||||
<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>
|
||||
<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>
|
||||
<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 />
|
||||
</span>
|
||||
</div>
|
||||
@@ -61,10 +69,10 @@ export function CategoryTiles({ categories }: { categories: Category[] }) {
|
||||
<section className="mx-auto max-w-7xl px-4 py-14">
|
||||
<div className="mb-8 flex items-end justify-between gap-4">
|
||||
<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>
|
||||
</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 className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -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):
|
||||
@@ -50,15 +54,27 @@ export function Navbar({ products, categories }: { products: Product[]; categori
|
||||
</div>
|
||||
|
||||
<div className="relative overflow-visible bg-white">
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 h-1 bg-ari-coral" />
|
||||
<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">
|
||||
{/* 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">
|
||||
{/* 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>
|
||||
<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>}
|
||||
@@ -104,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>
|
||||
);
|
||||
}
|
||||
@@ -171,7 +175,7 @@ function CategoryNavBar({
|
||||
}) {
|
||||
return (
|
||||
<nav className="bg-ari-marino text-white">
|
||||
<div className="mx-auto flex max-w-7xl items-center gap-1 px-4 py-2">
|
||||
<div className="relative mx-auto flex max-w-7xl items-center gap-1 px-4 py-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -213,7 +217,7 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
|
||||
<div ref={containerRef} className="shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
@@ -227,7 +231,7 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute left-0 top-full z-50 mt-1 w-[min(92vw,64rem)] rounded-2xl border border-white/10 bg-ari-marino p-6 shadow-2xl">
|
||||
<div className="absolute left-0 top-full z-50 mt-1 max-h-[80vh] w-[min(92vw,64rem)] overflow-y-auto rounded-2xl border border-white/10 bg-ari-marino p-6 shadow-2xl">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-6">
|
||||
{tree.map((root) => (
|
||||
<div key={root.id}>
|
||||
|
||||
@@ -33,15 +33,15 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
||||
: null;
|
||||
|
||||
return (
|
||||
<article className="group flex h-full flex-col overflow-hidden rounded-lg border border-slate-100 bg-white shadow-lg shadow-ari-carbon-oscuro/5 transition duration-300 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-ari-ciruela/10">
|
||||
<div className="relative aspect-square overflow-hidden bg-ari-hueso">
|
||||
<article className="group flex h-full flex-col overflow-hidden rounded-lg border border-slate-100 bg-white shadow-lg shadow-ari-marino/5 transition duration-300 hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-ari-coral/10">
|
||||
<div className="relative aspect-square overflow-hidden bg-white">
|
||||
<Link href={`/product/${product.slug}`} prefetch={false}><Image src={product.thumbnail} alt={product.name} fill priority={priority} sizes="(max-width: 640px) 82vw, (max-width: 1024px) 44vw, 280px" className="object-cover transition duration-500 group-hover:scale-[1.035]" /></Link>
|
||||
<div className="absolute left-3 top-3 flex gap-2">{discountPercent && discountPercent > 0 && <Badge className="bg-ari-terracota-oscuro text-white">-{discountPercent}%</Badge>}{product.isNew && <Badge className="bg-ari-carbon-oscuro text-white">Nuevo</Badge>}{product.featured && <Badge className="bg-ari-cobre text-white"><Sparkles className="mr-1 size-3" />Top</Badge>}</div>
|
||||
<button type="button" aria-label={isFavorite ? "Quitar de favoritos" : "Agregar a favoritos"} aria-pressed={isFavorite} className={`absolute right-3 top-3 rounded-full p-2.5 shadow-lg backdrop-blur transition ${isFavorite ? "bg-ari-ciruela text-white" : "bg-white/95 text-slate-900 hover:text-ari-ciruela"}`} onClick={() => toggleProduct(product)}><Heart className={`size-4 ${isFavorite ? "fill-current" : ""}`} /></button>
|
||||
<div className="absolute left-3 top-3 flex gap-2">{discountPercent && discountPercent > 0 && <Badge className="bg-ari-coral-claro text-ari-marino">-{discountPercent}%</Badge>}{product.isNew && <Badge className="bg-ari-marino text-white">Nuevo</Badge>}{product.featured && <Badge className="bg-ari-coral-claro text-ari-marino"><Sparkles className="mr-1 size-3" />Top</Badge>}</div>
|
||||
<button type="button" aria-label={isFavorite ? "Quitar de favoritos" : "Agregar a favoritos"} aria-pressed={isFavorite} className={`absolute right-3 top-3 rounded-full p-2.5 shadow-lg backdrop-blur transition ${isFavorite ? "bg-ari-coral text-white" : "bg-white/95 text-slate-900 hover:text-ari-coral"}`} onClick={() => toggleProduct(product)}><Heart className={`size-4 ${isFavorite ? "fill-current" : ""}`} /></button>
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col space-y-3 p-5">
|
||||
<div className="flex items-center justify-between gap-2 text-xs font-bold text-slate-500"><span>{product.category}</span><span className="rounded-md bg-ari-cobre/10 px-2 py-1 text-ari-cobre">{product.collection}</span></div>
|
||||
<Link href={`/product/${product.slug}`} prefetch={false}><h3 className="line-clamp-2 min-h-12 text-lg font-black leading-6 text-ari-carbon group-hover:text-ari-ciruela">{product.name}</h3></Link>
|
||||
<div className="flex items-center justify-between gap-2 text-xs font-bold text-slate-500"><span>{product.category}</span><span className="rounded-md bg-ari-coral-claro/10 px-2 py-1 text-ari-marino">{product.collection}</span></div>
|
||||
<Link href={`/product/${product.slug}`} prefetch={false}><h3 className="line-clamp-2 min-h-12 text-lg font-black leading-6 text-ari-marino group-hover:text-ari-coral">{product.name}</h3></Link>
|
||||
<p className="line-clamp-2 min-h-10 text-sm leading-5 text-slate-500">{product.shortDescription}</p>
|
||||
{product.variants.length > 1 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
@@ -55,7 +55,7 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
||||
onClick={() => setSelectedVariantId(variant.id)}
|
||||
className={`rounded-md border px-2.5 py-1 text-xs font-bold transition ${
|
||||
selectedVariantId === variant.id
|
||||
? "border-ari-ciruela bg-ari-ciruela/10 text-ari-ciruela"
|
||||
? "border-ari-coral bg-ari-coral/10 text-ari-coral"
|
||||
: "border-slate-200 text-slate-600 hover:border-slate-400"
|
||||
} ${!variant.available ? "cursor-not-allowed opacity-40" : ""}`}
|
||||
>
|
||||
@@ -70,7 +70,7 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
||||
<div className="mt-auto flex items-center justify-between gap-3 pt-1">
|
||||
<div className="flex flex-col">
|
||||
{product.compareAtPrice && <span className="text-xs font-bold text-slate-400 line-through">{formatMoney(product.compareAtPrice, product.currency)}</span>}
|
||||
<strong className="font-display text-base font-bold text-ari-carbon">{formatMoney(product.price, product.currency)}</strong>
|
||||
<strong className="font-display text-base font-bold text-ari-marino">{formatMoney(product.price, product.currency)}</strong>
|
||||
</div>
|
||||
<Button variant="primary" size="sm" onClick={() => addItem(product, selectedVariantId)}><ShoppingBag className="size-4" />Agregar</Button>
|
||||
</div>
|
||||
|
||||
@@ -18,5 +18,5 @@ export function ProductPurchase({ product }: { product: Product }) {
|
||||
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
||||
? selectedVariant.inventoryQuantity
|
||||
: 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 { Search, X } from "lucide-react";
|
||||
import { FormEvent, useEffect, useState } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { Product } from "@/lib/headless/types";
|
||||
|
||||
export function PredictiveSearch() {
|
||||
@@ -54,12 +53,34 @@ export function PredictiveSearch() {
|
||||
|
||||
return (
|
||||
<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="relative rounded-full bg-white">
|
||||
<Search className="pointer-events-none absolute left-5 top-1/2 z-10 size-5 -translate-y-1/2 text-violet-600" />
|
||||
<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" />
|
||||
{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>}
|
||||
</div>
|
||||
<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">
|
||||
{/* input propio (no el <Input> compartido) -- ese componente trae su
|
||||
propio focus:ring-4 focus:ring-cyan-300/30 hardcodeado que no se
|
||||
anulaba de forma confiable via tailwind-merge dentro de este
|
||||
contenedor compuesto (input + boton circular), causando un
|
||||
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>
|
||||
{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">
|
||||
@@ -69,12 +90,12 @@ export function PredictiveSearch() {
|
||||
{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">
|
||||
{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><strong className="line-clamp-1 text-sm">{product.name}</strong><span className="text-xs text-slate-500">{product.category} · {product.collection}</span></div>
|
||||
</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>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
runAsUser: 1001
|
||||
containers:
|
||||
- name: app
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.180
|
||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.216
|
||||
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,167 @@
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Flujo Google verificado en vivo (2026-08-29) contra el pod real, no
|
||||
// solo contra la doc: GET /auth/customer/google funciona igual que el
|
||||
// POST documentado (sin body, no hace falta callback_url -- ya viene de
|
||||
// GOOGLE_CALLBACK_URL en el modulo); la respuesta no trae Set-Cookie, o
|
||||
// sea que el "state" que Google reenvia en el callback es autocontenido
|
||||
// (firmado), no depende de sesion de servidor -- confirmado con un
|
||||
// callback con code/state inventados: 401 "No state provided, or
|
||||
// session expired" (mismo mensaje que con state ausente, no un error de
|
||||
// sesion real). auth/token/refresh confirmado que exige Bearer valido
|
||||
// (401 "Unauthorized" con uno invalido, no 404).
|
||||
function decodeJwtPayload(token: string): Record<string, unknown> {
|
||||
const payload = token.split(".")[1] ?? "";
|
||||
const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const json = Buffer.from(base64, "base64").toString("utf-8");
|
||||
return JSON.parse(json || "{}");
|
||||
}
|
||||
|
||||
export async function getGoogleAuthUrl(): Promise<string> {
|
||||
const data = await medusaAuthFetch("/auth/customer/google");
|
||||
return data.location as string;
|
||||
}
|
||||
|
||||
export async function handleGoogleCallback(code: string, state: string): Promise<CustomerSummary> {
|
||||
const query = new URLSearchParams({ code, state }).toString();
|
||||
const data = await medusaAuthFetch(`/auth/customer/google/callback?${query}`, { method: "POST" });
|
||||
const initialToken = data.token as string;
|
||||
const payload = decodeJwtPayload(initialToken);
|
||||
const actorId = payload.actor_id as string | undefined;
|
||||
|
||||
if (!actorId) {
|
||||
// Primer login con Google -- todavia no existe el customer real.
|
||||
const userMetadata = (payload.user_metadata as Record<string, unknown> | undefined) ?? {};
|
||||
const email = userMetadata.email as string;
|
||||
const firstName = (userMetadata.given_name as string) ?? (userMetadata.name as string) ?? email.split("@")[0];
|
||||
const lastName = (userMetadata.family_name as string) ?? "";
|
||||
await medusaAuthFetch("/store/customers", {
|
||||
method: "POST",
|
||||
token: initialToken,
|
||||
body: { email, first_name: firstName, last_name: lastName },
|
||||
});
|
||||
}
|
||||
|
||||
// El token del callback (o el de recien crear el customer) todavia no
|
||||
// sirve como sesion final -- hay que refrescarlo, tanto para usuarios
|
||||
// nuevos como para los que ya existian (confirmado contra la doc: los
|
||||
// dos casos convergen en el mismo paso de refresh).
|
||||
const refreshed = await medusaAuthFetch("/auth/token/refresh", { method: "POST", token: initialToken });
|
||||
return getCurrentCustomer(refreshed.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);
|
||||
}
|
||||
@@ -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 |
@@ -1,15 +1,16 @@
|
||||
<!-- ADR 0008 ("Navy & Coral"). Isotipo: mariposa geometrica de 4 elipses
|
||||
sobre circulo/campo marino + wordmark "ARI shopping".
|
||||
<!-- ADR 0008, paleta final "Azul & Amarillo" (Walmart-inspirada). Isotipo:
|
||||
mariposa geometrica de 4 elipses sobre circulo/campo azul + wordmark
|
||||
"ARI shopping".
|
||||
Ver docs-portal/docs/decisiones/0008-identidad-navy-coral.md -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 64" role="img" aria-label="ARI shopping">
|
||||
<rect width="200" height="64" rx="12" fill="#122844"/>
|
||||
<rect width="200" height="64" rx="12" fill="#0055B8"/>
|
||||
<g transform="translate(14 20)">
|
||||
<ellipse cx="10" cy="8" rx="9" ry="7" transform="rotate(-18 10 8)" fill="#D85A30"/>
|
||||
<ellipse cx="24" cy="8" rx="9" ry="7" transform="rotate(18 24 8)" fill="#D85A30"/>
|
||||
<ellipse cx="12" cy="16" rx="6" ry="5" transform="rotate(-10 12 16)" fill="#F0997B"/>
|
||||
<ellipse cx="22" cy="16" rx="6" ry="5" transform="rotate(10 22 16)" fill="#F0997B"/>
|
||||
<rect x="16" y="3" width="2" height="18" rx="1" fill="#122844"/>
|
||||
<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="64" y="38" font-family="Poppins, ui-sans-serif, system-ui, sans-serif" font-weight="700" font-size="26" fill="#FFFFFF">ARI</text>
|
||||
<text x="64" y="53" font-family="Poppins, ui-sans-serif, system-ui, sans-serif" font-weight="700" font-size="11" letter-spacing="2.5" fill="#F0997B">shopping</text>
|
||||
<text x="64" y="53" font-family="Poppins, ui-sans-serif, system-ui, sans-serif" font-weight="700" font-size="11" letter-spacing="2.5" fill="#FFC220">shopping</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
@@ -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,123 @@
|
||||
"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>;
|
||||
loginWithGoogle: (code: string, state: 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;
|
||||
},
|
||||
|
||||
loginWithGoogle: async (code, state) => {
|
||||
set({ loading: true, error: null });
|
||||
const result = await postJson("/api/customer/google/callback", { code, state });
|
||||
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