Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ceea23f40 | ||
|
|
313bb2eab4 | ||
|
|
710da06c0a | ||
|
|
9d08169092 | ||
|
|
1aa7802a61 | ||
|
|
b83722e9c5 | ||
|
|
8d543f5eb1 | ||
|
|
df791e0c28 | ||
|
|
feda1283d4 | ||
|
|
8fd0514e76 | ||
|
|
1cde29b344 | ||
|
|
8517102b63 | ||
|
|
7773bcdecf | ||
|
|
c62ad626cc | ||
|
|
8835d8ca0c | ||
|
|
997a00c284 | ||
|
|
0fb904b9ac | ||
|
|
a5ede05d96 | ||
|
|
63746eb090 | ||
|
|
2ca00d032d | ||
|
|
cb15749448 | ||
|
|
9e1adf4627 | ||
|
|
0ad74b6b70 | ||
|
|
d1d007fc7d | ||
|
|
11ac6d7949 | ||
|
|
093ae419d5 | ||
|
|
2b0d50c3d0 | ||
|
|
8126bb3d81 | ||
|
|
dedf4f0963 | ||
|
|
1cd1078cdf | ||
|
|
601378a77e | ||
|
|
1dccd0aa6a | ||
|
|
474ac3795b | ||
|
|
bb2ad3c317 | ||
|
|
578f085334 | ||
|
|
ce4842f375 | ||
|
|
2cce671049 | ||
|
|
22f97ee12e | ||
|
|
42c90d8534 | ||
|
|
cd8d2edd8f | ||
|
|
77389aea19 | ||
|
|
7ce11ecbb4 | ||
|
|
da10a4b688 |
No files matched your search
@@ -26,7 +26,14 @@ ENV CI=true \
|
|||||||
MEILISEARCH_API_KEY=build-only-meili-key \
|
MEILISEARCH_API_KEY=build-only-meili-key \
|
||||||
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
||||||
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
||||||
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback
|
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback \
|
||||||
|
PAYU_API_LOGIN=build-only-payu-login \
|
||||||
|
PAYU_API_KEY=build-only-payu-key \
|
||||||
|
PAYU_MERCHANT_ID=999999 \
|
||||||
|
PAYU_ACCOUNT_ID=999999 \
|
||||||
|
PAYU_ENV=sandbox \
|
||||||
|
PAYU_RESPONSE_URL=http://localhost:8000/checkout/pse/return \
|
||||||
|
PAYU_NOTIFY_URL=http://localhost:9000/hooks/payment/payu_pse
|
||||||
|
|
||||||
COPY package.json package-lock.json .npmrc ./
|
COPY package.json package-lock.json .npmrc ./
|
||||||
|
|
||||||
|
|||||||
@@ -181,6 +181,33 @@ module.exports = defineConfig({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
// ADR 0009: PayU LatAm elegido como proveedor de pago -- no existe
|
||||||
|
// ningun plugin real de Medusa para su API (los paquetes que
|
||||||
|
// aparecen buscando "PayU" son para PayU Polonia/CEE, API distinta
|
||||||
|
// por completo), asi que es un modulo custom propio. Alcance inicial:
|
||||||
|
// solo PSE (transferencia bancaria), no Nequi/Daviplata/tarjetas.
|
||||||
|
// provider_id resultante: "pp_payu_pse" (identifier "payu" + id
|
||||||
|
// "pse", convencion de Medusa).
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/payment",
|
||||||
|
options: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
resolve: "./src/modules/payu-pse",
|
||||||
|
id: "pse",
|
||||||
|
options: {
|
||||||
|
apiLogin: required("PAYU_API_LOGIN"),
|
||||||
|
apiKey: required("PAYU_API_KEY"),
|
||||||
|
merchantId: required("PAYU_MERCHANT_ID"),
|
||||||
|
accountId: required("PAYU_ACCOUNT_ID"),
|
||||||
|
env: process.env.PAYU_ENV || "sandbox",
|
||||||
|
responseUrl: required("PAYU_RESPONSE_URL"),
|
||||||
|
notifyUrl: required("PAYU_NOTIFY_URL"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
|
|
||||||
// ADR 0006 Etapa 2. Sin required(): a diferencia de S3/DB, Meilisearch
|
// 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,148 @@
|
|||||||
|
import { defineRouteConfig } from "@medusajs/admin-sdk";
|
||||||
|
import { ArrowDownTray, ArrowUpTray, CheckCircleSolid, XCircleSolid } from "@medusajs/icons";
|
||||||
|
import { Badge, Button, Container, Heading, Text, toast } from "@medusajs/ui";
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { sdk } from "../../lib/sdk";
|
||||||
|
|
||||||
|
// Importador masivo via CSV -- pensado para cargar varios productos de
|
||||||
|
// una sola vez (comprados en Amazon/eBay/etc, no dropshipping
|
||||||
|
// automatizado -- ver conversacion sobre por que se descarto raspar
|
||||||
|
// tiendas de terceros). Las fotos se descargan del origen y se re-alojan
|
||||||
|
// en el mismo MinIO/S3 del NAS que ya usa el resto del catalogo.
|
||||||
|
|
||||||
|
type RowResult = {
|
||||||
|
row: number;
|
||||||
|
title: string;
|
||||||
|
ok: boolean;
|
||||||
|
action?: "created" | "updated";
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function downloadTemplate() {
|
||||||
|
window.open("/admin/product-import", "_blank");
|
||||||
|
}
|
||||||
|
|
||||||
|
const ProductImportPanel = () => {
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [results, setResults] = useState<RowResult[] | null>(null);
|
||||||
|
|
||||||
|
async function handleFile(file: File) {
|
||||||
|
const csv = await file.text();
|
||||||
|
setLoading(true);
|
||||||
|
setResults(null);
|
||||||
|
try {
|
||||||
|
const data = await sdk.client.fetch<{ results?: RowResult[]; error?: string }>("/admin/product-import", {
|
||||||
|
method: "post",
|
||||||
|
body: { csv },
|
||||||
|
});
|
||||||
|
if (data.error) {
|
||||||
|
toast.error("No se pudo procesar el archivo", { description: data.error });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setResults(data.results ?? []);
|
||||||
|
const okCount = data.results?.filter((r) => r.ok).length ?? 0;
|
||||||
|
const failCount = (data.results?.length ?? 0) - okCount;
|
||||||
|
if (failCount === 0) {
|
||||||
|
toast.success(`${okCount} productos importados`);
|
||||||
|
} else {
|
||||||
|
toast.warning(`${okCount} importados, ${failCount} con error`, {
|
||||||
|
description: "Revisa el detalle abajo.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
toast.error("No se pudo procesar el archivo", { description: (error as Error).message });
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
if (inputRef.current) inputRef.current.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container className="divide-y p-0">
|
||||||
|
<div className="flex items-center justify-between px-6 py-4">
|
||||||
|
<div>
|
||||||
|
<Heading level="h2">Importación de productos</Heading>
|
||||||
|
<Text size="small" className="text-ui-fg-subtle">
|
||||||
|
Carga varios productos a la vez desde un archivo CSV, con fotos, descripción y precio.
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button size="small" variant="secondary" onClick={downloadTemplate}>
|
||||||
|
<ArrowDownTray />
|
||||||
|
Descargar plantilla
|
||||||
|
</Button>
|
||||||
|
<Button size="small" variant="primary" isLoading={loading} onClick={() => inputRef.current?.click()}>
|
||||||
|
<ArrowUpTray />
|
||||||
|
Subir CSV
|
||||||
|
</Button>
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".csv,text/csv"
|
||||||
|
className="hidden"
|
||||||
|
onChange={(event) => {
|
||||||
|
const file = event.target.files?.[0];
|
||||||
|
if (file) handleFile(file);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-6 py-4">
|
||||||
|
<Text size="small" className="text-ui-fg-subtle">
|
||||||
|
Columnas: <code>titulo, descripcion, precio, categoria, coleccion, cantidad, fotos</code>. Varias fotos se
|
||||||
|
separan con <code>;</code> dentro de la misma celda. Si <code>categoria</code>/<code>coleccion</code> no
|
||||||
|
coinciden con una ya existente, se crean nuevas. Si <code>titulo</code> coincide con un producto ya
|
||||||
|
importado, no se duplica: se le agregan las fotos nuevas y se actualiza la descripción si la fila trae una.
|
||||||
|
Cada foto se descarga y se guarda en el almacenamiento propio de la tienda (no queda enlazada al sitio de
|
||||||
|
origen).
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{results && (
|
||||||
|
<div className="px-6 py-4">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b text-left text-ui-fg-subtle">
|
||||||
|
<th className="w-10 py-2" />
|
||||||
|
<th className="py-2 font-medium">Fila</th>
|
||||||
|
<th className="py-2 font-medium">Producto</th>
|
||||||
|
<th className="py-2 font-medium">Detalle</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{results.map((result) => (
|
||||||
|
<tr key={result.row} className="border-b last:border-0">
|
||||||
|
<td className="py-2">
|
||||||
|
{result.ok ? (
|
||||||
|
<CheckCircleSolid className="text-ui-tag-green-icon" />
|
||||||
|
) : (
|
||||||
|
<XCircleSolid className="text-ui-tag-red-icon" />
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="py-2">{result.row}</td>
|
||||||
|
<td className="py-2">{result.title}</td>
|
||||||
|
<td className="py-2">
|
||||||
|
{result.ok ? (
|
||||||
|
<Badge color="green">{result.action === "updated" ? "Actualizado (ya existía)" : "Importado"}</Badge>
|
||||||
|
) : (
|
||||||
|
<span className="text-rose-600">{result.error}</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const config = defineRouteConfig({
|
||||||
|
label: "Importación",
|
||||||
|
icon: ArrowUpTray,
|
||||||
|
});
|
||||||
|
|
||||||
|
export default ProductImportPanel;
|
||||||
@@ -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,328 @@
|
|||||||
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import type {
|
||||||
|
IFulfillmentModuleService,
|
||||||
|
IProductModuleService,
|
||||||
|
ISalesChannelModuleService,
|
||||||
|
IStockLocationService,
|
||||||
|
} from "@medusajs/framework/types";
|
||||||
|
import {
|
||||||
|
createCollectionsWorkflow,
|
||||||
|
createInventoryItemsWorkflow,
|
||||||
|
createProductCategoriesWorkflow,
|
||||||
|
createProductsWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
|
uploadFilesWorkflow,
|
||||||
|
} from "@medusajs/medusa/core-flows";
|
||||||
|
import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
||||||
|
|
||||||
|
// Importador masivo de productos via CSV -- para alguien que compra
|
||||||
|
// producto fisico en Amazon/eBay/etc. y quiere cargarlo rapido a la
|
||||||
|
// tienda, no para dropshipping automatizado (ver conversacion: se evaluo
|
||||||
|
// y se descarto raspar catalogos de terceros sin autorizacion). Cada
|
||||||
|
// fila se procesa independiente (una foto rota o categoria mal escrita
|
||||||
|
// no tumba el resto del archivo).
|
||||||
|
//
|
||||||
|
// categoria/coleccion: si el nombre no matchea una categoria/coleccion
|
||||||
|
// ya existente (case-insensitive), se crea nueva -- antes se descartaba
|
||||||
|
// en silencio y el producto quedaba sin categoria/coleccion sin avisar
|
||||||
|
// (confirmado en vivo: "Hello Kitty & Friends" nunca se creo como
|
||||||
|
// coleccion). El handle de la nueva categoria/coleccion se genera con
|
||||||
|
// el mismo slugify() ASCII-safe de mas abajo, por la misma razon que el
|
||||||
|
// handle del producto: el default de Medusa no quita tildes/enies y
|
||||||
|
// rompe la ruta publica.
|
||||||
|
//
|
||||||
|
// Re-importar el mismo titulo (ej. para agregar mas fotos o actualizar
|
||||||
|
// la descripcion de un producto ya cargado) actualiza el producto
|
||||||
|
// existente en vez de crear uno nuevo -- antes cada re-importacion
|
||||||
|
// generaba un producto duplicado con handle distinto (confirmado en
|
||||||
|
// vivo con "Hello Kitty & Friends": misma fila re-subida para sumar
|
||||||
|
// fotos, dos productos con el mismo titulo en la tienda). El match es
|
||||||
|
// por titulo exacto (case-insensitive/trim), igual que categoria y
|
||||||
|
// coleccion; en un match, las fotos nuevas se agregan a las que ya
|
||||||
|
// tenia (no se reemplazan) y la descripcion se actualiza si la fila
|
||||||
|
// trae una. No toca precio/cantidad/categoria/coleccion del producto
|
||||||
|
// existente -- eso se edita a mano en el admin si hace falta.
|
||||||
|
//
|
||||||
|
// Las fotos se descargan del origen y se re-alojan en el mismo
|
||||||
|
// MinIO/S3 que ya usa el resto del catalogo (uploadFilesWorkflow ->
|
||||||
|
// mismo File Module Provider de medusa-config.ts, ya corre en el NAS).
|
||||||
|
// El bucket (S3_BUCKET=ari-products) es plano -- el provider de S3 de
|
||||||
|
// Medusa descarta cualquier subcarpeta del filename (usa solo
|
||||||
|
// path.parse().name + ulid, confirmado leyendo
|
||||||
|
// @medusajs/file-s3/dist/services/s3-file.js), asi que no hay una
|
||||||
|
// carpeta separada real para lo importado -- queda mezclado con el
|
||||||
|
// resto de fotos del catalogo, mismo criterio de nombres unicos por
|
||||||
|
// ulid que ya usa todo el sitio.
|
||||||
|
|
||||||
|
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
||||||
|
const IMAGE_FETCH_TIMEOUT_MS = 15000;
|
||||||
|
const OPTION_TITLE = "Presentación";
|
||||||
|
const DEFAULT_VARIANT_VALUE = "Estandar";
|
||||||
|
|
||||||
|
type ImportRow = {
|
||||||
|
titulo: string;
|
||||||
|
descripcion: string;
|
||||||
|
precio: string;
|
||||||
|
categoria: string;
|
||||||
|
coleccion: string;
|
||||||
|
cantidad: string;
|
||||||
|
fotos: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type RowResult = {
|
||||||
|
row: number;
|
||||||
|
title: string;
|
||||||
|
ok: boolean;
|
||||||
|
action?: "created" | "updated";
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Medusa genera el handle por defecto solo en minusculas + espacios a
|
||||||
|
// guiones, sin quitar tildes/enies -- confirmado en vivo: 3 productos
|
||||||
|
// importados con titulo acentuado (ej. "niñas", "Lógicos") quedaron con
|
||||||
|
// handle como "...niñas..." y daban 404 real al entrar por
|
||||||
|
// shop.cruzcloud.net (el tunel/ingress publico rompe rutas con UTF-8
|
||||||
|
// no-ASCII en el path, aunque el mismo request funciona perfecto pegandole
|
||||||
|
// directo al servicio dentro del cluster). Se genera el handle nosotros
|
||||||
|
// mismos, ASCII-only, en vez de dejarselo al default de Medusa. El sufijo
|
||||||
|
// corto evita colisiones entre titulos parecidos/repetidos sin necesidad
|
||||||
|
// de revisar unicidad antes de crear.
|
||||||
|
function slugify(title: string, uniquePart: string): string {
|
||||||
|
const base = title
|
||||||
|
.normalize("NFD")
|
||||||
|
.replace(/[̀-ͯ]/g, "")
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, "-")
|
||||||
|
.replace(/^-+|-+$/g, "")
|
||||||
|
.slice(0, 80)
|
||||||
|
.replace(/-+$/g, "");
|
||||||
|
return `${base || "producto"}-${uniquePart}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extensionFromContentType(contentType: string | null, url: string): string {
|
||||||
|
if (contentType?.includes("png")) return "png";
|
||||||
|
if (contentType?.includes("webp")) return "webp";
|
||||||
|
if (contentType?.includes("gif")) return "gif";
|
||||||
|
if (contentType?.includes("jpeg") || contentType?.includes("jpg")) return "jpg";
|
||||||
|
const match = url.match(/\.(jpe?g|png|webp|gif)(?:\?|$)/i);
|
||||||
|
return match ? match[1].toLowerCase().replace("jpeg", "jpg") : "jpg";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadImageAsBase64(url: string): Promise<{ content: string; mimeType: string; extension: string }> {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), IMAGE_FETCH_TIMEOUT_MS);
|
||||||
|
try {
|
||||||
|
const response = await fetch(url, { signal: controller.signal });
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`No se pudo descargar la imagen (${response.status})`);
|
||||||
|
}
|
||||||
|
const contentType = response.headers.get("content-type");
|
||||||
|
const buffer = Buffer.from(await response.arrayBuffer());
|
||||||
|
if (buffer.byteLength > MAX_IMAGE_BYTES) {
|
||||||
|
throw new Error(`Imagen supera ${MAX_IMAGE_BYTES / 1024 / 1024}MB`);
|
||||||
|
}
|
||||||
|
const extension = extensionFromContentType(contentType, url);
|
||||||
|
return {
|
||||||
|
content: buffer.toString("base64"),
|
||||||
|
mimeType: contentType?.split(";")[0] ?? `image/${extension === "jpg" ? "jpeg" : extension}`,
|
||||||
|
extension,
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
// Plantilla descargable -- misma fuente de verdad que valida el POST,
|
||||||
|
// asi que las columnas nunca quedan desincronizadas entre lo que se
|
||||||
|
// ofrece descargar y lo que realmente se procesa.
|
||||||
|
const header = "titulo,descripcion,precio,categoria,coleccion,cantidad,fotos";
|
||||||
|
const example =
|
||||||
|
'"Muñeco Buzz Lightyear","Figura articulada de 30cm, edición coleccionista.",89900,"Figuras de accion","Toy Story",3,"https://ejemplo.com/foto1.jpg;https://ejemplo.com/foto2.jpg"';
|
||||||
|
const csv = `${header}\n${example}\n`;
|
||||||
|
res.setHeader("Content-Type", "text/csv; charset=utf-8");
|
||||||
|
res.setHeader("Content-Disposition", 'attachment; filename="plantilla-importacion.csv"');
|
||||||
|
res.send(csv);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaResponse) {
|
||||||
|
const csvText = req.body?.csv;
|
||||||
|
if (!csvText || typeof csvText !== "string") {
|
||||||
|
res.status(400).json({ error: "Falta el contenido CSV" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = csvRowsToObjects(parseCsv(csvText)) as unknown as ImportRow[];
|
||||||
|
if (rows.length === 0) {
|
||||||
|
res.status(400).json({ error: "El archivo no tiene filas de datos" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const stockLocationService = req.scope.resolve<IStockLocationService>(Modules.STOCK_LOCATION);
|
||||||
|
const fulfillmentService = req.scope.resolve<IFulfillmentModuleService>(Modules.FULFILLMENT);
|
||||||
|
const salesChannelService = req.scope.resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL);
|
||||||
|
const productService = req.scope.resolve<IProductModuleService>(Modules.PRODUCT);
|
||||||
|
|
||||||
|
const [locations, shippingProfiles, salesChannels, categories, collections, existingProducts] = await Promise.all([
|
||||||
|
stockLocationService.listStockLocations({}),
|
||||||
|
fulfillmentService.listShippingProfiles({}),
|
||||||
|
salesChannelService.listSalesChannels({}),
|
||||||
|
// select explicito -- sin el, name/title llegaban undefined (el
|
||||||
|
// default de estos module services no siempre trae todos los
|
||||||
|
// escalares, a diferencia de la capa HTTP del Admin API, confirmado
|
||||||
|
// en vivo: la ruta /admin/product-categories con fields=id,name si
|
||||||
|
// los trae completos).
|
||||||
|
productService.listProductCategories({}, { select: ["id", "name"] }),
|
||||||
|
productService.listProductCollections({}, { select: ["id", "title"] }),
|
||||||
|
productService.listProducts({}, { select: ["id", "title"], relations: ["images"] }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const locationId = locations[0]?.id;
|
||||||
|
const shippingProfileId = shippingProfiles.find((p) => p.type === "default")?.id ?? shippingProfiles[0]?.id;
|
||||||
|
const salesChannelId = salesChannels[0]?.id;
|
||||||
|
|
||||||
|
if (!locationId || !shippingProfileId || !salesChannelId) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: "Faltan datos base de la tienda (bodega, perfil de envío o canal de venta)",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const categoryByName = new Map(
|
||||||
|
categories.filter((c) => c.name).map((c) => [c.name.toLowerCase().trim(), c.id]),
|
||||||
|
);
|
||||||
|
const collectionByName = new Map(
|
||||||
|
collections.filter((c) => c.title).map((c) => [c.title.toLowerCase().trim(), c.id]),
|
||||||
|
);
|
||||||
|
const productByTitle = new Map(
|
||||||
|
existingProducts.filter((p) => p.title).map((p) => [p.title.toLowerCase().trim(), p]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const results: RowResult[] = [];
|
||||||
|
|
||||||
|
for (let index = 0; index < rows.length; index++) {
|
||||||
|
const rowNumber = index + 2; // +1 header, +1 base 1
|
||||||
|
const row = rows[index];
|
||||||
|
const title = row.titulo?.trim();
|
||||||
|
try {
|
||||||
|
if (!title) throw new Error("Falta el título");
|
||||||
|
const price = Number(row.precio);
|
||||||
|
if (!Number.isFinite(price) || price <= 0) throw new Error("Precio inválido");
|
||||||
|
|
||||||
|
const imageUrls = (row.fotos ?? "")
|
||||||
|
.split(";")
|
||||||
|
.map((u) => u.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (imageUrls.length === 0) throw new Error("Falta al menos una foto");
|
||||||
|
|
||||||
|
const downloaded = await Promise.all(imageUrls.map((url) => downloadImageAsBase64(url)));
|
||||||
|
const { result: uploadedFiles } = await uploadFilesWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
files: downloaded.map((file, i) => ({
|
||||||
|
filename: `${Date.now()}-${index}-${i}.${file.extension}`,
|
||||||
|
mimeType: file.mimeType,
|
||||||
|
content: file.content,
|
||||||
|
access: "public" as const,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingProduct = productByTitle.get(title.toLowerCase());
|
||||||
|
if (existingProduct) {
|
||||||
|
await updateProductsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
id: existingProduct.id,
|
||||||
|
description: row.descripcion?.trim() || undefined,
|
||||||
|
images: [...(existingProduct.images ?? []).map((image) => ({ url: image.url })), ...uploadedFiles.map((f) => ({ url: f.url }))],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
results.push({ row: rowNumber, title, ok: true, action: "updated" });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const quantity = Number(row.cantidad);
|
||||||
|
const { result: inventoryItems } = await createInventoryItemsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
title,
|
||||||
|
location_levels: [
|
||||||
|
{ location_id: locationId, stocked_quantity: Number.isFinite(quantity) && quantity >= 0 ? quantity : 1 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const inventoryItemId = inventoryItems[0]?.id;
|
||||||
|
if (!inventoryItemId) throw new Error("No se pudo crear el registro de inventario");
|
||||||
|
|
||||||
|
const categoryName = row.categoria?.trim();
|
||||||
|
let categoryId = categoryName ? categoryByName.get(categoryName.toLowerCase()) : undefined;
|
||||||
|
if (categoryName && !categoryId) {
|
||||||
|
const { result: createdCategories } = await createProductCategoriesWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
product_categories: [
|
||||||
|
{ name: categoryName, handle: slugify(categoryName, `${Date.now().toString(36)}${index}`) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
categoryId = createdCategories[0].id;
|
||||||
|
categoryByName.set(categoryName.toLowerCase(), categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const collectionName = row.coleccion?.trim();
|
||||||
|
let collectionId = collectionName ? collectionByName.get(collectionName.toLowerCase()) : undefined;
|
||||||
|
if (collectionName && !collectionId) {
|
||||||
|
const { result: createdCollections } = await createCollectionsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
collections: [
|
||||||
|
{ title: collectionName, handle: slugify(collectionName, `${Date.now().toString(36)}${index}`) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
collectionId = createdCollections[0].id;
|
||||||
|
collectionByName.set(collectionName.toLowerCase(), collectionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await createProductsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
title,
|
||||||
|
handle: slugify(title, `${Date.now().toString(36)}${index}`),
|
||||||
|
description: row.descripcion || undefined,
|
||||||
|
status: "published",
|
||||||
|
thumbnail: uploadedFiles[0]?.url,
|
||||||
|
images: uploadedFiles.map((f) => ({ url: f.url })),
|
||||||
|
category_ids: categoryId ? [categoryId] : undefined,
|
||||||
|
collection_id: collectionId,
|
||||||
|
shipping_profile_id: shippingProfileId,
|
||||||
|
sales_channels: [{ id: salesChannelId }],
|
||||||
|
options: [{ title: OPTION_TITLE, values: [DEFAULT_VARIANT_VALUE] }],
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
title: DEFAULT_VARIANT_VALUE,
|
||||||
|
options: { [OPTION_TITLE]: DEFAULT_VARIANT_VALUE },
|
||||||
|
manage_inventory: true,
|
||||||
|
inventory_items: [{ inventory_item_id: inventoryItemId }],
|
||||||
|
prices: [{ amount: price, currency_code: "cop" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
results.push({ row: rowNumber, title, ok: true, action: "created" });
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ row: rowNumber, title: title || `Fila ${rowNumber}`, ok: false, error: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ results });
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||||
|
import { fetchPseBanks, type PayuBank, type PayuEnv } from "../../../../lib/payu";
|
||||||
|
|
||||||
|
// Lista de bancos PSE -- no hay forma de pedirle esto al modulo de pago
|
||||||
|
// custom directamente (AbstractPaymentProvider no expone sus metodos
|
||||||
|
// internos fuera del contrato de pago), asi que esta ruta llama a PayU
|
||||||
|
// con las mismas credenciales de medusa-config.ts. Cache en memoria (sin
|
||||||
|
// Redis/cron) porque PayU solo pide refrescar "una vez al dia" -- mismo
|
||||||
|
// criterio de simplicidad que ya usa la seccion de Meilisearch en
|
||||||
|
// medusa-config.ts.
|
||||||
|
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||||
|
let cache: { banks: PayuBank[]; fetchedAt: number } | null = null;
|
||||||
|
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) {
|
||||||
|
res.json({ banks: cache.banks });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const banks = await fetchPseBanks({
|
||||||
|
apiLogin: process.env.PAYU_API_LOGIN ?? "",
|
||||||
|
apiKey: process.env.PAYU_API_KEY ?? "",
|
||||||
|
merchantId: process.env.PAYU_MERCHANT_ID ?? "",
|
||||||
|
accountId: process.env.PAYU_ACCOUNT_ID ?? "",
|
||||||
|
env: (process.env.PAYU_ENV as PayuEnv) || "sandbox",
|
||||||
|
});
|
||||||
|
cache = { banks, fetchedAt: Date.now() };
|
||||||
|
res.json({ banks });
|
||||||
|
} catch (error) {
|
||||||
|
// Degrada a lista vacia en vez de tirar 500 -- el checkout debe poder
|
||||||
|
// mostrar un mensaje de "no disponible" en vez de romper la pagina
|
||||||
|
// entera, mismo criterio que /store/search cuando Meilisearch no
|
||||||
|
// responde.
|
||||||
|
res.json({ banks: cache?.banks ?? [], error: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// Parser CSV minimo (RFC4180: campos entre comillas, comillas escapadas
|
||||||
|
// como "", comas y saltos de linea dentro de campos citados) -- se evita
|
||||||
|
// sumar una dependencia nueva (papaparse/csv-parse) para un formato que
|
||||||
|
// nosotros mismos controlamos via la plantilla descargable.
|
||||||
|
export function parseCsv(text: string): string[][] {
|
||||||
|
const rows: string[][] = [];
|
||||||
|
let row: string[] = [];
|
||||||
|
let field = "";
|
||||||
|
let inQuotes = false;
|
||||||
|
let i = 0;
|
||||||
|
const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
||||||
|
|
||||||
|
while (i < normalized.length) {
|
||||||
|
const char = normalized[i];
|
||||||
|
if (inQuotes) {
|
||||||
|
if (char === '"') {
|
||||||
|
if (normalized[i + 1] === '"') {
|
||||||
|
field += '"';
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
inQuotes = false;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
field += char;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === '"') {
|
||||||
|
inQuotes = true;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === ",") {
|
||||||
|
row.push(field);
|
||||||
|
field = "";
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (char === "\n") {
|
||||||
|
row.push(field);
|
||||||
|
rows.push(row);
|
||||||
|
row = [];
|
||||||
|
field = "";
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
field += char;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
if (field.length > 0 || row.length > 0) {
|
||||||
|
row.push(field);
|
||||||
|
rows.push(row);
|
||||||
|
}
|
||||||
|
return rows.filter((r) => r.some((cell) => cell.trim().length > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function csvRowsToObjects(rows: string[][]): Record<string, string>[] {
|
||||||
|
const [header, ...body] = rows;
|
||||||
|
if (!header) return [];
|
||||||
|
const keys = header.map((h) => h.trim().toLowerCase());
|
||||||
|
return body.map((cols) => {
|
||||||
|
const obj: Record<string, string> = {};
|
||||||
|
keys.forEach((key, index) => {
|
||||||
|
obj[key] = (cols[index] ?? "").trim();
|
||||||
|
});
|
||||||
|
return obj;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
// Contrato real de la API de PayU LatAm (developers.payulatam.com,
|
||||||
|
// verificado en vivo 2026-09-06/07 -- NO es la misma API que los plugins
|
||||||
|
// de Medusa que aparecen buscando "PayU": esos son para PayU Polonia/CEE
|
||||||
|
// (clientId/posId/secondKey), API distinta por completo. Esta es la de
|
||||||
|
// apiLogin/apiKey/merchantId/accountId, la que cubre Colombia.
|
||||||
|
|
||||||
|
export type PayuEnv = "sandbox" | "production";
|
||||||
|
|
||||||
|
export interface PayuCredentials {
|
||||||
|
apiLogin: string;
|
||||||
|
apiKey: string;
|
||||||
|
merchantId: string;
|
||||||
|
accountId: string;
|
||||||
|
env: PayuEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BASE_URL: Record<PayuEnv, string> = {
|
||||||
|
sandbox: "https://sandbox.api.payulatam.com/payments-api/4.0/service.cgi",
|
||||||
|
production: "https://api.payulatam.com/payments-api/4.0/service.cgi",
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function payuRequest(
|
||||||
|
credentials: PayuCredentials,
|
||||||
|
body: Record<string, unknown>,
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
const response = await fetch(BASE_URL[credentials.env], {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
test: credentials.env === "sandbox",
|
||||||
|
language: "es",
|
||||||
|
...body,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
let json: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
json = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
throw new Error(`Respuesta no-JSON de PayU (HTTP ${response.status}): ${text.slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`PayU respondió HTTP ${response.status}: ${JSON.stringify(json).slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PayuBank {
|
||||||
|
id: string;
|
||||||
|
description: string;
|
||||||
|
pseCode: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPseBanks(credentials: PayuCredentials): Promise<PayuBank[]> {
|
||||||
|
const json = await payuRequest(credentials, {
|
||||||
|
command: "GET_BANKS_LIST",
|
||||||
|
bankListInformation: { paymentMethod: "PSE", paymentCountry: "CO" },
|
||||||
|
});
|
||||||
|
const banks = (json.banks ?? []) as Array<{
|
||||||
|
id?: unknown;
|
||||||
|
description?: unknown;
|
||||||
|
pseCode?: unknown;
|
||||||
|
}>;
|
||||||
|
return banks
|
||||||
|
.filter((bank) => typeof bank.pseCode === "string" && typeof bank.description === "string")
|
||||||
|
.map((bank) => ({
|
||||||
|
id: String(bank.id ?? bank.pseCode),
|
||||||
|
description: String(bank.description),
|
||||||
|
pseCode: String(bank.pseCode),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regla documentada de PayU para el campo de monto de la firma: si el
|
||||||
|
// segundo decimal es cero, un solo decimal (150.00 -> "150.0",
|
||||||
|
// 150.20 -> "150.2"); si no, dos decimales (150.25 -> "150.25").
|
||||||
|
export function formatPayuAmount(amount: number): string {
|
||||||
|
const twoDecimals = amount.toFixed(2);
|
||||||
|
return twoDecimals.endsWith("0") ? amount.toFixed(1) : twoDecimals;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firma de la orden (SUBMIT_TRANSACTION) -- distinta de la firma del
|
||||||
|
// webhook de abajo, confirmado contra el SDK PHP oficial de PayU.
|
||||||
|
export function buildOrderSignature(params: {
|
||||||
|
apiKey: string;
|
||||||
|
merchantId: string;
|
||||||
|
referenceCode: string;
|
||||||
|
amount: string;
|
||||||
|
currency: string;
|
||||||
|
}): string {
|
||||||
|
const raw = `${params.apiKey}~${params.merchantId}~${params.referenceCode}~${params.amount}~${params.currency}`;
|
||||||
|
return createHash("md5").update(raw).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firma del webhook de confirmación (notifyUrl) -- lo único que impide
|
||||||
|
// que cualquiera falsifique una confirmación de pago. Falla cerrado:
|
||||||
|
// cualquier mismatch devuelve false, nunca se traga la excepción.
|
||||||
|
export function verifyWebhookSignature(params: {
|
||||||
|
apiKey: string;
|
||||||
|
merchantId: string;
|
||||||
|
referenceSale: string;
|
||||||
|
value: string;
|
||||||
|
currency: string;
|
||||||
|
statePol: string;
|
||||||
|
sign: string;
|
||||||
|
}): boolean {
|
||||||
|
const raw = `${params.apiKey}~${params.merchantId}~${params.referenceSale}~${params.value}~${params.currency}~${params.statePol}`;
|
||||||
|
const expected = createHash("md5").update(raw).digest("hex");
|
||||||
|
return expected.toLowerCase() === params.sign.toLowerCase();
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||||
|
import PayuPseProviderService from "./service";
|
||||||
|
|
||||||
|
export default ModuleProvider(Modules.PAYMENT, {
|
||||||
|
services: [PayuPseProviderService],
|
||||||
|
});
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import { AbstractPaymentProvider, BigNumber } from "@medusajs/framework/utils";
|
||||||
|
import type {
|
||||||
|
AuthorizePaymentInput,
|
||||||
|
AuthorizePaymentOutput,
|
||||||
|
CancelPaymentInput,
|
||||||
|
CancelPaymentOutput,
|
||||||
|
CapturePaymentInput,
|
||||||
|
CapturePaymentOutput,
|
||||||
|
DeletePaymentInput,
|
||||||
|
DeletePaymentOutput,
|
||||||
|
GetPaymentStatusInput,
|
||||||
|
GetPaymentStatusOutput,
|
||||||
|
InitiatePaymentInput,
|
||||||
|
InitiatePaymentOutput,
|
||||||
|
Logger,
|
||||||
|
ProviderWebhookPayload,
|
||||||
|
RefundPaymentInput,
|
||||||
|
RefundPaymentOutput,
|
||||||
|
RetrievePaymentInput,
|
||||||
|
RetrievePaymentOutput,
|
||||||
|
UpdatePaymentInput,
|
||||||
|
UpdatePaymentOutput,
|
||||||
|
WebhookActionResult,
|
||||||
|
} from "@medusajs/framework/types";
|
||||||
|
import { buildOrderSignature, formatPayuAmount, payuRequest, verifyWebhookSignature } from "../../lib/payu";
|
||||||
|
import type { PayuPseInputData, PayuPseOptions, PayuPseSessionData } from "./types";
|
||||||
|
|
||||||
|
type InjectedDependencies = {
|
||||||
|
logger: Logger;
|
||||||
|
};
|
||||||
|
|
||||||
|
// PSE es AUTHORIZATION_AND_CAPTURE en un solo paso del lado de PayU, y
|
||||||
|
// asincrono: no hay confirmacion real hasta que llega el webhook (ver
|
||||||
|
// getWebhookActionAndData). authorizePayment/capturePayment por eso son
|
||||||
|
// casi no-ops -- el estado real lo trae siempre el webhook, nunca una
|
||||||
|
// llamada sincrona nuestra a PayU.
|
||||||
|
export default class PayuPseProviderService extends AbstractPaymentProvider<PayuPseOptions> {
|
||||||
|
static identifier = "payu";
|
||||||
|
|
||||||
|
protected logger_: Logger;
|
||||||
|
protected options_: PayuPseOptions;
|
||||||
|
|
||||||
|
constructor(container: InjectedDependencies, options: PayuPseOptions) {
|
||||||
|
super(container, options);
|
||||||
|
this.logger_ = container.logger;
|
||||||
|
this.options_ = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateOptions(options: Record<string, unknown>): void {
|
||||||
|
for (const key of ["apiLogin", "apiKey", "merchantId", "accountId", "env", "responseUrl", "notifyUrl"]) {
|
||||||
|
if (!options[key]) {
|
||||||
|
throw new Error(`payu-pse: falta la opción "${key}" en medusa-config.ts`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
|
||||||
|
const data = input.data as unknown as PayuPseInputData & { session_id: string };
|
||||||
|
const sessionId = data.session_id;
|
||||||
|
const amount = new BigNumber(input.amount).numeric;
|
||||||
|
const currency = input.currency_code.toUpperCase();
|
||||||
|
const formattedAmount = formatPayuAmount(amount);
|
||||||
|
|
||||||
|
const signature = buildOrderSignature({
|
||||||
|
apiKey: this.options_.apiKey,
|
||||||
|
merchantId: this.options_.merchantId,
|
||||||
|
referenceCode: sessionId,
|
||||||
|
amount: formattedAmount,
|
||||||
|
currency,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Shape del request confirmado contra la documentacion real de PayU
|
||||||
|
// LatAm para command/paymentMethod/extraParameters -- la anidacion
|
||||||
|
// exacta de buyer/payer (nombres de campo dentro de esos objetos) no
|
||||||
|
// quedo verificada campo por campo contra una respuesta real de
|
||||||
|
// sandbox en esta sesion. Primera prueba end-to-end contra el
|
||||||
|
// sandbox real de PayU debe confirmar esto (ver plan de
|
||||||
|
// implementacion, seccion Verificacion).
|
||||||
|
const json = await payuRequest(
|
||||||
|
{ apiLogin: this.options_.apiLogin, apiKey: this.options_.apiKey, merchantId: this.options_.merchantId, accountId: this.options_.accountId, env: this.options_.env },
|
||||||
|
{
|
||||||
|
command: "SUBMIT_TRANSACTION",
|
||||||
|
merchant: {
|
||||||
|
apiLogin: this.options_.apiLogin,
|
||||||
|
apiKey: this.options_.apiKey,
|
||||||
|
},
|
||||||
|
transaction: {
|
||||||
|
order: {
|
||||||
|
accountId: this.options_.accountId,
|
||||||
|
referenceCode: sessionId,
|
||||||
|
description: `Orden ARI Shopping ${sessionId}`,
|
||||||
|
language: "es",
|
||||||
|
signature,
|
||||||
|
notifyUrl: this.options_.notifyUrl,
|
||||||
|
additionalValues: {
|
||||||
|
TX_VALUE: { value: amount, currency },
|
||||||
|
},
|
||||||
|
buyer: {
|
||||||
|
fullName: data.full_name,
|
||||||
|
emailAddress: data.email,
|
||||||
|
contactPhone: data.phone,
|
||||||
|
dniNumber: data.doc_number,
|
||||||
|
shippingAddress: {
|
||||||
|
street1: data.address,
|
||||||
|
city: data.city,
|
||||||
|
state: data.state,
|
||||||
|
country: "CO",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
payer: {
|
||||||
|
fullName: data.full_name,
|
||||||
|
emailAddress: data.email,
|
||||||
|
contactPhone: data.phone,
|
||||||
|
dniNumber: data.doc_number,
|
||||||
|
billingAddress: {
|
||||||
|
street1: data.address,
|
||||||
|
city: data.city,
|
||||||
|
state: data.state,
|
||||||
|
country: "CO",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
type: "AUTHORIZATION_AND_CAPTURE",
|
||||||
|
paymentMethod: "PSE",
|
||||||
|
paymentCountry: "CO",
|
||||||
|
extraParameters: {
|
||||||
|
RESPONSE_URL: this.options_.responseUrl,
|
||||||
|
FINANCIAL_INSTITUTION_CODE: data.bank_code,
|
||||||
|
USER_TYPE: data.user_type,
|
||||||
|
PSE_REFERENCE2: data.doc_type,
|
||||||
|
PSE_REFERENCE3: data.doc_number,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const transactionResponse = (json.transactionResponse ?? {}) as Record<string, unknown>;
|
||||||
|
const extraParameters = (transactionResponse.extraParameters ?? {}) as Record<string, unknown>;
|
||||||
|
const bankUrl = extraParameters.BANK_URL;
|
||||||
|
if (typeof bankUrl !== "string" || !bankUrl) {
|
||||||
|
throw new Error(
|
||||||
|
`PayU no devolvió BANK_URL para la sesión ${sessionId}: ${JSON.stringify(transactionResponse).slice(0, 300)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionData: PayuPseSessionData = {
|
||||||
|
...data,
|
||||||
|
session_id: sessionId,
|
||||||
|
payu_order_id: String(transactionResponse.orderId ?? ""),
|
||||||
|
payu_transaction_id: String(transactionResponse.transactionId ?? ""),
|
||||||
|
reference_code: sessionId,
|
||||||
|
bank_url: bankUrl,
|
||||||
|
state: String(transactionResponse.state ?? "PENDING"),
|
||||||
|
amount,
|
||||||
|
currency,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { id: sessionId, data: sessionData as unknown as Record<string, unknown>, status: "pending" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSE es diferido: en el momento de completar el carrito, PayU todavia
|
||||||
|
// no confirmo nada -- "pending_authorization" es el mecanismo
|
||||||
|
// documentado de Medusa para esto (la orden queda "awaiting" y el
|
||||||
|
// navegador ya puede redirigirse al banco).
|
||||||
|
async authorizePayment(input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
|
||||||
|
return { data: input.data, status: "pending_authorization" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casi no-op: cuando el webhook reporta "captured", PayU ya liquido el
|
||||||
|
// dinero de su lado (un solo paso AUTHORIZATION_AND_CAPTURE) -- solo
|
||||||
|
// persiste el data actualizado.
|
||||||
|
async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSE no tiene concepto de cancelar una transaccion ya enviada al banco.
|
||||||
|
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
|
||||||
|
this.logger_.warn("payu-pse: cancelPayment llamado, pero PSE no soporta cancelar una transacción ya enviada");
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
// No verificado contra el endpoint real de PayU en esta sesión -- con
|
||||||
|
// dinero real de por medio, mejor tirar un error explícito que fingir
|
||||||
|
// un reembolso que nunca llamó a PayU.
|
||||||
|
async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
|
||||||
|
throw new Error(
|
||||||
|
"payu-pse: refundPayment no está implementado todavía -- el endpoint de reembolso de PayU LatAm no quedó verificado en vivo. Procesar el reembolso manualmente desde el panel de PayU por ahora.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Idem refundPayment: no verificado en vivo, mejor fallar explícito.
|
||||||
|
async retrievePayment(_input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
|
||||||
|
throw new Error("payu-pse: retrievePayment no está implementado todavía -- usar el panel de PayU para consultar una transacción.");
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
|
||||||
|
// PayU no tiene concepto de "modificar" una transaccion ya enviada.
|
||||||
|
// El checkout solo llega al step de pago despues de fijar direccion
|
||||||
|
// y envio, asi que el total no deberia cambiar una vez que existe
|
||||||
|
// una sesion PSE -- si esto se dispara, es una señal de que algo
|
||||||
|
// cambió el carrito después de crear la sesión.
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
|
||||||
|
const data = input.data as unknown as PayuPseSessionData | undefined;
|
||||||
|
const state = data?.state;
|
||||||
|
if (state === "APPROVED") return { status: "captured" };
|
||||||
|
if (state === "DECLINED" || state === "EXPIRED" || state === "ERROR") return { status: "canceled" };
|
||||||
|
return { status: "pending" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unico punto real de confirmacion asincrona. Falla cerrado: si la
|
||||||
|
// firma no matchea, no se hace nada -- nunca se confia en un webhook
|
||||||
|
// sin firma valida, es lo unico que impide que cualquiera falsifique
|
||||||
|
// un pago aprobado.
|
||||||
|
async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
|
||||||
|
const body = payload.data as Record<string, unknown>;
|
||||||
|
const merchantId = String(body.merchant_id ?? "");
|
||||||
|
const referenceSale = String(body.reference_sale ?? "");
|
||||||
|
const value = String(body.value ?? "");
|
||||||
|
const currency = String(body.currency ?? "");
|
||||||
|
const statePol = String(body.state_pol ?? "");
|
||||||
|
const sign = String(body.sign ?? "");
|
||||||
|
|
||||||
|
const validSignature = verifyWebhookSignature({
|
||||||
|
apiKey: this.options_.apiKey,
|
||||||
|
merchantId,
|
||||||
|
referenceSale,
|
||||||
|
value,
|
||||||
|
currency,
|
||||||
|
statePol,
|
||||||
|
sign,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!validSignature) {
|
||||||
|
this.logger_.warn(`payu-pse: webhook con firma inválida para reference_sale=${referenceSale}, ignorado`);
|
||||||
|
return { action: "not_supported" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo state_pol "4" (aprobado) es exito -- la tabla completa de
|
||||||
|
// codigos no quedo 100% verificada, asi que cualquier otro valor se
|
||||||
|
// trata como fallido en vez de asumir que es un exito distinto. Un
|
||||||
|
// "failed" de mas es reintentable; un "captured" de mas (dinero que
|
||||||
|
// nunca se aprobo) no lo es.
|
||||||
|
const action = statePol === "4" ? "captured" : "failed";
|
||||||
|
|
||||||
|
return {
|
||||||
|
action,
|
||||||
|
data: {
|
||||||
|
session_id: referenceSale,
|
||||||
|
amount: new BigNumber(value || 0),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import type { PayuEnv } from "../../lib/payu";
|
||||||
|
|
||||||
|
export interface PayuPseOptions {
|
||||||
|
apiLogin: string;
|
||||||
|
apiKey: string;
|
||||||
|
merchantId: string;
|
||||||
|
accountId: string;
|
||||||
|
env: PayuEnv;
|
||||||
|
// A donde PayU redirige al comprador de vuelta tras pagar en el banco
|
||||||
|
// (pagina propia del storefront, no confirma nada por si sola -- ver
|
||||||
|
// src/modules/payu-pse/service.ts).
|
||||||
|
responseUrl: string;
|
||||||
|
// URL publica de notifyUrl -- la rellena Medusa (ruta nativa
|
||||||
|
// /hooks/payment/:provider, no la escribimos nosotros), ver
|
||||||
|
// medusa-config.ts.
|
||||||
|
notifyUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PayuDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
export type PayuUserType = "N" | "J";
|
||||||
|
|
||||||
|
// Lo que el storefront manda como `data` al crear la sesion de pago PSE
|
||||||
|
// (recolectado en el step "address" del checkout, mas el banco elegido en
|
||||||
|
// el nuevo step "payment"). No viene de `context.customer` porque el
|
||||||
|
// checkout es de invitado -- ver ADR 0009.
|
||||||
|
export interface PayuPseInputData {
|
||||||
|
bank_code: string;
|
||||||
|
user_type: PayuUserType;
|
||||||
|
doc_type: PayuDocType;
|
||||||
|
doc_number: string;
|
||||||
|
full_name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
address: string;
|
||||||
|
city: string;
|
||||||
|
// Nombre del departamento (PayU pide "state" como texto libre, no un
|
||||||
|
// codigo DIVIPOLA como el resto del checkout).
|
||||||
|
state: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lo que initiatePayment devuelve y queda guardado en `data` de la
|
||||||
|
// PaymentSession -- publico para el storefront (ver nota en
|
||||||
|
// AbstractPaymentProvider.initiatePayment), nunca poner credenciales acá.
|
||||||
|
export interface PayuPseSessionData extends PayuPseInputData {
|
||||||
|
session_id: string;
|
||||||
|
payu_order_id: string;
|
||||||
|
payu_transaction_id: string;
|
||||||
|
reference_code: string;
|
||||||
|
bank_url: string;
|
||||||
|
state: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
@@ -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 },
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -37,6 +37,9 @@ flowchart LR
|
|||||||
SSH["Cliente SSH<br/>(laptop / tablet / lo que sea)"] -->|docker exec| C["Contenedor tmux-host<br/>--network host, --restart unless-stopped"]
|
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'"]
|
C --> T["tmux server<br/>sesión 'lab'"]
|
||||||
T --> CC["proceso claude<br/>(Claude Code)"]
|
T --> CC["proceso claude<br/>(Claude Code)"]
|
||||||
|
C --> HC["healthcheck.sh (background)<br/>cada 30 min"]
|
||||||
|
HC -.->|curl| NET["gitea.cruzcloud.net"]
|
||||||
|
HC -.->|recrea si falta| T
|
||||||
C -.->|bind mount| DATA["/DATA (host)<br/>repos y configs del lab"]
|
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| 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"]
|
C -.->|bind mount| HOME["/DATA/AppData/k3d-lab-v3/claude-code-home (host)<br/>-> /root/.claude"]
|
||||||
@@ -49,7 +52,17 @@ reinicia.
|
|||||||
|
|
||||||
## Contenedor: `tmux-host`
|
## Contenedor: `tmux-host`
|
||||||
|
|
||||||
|
La imagen se construye desde `scripts/tmux-host/Dockerfile` (antes era
|
||||||
|
un `docker run ... alpine sh -c "apk add ..."` inline — mismo contenido,
|
||||||
|
pero ahora como imagen versionada en vez de reinstalar todo en cada
|
||||||
|
arranque). El Dockerfile fija `WORKDIR /DATA/AppData/k3d-lab-v3/lab-cruzcloud`
|
||||||
|
(la raíz del lab, con `CLAUDE.md`, `apps-registry/`, `platform-infra/` y
|
||||||
|
`scripts/`) y agrega `healthcheck.sh` (ver más abajo) como proceso en
|
||||||
|
background del contenedor.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
docker build -t tmux-host:local scripts/tmux-host
|
||||||
|
|
||||||
docker run -d \
|
docker run -d \
|
||||||
--name tmux-host \
|
--name tmux-host \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
@@ -59,9 +72,15 @@ docker run -d \
|
|||||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home:/root/.claude \
|
-v /DATA/AppData/k3d-lab-v3/claude-code-home:/root/.claude \
|
||||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home.json:/root/.claude.json \
|
-v /DATA/AppData/k3d-lab-v3/claude-code-home.json:/root/.claude.json \
|
||||||
--network host \
|
--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"
|
tmux-host:local
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`WORKDIR` hace que `docker exec` (y por lo tanto `lab-session.sh`)
|
||||||
|
arranquen ya posicionados en la raíz del lab sin tener que navegar a
|
||||||
|
mano — `lab-session.sh` además pasa la ruta explícita vía `tmux new -c`
|
||||||
|
por las dudas, para no depender de que `docker exec` herede el `WORKDIR`
|
||||||
|
de la imagen.
|
||||||
|
|
||||||
| Volumen | Destino | Por qué |
|
| 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 |
|
| `/DATA` | `/DATA` | Acceso a los repos (`apps-registry`, `platform-infra`, `scripts`) y configs del lab, mismos paths que en el host |
|
||||||
@@ -195,13 +214,47 @@ Si la sesión `lab` existe, se adjunta a ella (mismo shell, mismo
|
|||||||
ejemplo justo después de que el contenedor se recreó desde cero— la
|
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.
|
crea. No hay que recordar cuál de los dos casos aplica.
|
||||||
|
|
||||||
|
## Chequeo de salud automático (cada 30 min)
|
||||||
|
|
||||||
|
`scripts/tmux-host/healthcheck.sh` corre en background dentro del
|
||||||
|
propio contenedor (lanzado por `entrypoint.sh`, el `ENTRYPOINT` de la
|
||||||
|
imagen) y cada `HEALTHCHECK_INTERVAL_SEC` (1800s por defecto) hace dos
|
||||||
|
chequeos independientes, con una respuesta distinta según el tipo de
|
||||||
|
falla:
|
||||||
|
|
||||||
|
- **Conectividad de red real** (`curl` a `https://gitea.cruzcloud.net/`):
|
||||||
|
si falla, **solo se registra** en el log y se notifica por Telegram —
|
||||||
|
el contenedor nunca intenta "arreglar" la red del host. Un problema de
|
||||||
|
red puede ser de hardware/BIOS (deuda técnica ya conocida, ver
|
||||||
|
`incidente-medusa-crashloop-2026-08.md`), fuera del alcance real de un
|
||||||
|
contenedor.
|
||||||
|
- **Existencia de la sesión tmux `lab`** (`tmux has-session`): si no
|
||||||
|
existe, **sí se recrea automáticamente** (`tmux new-session -d -s lab
|
||||||
|
-c <WORKDIR>`) — es solo recuperar el propio entorno de trabajo del
|
||||||
|
contenedor, no tocar infraestructura externa, así que es seguro
|
||||||
|
hacerlo sin intervención humana.
|
||||||
|
|
||||||
|
Todo evento (chequeo ok, falla de red, sesión recreada) queda en
|
||||||
|
`/DATA/AppData/k3d-lab-v3/tmux-host/logs/health.log` — persistente en
|
||||||
|
`/DATA`, no solo en el stdout del contenedor (que se pierde con
|
||||||
|
`docker logs` al recrearlo). Las notificaciones de Telegram reusan el
|
||||||
|
mismo bot/`chat_id` ya configurado para `scripts/lab-agent/`
|
||||||
|
(`lab-agent.env`), en vez de duplicar credenciales entre los dos
|
||||||
|
agentes del lab.
|
||||||
|
|
||||||
|
Para probar el intervalo sin esperar 30 minutos, se puede levantar el
|
||||||
|
contenedor con `-e HEALTHCHECK_INTERVAL_SEC=60` (solo para pruebas en un
|
||||||
|
contenedor descartable — nunca cambiar esto en el `tmux-host` real sin
|
||||||
|
volver a 1800 después).
|
||||||
|
|
||||||
## Qué sobrevive a qué
|
## Qué sobrevive a qué
|
||||||
|
|
||||||
| Evento | ¿Sobrevive la sesión tmux (`lab`)? | ¿Sobrevive el login de Claude Code? |
|
| 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í |
|
| 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 restart tmux-host` (reinicio del NAS) | **No al toque, pero se auto-recupera solo** — el proceso `tmux server` muere con el contenedor; `healthcheck.sh` la recrea en el próximo ciclo (máx. 30 min) sin intervención, o `lab-session.sh` la crea al instante si alguien se reconecta antes | 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`) |
|
| `docker rm` + recrear el contenedor desde cero | No, pero igual se auto-recupera sola (mismo mecanismo de arriba) | 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`) |
|
||||||
|
| Falla de red real del host/NAS | N/A | N/A — `healthcheck.sh` la detecta y notifica, pero no la corrige (fuera de su alcance) |
|
||||||
|
|
||||||
## Validación en vivo
|
## Validación en vivo
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
# ADR 0008 — Identidad visual "Navy & Coral" para ARI Shopping
|
# ADR 0008 — Identidad visual "Navy & Coral" para ARI Shopping
|
||||||
|
|
||||||
**Estado:** aceptada (implementación en curso, por sub-fases)
|
**Estado:** aceptada, con enmienda de paleta (ver §8) — sub-fases 1 a 4
|
||||||
**Fecha:** 2026-08-27
|
completas, sub-fase 5 parcial (ver §9)
|
||||||
|
**Fecha:** 2026-08-27 (enmendada 2026-09-06)
|
||||||
**Reemplaza a:** [ADR 0007](0007-identidad-visual-propia.md) (Opción 2, "Atelier cálido")
|
**Reemplaza a:** [ADR 0007](0007-identidad-visual-propia.md) (Opción 2, "Atelier cálido")
|
||||||
|
|
||||||
|
> **Nota de vigencia:** la paleta descrita en §4 ("Navy & Coral":
|
||||||
|
> marino `#122844` / coral `#D85A30` / coral claro `#F0997B`) fue la
|
||||||
|
> dirección **aprobada e implementada en las sub-fases 1-3**, pero fue
|
||||||
|
> **reemplazada el mismo día** por una paleta azul/amarillo estilo
|
||||||
|
> Walmart (rama `fix/adr0008-walmart-palette-blue-yellow`, ver §8). Los
|
||||||
|
> valores reales en producción hoy están en §8, no en §4. Se deja §4
|
||||||
|
> intacto como registro histórico de la decisión original.
|
||||||
|
|
||||||
## 1. Contexto
|
## 1. Contexto
|
||||||
|
|
||||||
Este es el tercer intento de identidad visual propia para ARI Shopping,
|
Este es el tercer intento de identidad visual propia para ARI Shopping,
|
||||||
@@ -168,3 +177,66 @@ definitivo; los alias se eliminan por completo al cerrar la sub-fase
|
|||||||
`commerce-backend`, `platform-infra`, ni CI nuevo.
|
`commerce-backend`, `platform-infra`, ni CI nuevo.
|
||||||
- `docs-portal` se actualiza con capturas/descripción del resultado
|
- `docs-portal` se actualiza con capturas/descripción del resultado
|
||||||
final una vez cada sub-fase esté validada en producción, no antes.
|
final una vez cada sub-fase esté validada en producción, no antes.
|
||||||
|
|
||||||
|
## 8. Enmienda 2026-08-27 tarde: pivote de paleta a azul/amarillo
|
||||||
|
|
||||||
|
Horas después de mergear la sub-fase 3 (product card + grid), se
|
||||||
|
mergeó `fix/adr0008-walmart-palette-blue-yellow`: la paleta "Navy &
|
||||||
|
Coral" de §4 se descartó en producción y se reemplazó por una paleta
|
||||||
|
azul/amarillo (mismo patrón "estética Walmart" ya usado como
|
||||||
|
referencia de UX en ADR 0007). Esta decisión **no quedó documentada
|
||||||
|
como enmienda en su momento** — se detecta y se registra aquí recién
|
||||||
|
el 2026-09-06, al auditar el estado real del código contra este
|
||||||
|
documento.
|
||||||
|
|
||||||
|
Valores reales en `globals.css` hoy (los nombres de token de §4 se
|
||||||
|
conservan, pero apuntan a estos valores, no a los de la tabla
|
||||||
|
original):
|
||||||
|
|
||||||
|
| Token | Valor real | Uso |
|
||||||
|
|---|---|---|
|
||||||
|
| `--color-ari-marino` | `#0055B8` (azul) | ancla: header, footer, fondo de hero, botón de búsqueda |
|
||||||
|
| `--color-ari-coral` | `#0055B8` (azul, mismo valor que marino) | CTA "Agregar al carrito", precio destacado |
|
||||||
|
| `--color-ari-coral-claro` | `#FFC220` (amarillo) | badges de oferta/urgencia, acento del isotipo, botón "yellow" del hero |
|
||||||
|
|
||||||
|
Nota: `ari-coral` y `ari-marino` son el mismo azul (`#0055B8`) — a
|
||||||
|
diferencia de la especificación original de §4, donde marino y coral
|
||||||
|
eran colores distintos. Cualquier lectura de este ADR para decisiones
|
||||||
|
de diseño futuras debe partir de esta tabla, no de §4.
|
||||||
|
|
||||||
|
El isotipo (mariposa de 4 elipses, §4) tampoco se implementó como se
|
||||||
|
describe: el logo vigente es `logo-ari-circular.svg` (rama
|
||||||
|
`adr0008-logo-circular-header`), un lockup circular distinto al
|
||||||
|
descrito en la tabla de coordenadas de §4. `logo-ari.svg` (rectangular,
|
||||||
|
el que sí sigue la spec original) quedó sin usarse en el header.
|
||||||
|
|
||||||
|
## 9. Estado real por sub-fase (auditado 2026-09-06)
|
||||||
|
|
||||||
|
Auditoría contra el código en `main`, no contra el plan de §6.
|
||||||
|
|
||||||
|
| # | Sub-fase | Estado | Evidencia |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | Tokens base + logo | ✅ completa (con la paleta enmendada en §8, no la de §4) | `globals.css`, `logo-ari.svg` inicial, luego reemplazado por circular en sub-fase posterior |
|
||||||
|
| 2 | Header + footer (incl. limpieza de §5) | ✅ completa | `navbar.tsx`, restos arcoíris (gradiente ámbar/lima, línea cian/violeta/fucsia de §5) eliminados |
|
||||||
|
| 3 | Product card + grid + badges | ✅ completa | `product-card.tsx` en tokens `ari-*` |
|
||||||
|
| 4 | Home (hero, tiles, secciones) | ✅ completa | `hero-carousel.tsx`, `category-tiles.tsx` (varias iteraciones: pastel → scrim → foto flotante → foto más grande, todas mergeadas) |
|
||||||
|
| 5 | Página de producto + drawers de carrito/wishlist | ⚠️ **parcial** | `product-purchase.tsx`/página de producto sí migraron (rama `adr0008-product-purchase-mobile-y-badge`). **`cart-drawer.tsx` y `wishlist-drawer.tsx` no tienen ningún token `ari-*` — nunca se tocaron.** No hay rama mergeada que los mencione. |
|
||||||
|
|
||||||
|
**Deuda abierta, no asumir resuelta:**
|
||||||
|
|
||||||
|
- Los alias de compatibilidad de §6 (`ari-ciruela`, `ari-cobre`,
|
||||||
|
`ari-carbon`, `ari-carbon-oscuro`, `ari-terracota-oscuro`,
|
||||||
|
`ari-hueso`) **siguen en uso real en `button.tsx`**
|
||||||
|
(`focus-visible:ring-ari-cobre/40`, `bg-ari-ciruela`,
|
||||||
|
`hover:border-ari-cobre`) — la condición de cierre de §6 ("los alias
|
||||||
|
se eliminan por completo al cerrar la sub-fase 5") no se cumplió.
|
||||||
|
Confirma que la sub-fase 5 no está cerrada, más allá de los drawers.
|
||||||
|
- Ramas mergeadas fuera del plan original de 5 sub-fases de §6, sin
|
||||||
|
enmienda que las registre: `adr0008-megamenu-mobile-overflow`,
|
||||||
|
`adr0008-club-ari-y-novedades`, `adr0008-club-ari-imagen-azul`. Son
|
||||||
|
trabajo real en producción, pero expanden el alcance de este ADR sin
|
||||||
|
quedar documentado como tal.
|
||||||
|
- `docs-portal` (este documento) es la primera actualización desde el
|
||||||
|
cierre de la sub-fase 3 — la condición de §7 ("se actualiza con
|
||||||
|
capturas/descripción... una vez cada sub-fase esté validada") no se
|
||||||
|
vino cumpliendo sub-fase por sub-fase como se planeó.
|
||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsNonRoot: false
|
runAsNonRoot: false
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.207
|
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.224
|
||||||
# El base saca TODAS las capabilities. Probado en vivo y
|
# El base saca TODAS las capabilities. Probado en vivo y
|
||||||
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
||||||
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { completeCart } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId } = await request.json();
|
||||||
|
if (!cartId) {
|
||||||
|
return Response.json({ error: "Falta cartId" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await completeCart(cartId);
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { getPseBanks } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const banks = await getPseBanks();
|
||||||
|
return Response.json({ banks });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { createPaymentCollection, createPsePaymentSession } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId, ...pse } = await request.json();
|
||||||
|
if (!cartId || !pse.bankCode || !pse.docNumber || !pse.fullName || !pse.email || !pse.phone) {
|
||||||
|
return Response.json({ error: "Faltan campos obligatorios para el pago con PSE" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const paymentCollectionId = await createPaymentCollection(cartId);
|
||||||
|
const bankUrl = await createPsePaymentSession(paymentCollectionId, pse);
|
||||||
|
return Response.json({ bankUrl });
|
||||||
|
} 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,10 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import { GoogleCallbackClient } from "@/components/account/google-callback-client";
|
||||||
|
|
||||||
|
export default function GoogleCallbackPage() {
|
||||||
|
return (
|
||||||
|
<Suspense>
|
||||||
|
<GoogleCallbackClient />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import { PseReturnClient } from "@/components/checkout/pse-return-client";
|
||||||
|
|
||||||
|
export default function PseReturnPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<PseReturnClient />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -24,3 +24,11 @@ data:
|
|||||||
# env var del plugin, no del servidor Meilisearch en si -- ver
|
# env var del plugin, no del servidor Meilisearch en si -- ver
|
||||||
# MEILI_MASTER_KEY en secrets.template.yaml).
|
# MEILI_MASTER_KEY en secrets.template.yaml).
|
||||||
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
||||||
|
|
||||||
|
# PayU LatAm (ADR 0009) -- solo URLs/config no sensible, credenciales
|
||||||
|
# reales (apiLogin/apiKey/merchantId/accountId) van en
|
||||||
|
# secrets.template.yaml. PAYU_ENV=sandbox hasta que haya credenciales
|
||||||
|
# de produccion reales.
|
||||||
|
PAYU_ENV: sandbox
|
||||||
|
PAYU_RESPONSE_URL: https://shop.cruzcloud.net/checkout/pse/return
|
||||||
|
PAYU_NOTIFY_URL: https://commerce.cruzcloud.net/hooks/payment/payu_pse
|
||||||
@@ -65,7 +65,7 @@ spec:
|
|||||||
memory: 64Mi
|
memory: 64Mi
|
||||||
|
|
||||||
- name: migrations
|
- name: migrations
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
|
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.225
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
command:
|
command:
|
||||||
- node
|
- node
|
||||||
@@ -86,7 +86,7 @@ spec:
|
|||||||
|
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.168
|
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.225
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
envFrom:
|
envFrom:
|
||||||
- configMapRef:
|
- configMapRef:
|
||||||
|
|||||||
@@ -35,6 +35,15 @@ stringData:
|
|||||||
# commerce-storefront: el subscriber de Medusa lo envía como header
|
# commerce-storefront: el subscriber de Medusa lo envía como header
|
||||||
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
||||||
REVALIDATE_SECRET: CAMBIAR
|
REVALIDATE_SECRET: CAMBIAR
|
||||||
|
|
||||||
|
# PayU LatAm (ADR 0009) -- credenciales del comercio. Mientras no exista
|
||||||
|
# cuenta real, usar las de sandbox genéricas y públicas de PayU
|
||||||
|
# (developers.payulatam.com/latam/en/docs/getting-started/test-your-solution.html),
|
||||||
|
# nunca hardcodeadas acá.
|
||||||
|
PAYU_API_LOGIN: CAMBIAR
|
||||||
|
PAYU_API_KEY: CAMBIAR
|
||||||
|
PAYU_MERCHANT_ID: CAMBIAR
|
||||||
|
PAYU_ACCOUNT_ID: CAMBIAR
|
||||||
---
|
---
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Secret
|
kind: Secret
|
||||||
|
|||||||
@@ -10,6 +10,17 @@ import { useCustomerStore } from "@/store/customer-store";
|
|||||||
|
|
||||||
type Mode = "login" | "register";
|
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 }) {
|
export function AccountDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
|
||||||
const { customer, hasHydrated, loading, error, login, register, logout } = useCustomerStore();
|
const { customer, hasHydrated, loading, error, login, register, logout } = useCustomerStore();
|
||||||
const [mode, setMode] = useState<Mode>("login");
|
const [mode, setMode] = useState<Mode>("login");
|
||||||
@@ -57,6 +68,14 @@ export function AccountDialog({ open, onOpenChange }: { open: boolean; onOpenCha
|
|||||||
{loading ? "Un momento…" : mode === "login" ? "Iniciar sesión" : "Crear cuenta"}
|
{loading ? "Un momento…" : mode === "login" ? "Iniciar sesión" : "Crear cuenta"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="mt-3 text-sm font-bold text-ari-marino hover:underline"
|
className="mt-3 text-sm font-bold text-ari-marino hover:underline"
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -352,7 +352,11 @@ export function CatalogClient({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-8 lg:grid-cols-[260px_1fr]">
|
<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-marino/5 lg:sticky lg:top-44">
|
{/* overflow-y-auto + max-h propio en lg: sticky no le da scroll
|
||||||
|
propio al contenido, y con 30+ categorias mas marca/edad/precio
|
||||||
|
el panel se pasa del viewport sin forma de llegar al resto salvo
|
||||||
|
bajando el zoom del navegador (reportado en vivo). */}
|
||||||
|
<aside className="h-fit space-y-6 overflow-y-auto rounded-lg border border-slate-100 bg-white p-6 shadow-lg shadow-ari-marino/5 lg:sticky lg:top-44 lg:max-h-[calc(100vh-13rem)]">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<strong className="flex items-center gap-2 text-lg font-black">
|
<strong className="flex items-center gap-2 text-lg font-black">
|
||||||
<SlidersHorizontal className="size-5 text-ari-coral-claro" />
|
<SlidersHorizontal className="size-5 text-ari-coral-claro" />
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ArrowLeft, MapPin, MessageCircle, Truck } from "lucide-react";
|
import { ArrowLeft, Landmark, MapPin, MessageCircle, Truck } from "lucide-react";
|
||||||
import { type FormEvent, useState } from "react";
|
import { type FormEvent, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -13,11 +13,12 @@ import { useCartStore } from "@/store/cart-store";
|
|||||||
const SELECT_CLASS =
|
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";
|
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
||||||
|
|
||||||
// ADR 0009, siguiente corte tras el carrito real: direccion + seleccion de
|
// ADR 0009: direccion + envio + pago real, todo contra el Store API real.
|
||||||
// envio contra el Store API real (mismos endpoints ya verificados en vivo
|
// El pago es PayU LatAm/PSE (modulo custom del backend, ver
|
||||||
// para las shipping options). El pago (PayU custom) todavia no existe --
|
// workloads/commerce-backend/src/modules/payu-pse) -- redirige al banco
|
||||||
// el ultimo paso sigue siendo WhatsApp, ahora con el pedido completo
|
// del comprador, la confirmacion real llega despues via webhook async
|
||||||
// (direccion, envio, total real) en vez de solo la lista de productos.
|
// (nunca por esta pantalla). WhatsApp queda como respaldo manual si la
|
||||||
|
// iniciacion del pago falla, ya no como camino principal.
|
||||||
|
|
||||||
interface ShippingOption {
|
interface ShippingOption {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -25,7 +26,12 @@ interface ShippingOption {
|
|||||||
amount: number;
|
amount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Step = "address" | "shipping" | "review";
|
interface PseBank {
|
||||||
|
pseCode: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Step = "address" | "shipping" | "payment";
|
||||||
|
|
||||||
async function postJson(url: string, body: unknown) {
|
async function postJson(url: string, body: unknown) {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
@@ -60,6 +66,11 @@ export function CheckoutClient() {
|
|||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [banks, setBanks] = useState<PseBank[]>([]);
|
||||||
|
const [bankCode, setBankCode] = useState("");
|
||||||
|
const [userType, setUserType] = useState<"N" | "J">("N");
|
||||||
|
const [docType, setDocType] = useState<"CC" | "CE" | "NIT" | "TI" | "PP">("CC");
|
||||||
|
const [docNumber, setDocNumber] = useState("");
|
||||||
|
|
||||||
const itemsSubtotal = items.reduce((sum, item) => sum + (item.product.price ?? 0) * item.quantity, 0);
|
const itemsSubtotal = items.reduce((sum, item) => sum + (item.product.price ?? 0) * item.quantity, 0);
|
||||||
const currency = items[0]?.product.currency;
|
const currency = items[0]?.product.currency;
|
||||||
@@ -103,7 +114,12 @@ export function CheckoutClient() {
|
|||||||
if (cart.error) throw new Error(cart.error);
|
if (cart.error) throw new Error(cart.error);
|
||||||
setShippingTotal(cart.shippingTotal ?? 0);
|
setShippingTotal(cart.shippingTotal ?? 0);
|
||||||
setTotal(cart.total ?? itemsSubtotal);
|
setTotal(cart.total ?? itemsSubtotal);
|
||||||
setStep("review");
|
const banksResponse = await fetch("/api/cart/payment/banks");
|
||||||
|
const banksData = await banksResponse.json();
|
||||||
|
const bankList: PseBank[] = banksData.banks ?? [];
|
||||||
|
setBanks(bankList);
|
||||||
|
setBankCode(bankList[0]?.pseCode ?? "");
|
||||||
|
setStep("payment");
|
||||||
} catch (submitError) {
|
} catch (submitError) {
|
||||||
setError((submitError as Error).message);
|
setError((submitError as Error).message);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -111,6 +127,38 @@ export function CheckoutClient() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function submitPayment(event: FormEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!cartId || !bankCode || !docNumber || !selectedCiudad || !selectedDepartamento) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const session = await postJson("/api/cart/payment/session", {
|
||||||
|
cartId,
|
||||||
|
bankCode,
|
||||||
|
userType,
|
||||||
|
docType,
|
||||||
|
docNumber,
|
||||||
|
fullName: `${form.firstName} ${form.lastName}`.trim(),
|
||||||
|
email: form.email,
|
||||||
|
phone: form.phone,
|
||||||
|
address: form.address1,
|
||||||
|
city: selectedCiudad.name,
|
||||||
|
state: selectedDepartamento.name,
|
||||||
|
});
|
||||||
|
if (session.error) throw new Error(session.error);
|
||||||
|
const completion = await postJson("/api/cart/complete", { cartId });
|
||||||
|
if (completion.error) throw new Error(completion.error);
|
||||||
|
// Navegacion completa, no iframe -- asi lo exige PayU para el
|
||||||
|
// flujo de PSE. La confirmacion real llega despues via webhook,
|
||||||
|
// esta pagina nunca vuelve a cargar sola.
|
||||||
|
window.location.href = session.bankUrl;
|
||||||
|
} catch (submitError) {
|
||||||
|
setError((submitError as Error).message);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function continueOnWhatsApp() {
|
function continueOnWhatsApp() {
|
||||||
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
||||||
const message = `Hola Ari Shopping 👋\nQuiero confirmar mi pedido:\n\n${lines}\n\nSubtotal: ${formatMoney(itemsSubtotal, currency)}\nEnvío: ${formatMoney(shippingTotal, currency)}\nTotal: ${formatMoney(total, currency)}\n\nNombre: ${form.firstName} ${form.lastName}\nDirección: ${form.address1}, ${selectedCiudad?.name ?? ""}${selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}\nTeléfono: ${form.phone}`;
|
const message = `Hola Ari Shopping 👋\nQuiero confirmar mi pedido:\n\n${lines}\n\nSubtotal: ${formatMoney(itemsSubtotal, currency)}\nEnvío: ${formatMoney(shippingTotal, currency)}\nTotal: ${formatMoney(total, currency)}\n\nNombre: ${form.firstName} ${form.lastName}\nDirección: ${form.address1}, ${selectedCiudad?.name ?? ""}${selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}\nTeléfono: ${form.phone}`;
|
||||||
@@ -192,17 +240,55 @@ export function CheckoutClient() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === "review" && (
|
{step === "payment" && (
|
||||||
<div className="mt-8 space-y-4">
|
<form onSubmit={submitPayment} className="mt-8 space-y-4">
|
||||||
<div className="rounded-2xl border border-slate-200 p-5">
|
<div className="rounded-2xl border border-slate-200 p-5">
|
||||||
<p className="text-xs font-black uppercase tracking-wide text-slate-400">Entrega</p>
|
<p className="text-xs font-black uppercase tracking-wide text-slate-400">Entrega</p>
|
||||||
<p className="mt-1 font-bold">{form.firstName} {form.lastName}</p>
|
<p className="mt-1 font-bold">{form.firstName} {form.lastName}</p>
|
||||||
<p className="text-sm text-slate-500">{form.address1}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</p>
|
<p className="text-sm text-slate-500">{form.address1}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</p>
|
||||||
<p className="text-sm text-slate-500">{form.phone}</p>
|
<p className="text-sm text-slate-500">{form.phone}</p>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-slate-500">El pago en línea todavía no está disponible — confirmamos tu pedido por WhatsApp con estos datos.</p>
|
|
||||||
<Button variant="primary" size="lg" className="w-full" onClick={continueOnWhatsApp}><MessageCircle className="size-5" />Confirmar por WhatsApp</Button>
|
<p className="flex items-center gap-2 text-sm font-bold text-slate-700"><Landmark className="size-4" />Paga con PSE (transferencia desde tu banco)</p>
|
||||||
|
|
||||||
|
{banks.length > 0 ? (
|
||||||
|
<select required value={bankCode} onChange={(event) => setBankCode(event.target.value)} className={SELECT_CLASS}>
|
||||||
|
{banks.map((bank) => <option key={bank.pseCode} value={bank.pseCode}>{bank.description}</option>)}
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<p className="rounded-2xl bg-yellow-50 p-3 text-xs font-bold leading-5 text-yellow-800">No pudimos cargar la lista de bancos — probá de nuevo en un momento, o confirmá tu pedido por WhatsApp abajo.</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex gap-4 text-sm font-bold">
|
||||||
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "N"} onChange={() => setUserType("N")} />Persona natural</label>
|
||||||
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "J"} onChange={() => setUserType("J")} />Persona jurídica</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
value={docType}
|
||||||
|
onChange={(event) => setDocType(event.target.value as typeof docType)}
|
||||||
|
className={SELECT_CLASS}
|
||||||
|
>
|
||||||
|
<option value="CC">Cédula de ciudadanía</option>
|
||||||
|
<option value="CE">Cédula de extranjería</option>
|
||||||
|
<option value="TI">Tarjeta de identidad</option>
|
||||||
|
<option value="PP">Pasaporte</option>
|
||||||
|
<option value="NIT">NIT</option>
|
||||||
|
</select>
|
||||||
|
<Input placeholder="Número de documento" required value={docNumber} onChange={(event) => setDocNumber(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 || banks.length === 0}>{loading ? "Redirigiendo a tu banco…" : "Pagar con PSE"}</Button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 text-xs font-bold uppercase tracking-wide text-slate-400">
|
||||||
|
<span className="h-px flex-1 bg-slate-200" />¿Prefieres otra vía?<span className="h-px flex-1 bg-slate-200" />
|
||||||
|
</div>
|
||||||
|
<Button type="button" variant="outline" size="lg" className="w-full" onClick={continueOnWhatsApp}><MessageCircle className="size-5" />Confirmar por WhatsApp</Button>
|
||||||
|
</form>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -219,8 +305,8 @@ export function CheckoutClient() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="mt-5 space-y-2 border-t border-slate-100 pt-4 text-sm">
|
<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>
|
<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>}
|
{step === "payment" && <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 className="flex justify-between text-base"><span className="font-black">Total</span><span className="font-black">{formatMoney(step === "payment" ? total : itemsSubtotal, currency)}</span></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Clock } from "lucide-react";
|
||||||
|
import { useSearchParams } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
// PayU redirige aca despues de que el comprador paga en su banco -- esto
|
||||||
|
// NO confirma el pago. Los parametros de esta URL son solo informativos;
|
||||||
|
// el estado real y definitivo llega por el webhook async de PayU al
|
||||||
|
// backend (getWebhookActionAndData en el modulo payu-pse), nunca por
|
||||||
|
// esta pantalla. Por eso el mensaje nunca afirma exito, solo que
|
||||||
|
// estamos esperando la confirmacion.
|
||||||
|
export function PseReturnClient() {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const referenceCode = searchParams.get("referenceCode") ?? searchParams.get("reference_sale");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg px-4 py-24 text-center">
|
||||||
|
<Clock className="mx-auto size-12 text-ari-marino" />
|
||||||
|
<h1 className="mt-6 text-2xl font-black">Estamos confirmando tu pago</h1>
|
||||||
|
<p className="mt-3 text-slate-500">
|
||||||
|
Tu banco ya procesó la transferencia. PayU nos avisa en unos minutos si quedó aprobada — te llegará la confirmación por correo.
|
||||||
|
{referenceCode && (
|
||||||
|
<>
|
||||||
|
{" "}Tu número de referencia es <strong>{referenceCode}</strong>.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<p className="mt-3 text-sm text-slate-400">
|
||||||
|
Si después de un rato no ves la confirmación, escribinos por WhatsApp con este número de referencia.
|
||||||
|
</p>
|
||||||
|
<Button asChild variant="primary" className="mt-8">
|
||||||
|
<Link href="/catalog">Volver al catálogo</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -199,6 +199,24 @@ function CategoryNavBar({
|
|||||||
function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActive: (name: string) => boolean }) {
|
function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActive: (name: string) => boolean }) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
const cancelClose = () => {
|
||||||
|
if (closeTimer.current) {
|
||||||
|
clearTimeout(closeTimer.current);
|
||||||
|
closeTimer.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Delay corto en vez de cerrar al toque: aunque el gap entre el boton y
|
||||||
|
// el panel ya se elimino (antes era la causa real -- el panel es
|
||||||
|
// absolute y no suma a la altura del contenedor, asi que un mt-1 ahi
|
||||||
|
// dejaba una franja muerta que cerraba el menu a mitad de camino,
|
||||||
|
// reportado en vivo), este margen extra tolera movimientos rapidos o en
|
||||||
|
// diagonal cerca del borde sin reabrir nada raro.
|
||||||
|
const scheduleClose = () => {
|
||||||
|
cancelClose();
|
||||||
|
closeTimer.current = setTimeout(() => setOpen(false), 200);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
@@ -216,8 +234,15 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
|||||||
};
|
};
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => () => cancelClose(), []);
|
||||||
|
|
||||||
|
const openNow = () => {
|
||||||
|
cancelClose();
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={containerRef} className="shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
|
<div ref={containerRef} className="shrink-0" onMouseEnter={openNow} onMouseLeave={scheduleClose}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setOpen((value) => !value)}
|
onClick={() => setOpen((value) => !value)}
|
||||||
@@ -231,7 +256,7 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
{open && (
|
{open && (
|
||||||
<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="absolute left-0 top-full z-50 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">
|
<div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-6">
|
||||||
{tree.map((root) => (
|
{tree.map((root) => (
|
||||||
<div key={root.id}>
|
<div key={root.id}>
|
||||||
|
|||||||
@@ -7,5 +7,19 @@ import { useCartStore } from "@/store/cart-store";
|
|||||||
|
|
||||||
export function MobileAddToCart({ product }: { product: Product }) {
|
export function MobileAddToCart({ product }: { product: Product }) {
|
||||||
const addItem = useCartStore((state) => state.addItem);
|
const addItem = useCartStore((state) => state.addItem);
|
||||||
return <div className="fixed inset-x-0 bottom-0 z-40 border-t border-slate-200 bg-white/95 p-3 shadow-2xl backdrop-blur lg:hidden"><Button variant="primary" size="lg" className="w-full" onClick={() => addItem(product, product.variants[0]?.id)}><ShoppingBag />Añadir al carrito</Button></div>;
|
const outOfStock = product.variants[0]?.available === false;
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-x-0 bottom-0 z-40 border-t border-slate-200 bg-white/95 p-3 shadow-2xl backdrop-blur lg:hidden">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="lg"
|
||||||
|
className="w-full"
|
||||||
|
disabled={outOfStock}
|
||||||
|
onClick={() => addItem(product, product.variants[0]?.id)}
|
||||||
|
>
|
||||||
|
<ShoppingBag />
|
||||||
|
{outOfStock ? "Agotado" : "Añadir al carrito"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,9 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
|||||||
|
|
||||||
const [selectedVariantId, setSelectedVariantId] = useState(product.variants[0]?.id);
|
const [selectedVariantId, setSelectedVariantId] = useState(product.variants[0]?.id);
|
||||||
const selectedVariant = product.variants.find((variant) => variant.id === selectedVariantId) ?? product.variants[0];
|
const selectedVariant = product.variants.find((variant) => variant.id === selectedVariantId) ?? product.variants[0];
|
||||||
|
const outOfStock = selectedVariant?.available === false;
|
||||||
const lowStock =
|
const lowStock =
|
||||||
|
!outOfStock &&
|
||||||
selectedVariant?.inventoryQuantity !== null &&
|
selectedVariant?.inventoryQuantity !== null &&
|
||||||
selectedVariant?.inventoryQuantity !== undefined &&
|
selectedVariant?.inventoryQuantity !== undefined &&
|
||||||
selectedVariant.inventoryQuantity > 0 &&
|
selectedVariant.inventoryQuantity > 0 &&
|
||||||
@@ -36,7 +38,8 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
|||||||
<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">
|
<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">
|
<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>
|
<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-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>
|
<div className="absolute left-3 top-3 flex gap-2">{outOfStock && <Badge className="bg-rose-600 text-white">Agotado</Badge>}{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>
|
||||||
|
{outOfStock && <div className="pointer-events-none absolute inset-0 bg-white/40" />}
|
||||||
<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>
|
<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>
|
||||||
<div className="flex flex-1 flex-col space-y-3 p-5">
|
<div className="flex flex-1 flex-col space-y-3 p-5">
|
||||||
@@ -67,12 +70,15 @@ export function ProductCard({ product, priority = false }: { product: Product; p
|
|||||||
{lowStock !== null && (
|
{lowStock !== null && (
|
||||||
<span className="flex items-center gap-1.5 text-xs font-bold text-amber-600"><TriangleAlert className="size-3.5" />Quedan {lowStock}</span>
|
<span className="flex items-center gap-1.5 text-xs font-bold text-amber-600"><TriangleAlert className="size-3.5" />Quedan {lowStock}</span>
|
||||||
)}
|
)}
|
||||||
|
{outOfStock && (
|
||||||
|
<span className="flex items-center gap-1.5 text-xs font-bold text-rose-600"><TriangleAlert className="size-3.5" />Sin stock</span>
|
||||||
|
)}
|
||||||
<div className="mt-auto flex items-center justify-between gap-3 pt-1">
|
<div className="mt-auto flex items-center justify-between gap-3 pt-1">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
{product.compareAtPrice && <span className="text-xs font-bold text-slate-400 line-through">{formatMoney(product.compareAtPrice, product.currency)}</span>}
|
{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-marino">{formatMoney(product.price, product.currency)}</strong>
|
<strong className="font-display text-base font-bold text-ari-marino">{formatMoney(product.price, product.currency)}</strong>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="primary" size="sm" onClick={() => addItem(product, selectedVariantId)}><ShoppingBag className="size-4" />Agregar</Button>
|
<Button variant="primary" size="sm" disabled={outOfStock} onClick={() => addItem(product, selectedVariantId)}><ShoppingBag className="size-4" />{outOfStock ? "Agotado" : "Agregar"}</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|||||||
@@ -2,19 +2,36 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { Maximize2, Minus, Plus, RotateCcw, ZoomIn } from "lucide-react";
|
import { Maximize2, Minus, Plus, RotateCcw, ZoomIn } from "lucide-react";
|
||||||
import { PointerEvent, WheelEvent, useRef, useState } from "react";
|
import { MouseEvent, PointerEvent, WheelEvent, useRef, useState } from "react";
|
||||||
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
||||||
|
|
||||||
interface Offset { x: number; y: number }
|
interface Offset { x: number; y: number }
|
||||||
interface DragState { pointerId: number; startX: number; startY: number; originX: number; originY: number }
|
interface DragState { pointerId: number; startX: number; startY: number; originX: number; originY: number }
|
||||||
|
interface HoverZoomOrigin { x: number; y: number }
|
||||||
|
|
||||||
|
// Zoom automatico al pasar el cursor (estilo lupa clasico de e-commerce)
|
||||||
|
// sobre la imagen principal -- solo mouse (mousemove no dispara de forma
|
||||||
|
// continua en touch, asi que en mobile simplemente no aparece el efecto,
|
||||||
|
// sin romper nada). Independiente del zoom interactivo del modal
|
||||||
|
// (click -> Dialog con scale/drag), que sigue igual.
|
||||||
|
const HOVER_ZOOM_SCALE = 2.2;
|
||||||
|
|
||||||
export function ProductGallery({ images, name }: { images: string[]; name: string }) {
|
export function ProductGallery({ images, name }: { images: string[]; name: string }) {
|
||||||
const [selected, setSelected] = useState(images[0] ?? "");
|
const [selected, setSelected] = useState(images[0] ?? "");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [scale, setScale] = useState(1);
|
const [scale, setScale] = useState(1);
|
||||||
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
|
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
|
||||||
|
const [hoverZoom, setHoverZoom] = useState<HoverZoomOrigin | null>(null);
|
||||||
const drag = useRef<DragState | null>(null);
|
const drag = useRef<DragState | null>(null);
|
||||||
|
|
||||||
|
const trackHoverZoom = (event: MouseEvent<HTMLButtonElement>) => {
|
||||||
|
const rect = event.currentTarget.getBoundingClientRect();
|
||||||
|
setHoverZoom({
|
||||||
|
x: ((event.clientX - rect.left) / rect.width) * 100,
|
||||||
|
y: ((event.clientY - rect.top) / rect.height) * 100,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const applyScale = (next: number) => {
|
const applyScale = (next: number) => {
|
||||||
const value = Math.min(3, Math.max(1, Number(next.toFixed(2))));
|
const value = Math.min(3, Math.max(1, Number(next.toFixed(2))));
|
||||||
setScale(value);
|
setScale(value);
|
||||||
@@ -44,8 +61,24 @@ export function ProductGallery({ images, name }: { images: string[]; name: strin
|
|||||||
</div>
|
</div>
|
||||||
<Dialog open={open} onOpenChange={changeOpen}>
|
<Dialog open={open} onOpenChange={changeOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<button type="button" className="group relative order-1 aspect-square overflow-hidden rounded-[2rem] bg-slate-50 lg:order-2">
|
<button
|
||||||
<Image src={selected} alt={name} fill priority sizes="(max-width: 1024px) 100vw, 50vw" className="object-cover transition duration-500 group-hover:scale-[1.03]" />
|
type="button"
|
||||||
|
className="group relative order-1 aspect-square cursor-zoom-in overflow-hidden rounded-[2rem] bg-slate-50 lg:order-2"
|
||||||
|
onMouseMove={trackHoverZoom}
|
||||||
|
onMouseLeave={() => setHoverZoom(null)}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
src={selected}
|
||||||
|
alt={name}
|
||||||
|
fill
|
||||||
|
priority
|
||||||
|
sizes="(max-width: 1024px) 100vw, 50vw"
|
||||||
|
className="object-cover transition-transform duration-150 ease-out"
|
||||||
|
style={{
|
||||||
|
transform: `scale(${hoverZoom ? HOVER_ZOOM_SCALE : 1})`,
|
||||||
|
transformOrigin: hoverZoom ? `${hoverZoom.x}% ${hoverZoom.y}%` : "center",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<span className="absolute bottom-5 right-5 inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-xs font-black shadow-xl"><ZoomIn className="size-4" />Zoom interactivo</span>
|
<span className="absolute bottom-5 right-5 inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-xs font-black shadow-xl"><ZoomIn className="size-4" />Zoom interactivo</span>
|
||||||
</button>
|
</button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CheckCircle2, ShoppingBag, TriangleAlert, Truck } from "lucide-react";
|
import { CheckCircle2, ShoppingBag, TriangleAlert, Truck, XCircle } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import type { Product } from "@/lib/headless/types";
|
import type { Product } from "@/lib/headless/types";
|
||||||
@@ -11,12 +11,68 @@ export function ProductPurchase({ product }: { product: Product }) {
|
|||||||
const [variantId, setVariantId] = useState(product.variants[0]?.id);
|
const [variantId, setVariantId] = useState(product.variants[0]?.id);
|
||||||
const addItem = useCartStore((state) => state.addItem);
|
const addItem = useCartStore((state) => state.addItem);
|
||||||
const selectedVariant = product.variants.find((variant) => variant.id === variantId) ?? product.variants[0];
|
const selectedVariant = product.variants.find((variant) => variant.id === variantId) ?? product.variants[0];
|
||||||
|
const outOfStock = selectedVariant?.available === false;
|
||||||
const lowStock =
|
const lowStock =
|
||||||
|
!outOfStock &&
|
||||||
selectedVariant?.inventoryQuantity !== null &&
|
selectedVariant?.inventoryQuantity !== null &&
|
||||||
selectedVariant?.inventoryQuantity !== undefined &&
|
selectedVariant?.inventoryQuantity !== undefined &&
|
||||||
selectedVariant.inventoryQuantity > 0 &&
|
selectedVariant.inventoryQuantity > 0 &&
|
||||||
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
selectedVariant.inventoryQuantity <= LOW_STOCK_THRESHOLD
|
||||||
? selectedVariant.inventoryQuantity
|
? selectedVariant.inventoryQuantity
|
||||||
: null;
|
: null;
|
||||||
return <div><div className="mb-5 flex flex-wrap gap-2">{product.variants.map((variant) => <button key={variant.id} onClick={() => setVariantId(variant.id)} className={`rounded-full border px-4 py-2 text-sm font-bold ${variantId === variant.id ? "border-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>;
|
|
||||||
|
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.available === false ? "opacity-40" : ""}`}
|
||||||
|
>
|
||||||
|
{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"
|
||||||
|
disabled={outOfStock}
|
||||||
|
onClick={() => addItem(product, variantId)}
|
||||||
|
>
|
||||||
|
<ShoppingBag />
|
||||||
|
{outOfStock ? "Agotado" : "Añadir al carrito"}
|
||||||
|
</Button>
|
||||||
|
<div className="mt-5 grid gap-3 rounded-2xl bg-slate-50 p-4 text-sm">
|
||||||
|
{outOfStock ? (
|
||||||
|
<span className="flex items-center gap-2 font-bold text-rose-600">
|
||||||
|
<XCircle className="size-4" />
|
||||||
|
Agotado
|
||||||
|
</span>
|
||||||
|
) : 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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsUser: 1001
|
runAsUser: 1001
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.213
|
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.226
|
||||||
env:
|
env:
|
||||||
- name: HEADLESS_PROVIDER
|
- name: HEADLESS_PROVIDER
|
||||||
value: medusa
|
value: medusa
|
||||||
|
|||||||
@@ -119,7 +119,9 @@ function mapCart(cart: MedusaCart): CartSummary {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function medusaCartFetch(
|
// Exportado para medusa-payment.ts (mismo backend, mismo criterio de
|
||||||
|
// no-store/x-publishable-api-key -- evita duplicar el fetch helper).
|
||||||
|
export async function medusaCartFetch(
|
||||||
path: string,
|
path: string,
|
||||||
init?: { method?: string; body?: unknown },
|
init?: { method?: string; body?: unknown },
|
||||||
): Promise<Record<string, unknown>> {
|
): Promise<Record<string, unknown>> {
|
||||||
|
|||||||
@@ -87,6 +87,56 @@ export async function loginCustomer(email: string, password: string): Promise<Cu
|
|||||||
return getCurrentCustomer(data.token as string);
|
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(
|
export async function registerCustomer(
|
||||||
email: string,
|
email: string,
|
||||||
password: string,
|
password: string,
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// ADR 0009: pago real via PayU LatAm (PSE), modulo custom del backend
|
||||||
|
// (workloads/commerce-backend/src/modules/payu-pse). Archivo separado de
|
||||||
|
// medusa-cart.ts por el mismo motivo que ese archivo esta separado de
|
||||||
|
// medusa.ts -- reutiliza su mismo fetch helper (medusaCartFetch), no
|
||||||
|
// duplica la logica de headers/no-store.
|
||||||
|
import { medusaCartFetch } from "./medusa-cart";
|
||||||
|
|
||||||
|
export interface PseBank {
|
||||||
|
pseCode: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PseUserType = "N" | "J";
|
||||||
|
export type PseDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
|
||||||
|
export interface PsePaymentInput {
|
||||||
|
bankCode: string;
|
||||||
|
userType: PseUserType;
|
||||||
|
docType: PseDocType;
|
||||||
|
docNumber: string;
|
||||||
|
fullName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
address: string;
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "pp_{identifier}_{id}" -- convencion de Medusa, confirmada contra el
|
||||||
|
// codigo fuente de @medusajs/payment (identifier "payu" + id "pse" en
|
||||||
|
// medusa-config.ts).
|
||||||
|
const PSE_PROVIDER_ID = "pp_payu_pse";
|
||||||
|
|
||||||
|
export async function getPseBanks(): Promise<PseBank[]> {
|
||||||
|
const data = await medusaCartFetch("/store/payments/pse-banks");
|
||||||
|
const banks = (data.banks as Array<{ pseCode?: string; description?: string }> | undefined) ?? [];
|
||||||
|
return banks
|
||||||
|
.filter((bank): bank is { pseCode: string; description: string } => Boolean(bank.pseCode && bank.description))
|
||||||
|
.map((bank) => ({ pseCode: bank.pseCode, description: bank.description }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPaymentCollection(cartId: string): Promise<string> {
|
||||||
|
const data = await medusaCartFetch("/store/payment-collections", {
|
||||||
|
method: "POST",
|
||||||
|
body: { cart_id: cartId },
|
||||||
|
});
|
||||||
|
const collection = data.payment_collection as { id: string };
|
||||||
|
return collection.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPsePaymentSession(paymentCollectionId: string, input: PsePaymentInput): Promise<string> {
|
||||||
|
const data = await medusaCartFetch(`/store/payment-collections/${paymentCollectionId}/payment-sessions`, {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
provider_id: PSE_PROVIDER_ID,
|
||||||
|
data: {
|
||||||
|
bank_code: input.bankCode,
|
||||||
|
user_type: input.userType,
|
||||||
|
doc_type: input.docType,
|
||||||
|
doc_number: input.docNumber,
|
||||||
|
full_name: input.fullName,
|
||||||
|
email: input.email,
|
||||||
|
phone: input.phone,
|
||||||
|
address: input.address,
|
||||||
|
city: input.city,
|
||||||
|
state: input.state,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const collection = data.payment_collection as {
|
||||||
|
payment_sessions?: Array<{ provider_id: string; data?: { bank_url?: string } }>;
|
||||||
|
};
|
||||||
|
const session = collection.payment_sessions?.find((paymentSession) => paymentSession.provider_id === PSE_PROVIDER_ID);
|
||||||
|
const bankUrl = session?.data?.bank_url;
|
||||||
|
if (!bankUrl) {
|
||||||
|
throw new Error("PayU no devolvió la URL del banco para completar el pago.");
|
||||||
|
}
|
||||||
|
return bankUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// El carrito se completa (orden creada en estado "awaiting") ANTES de
|
||||||
|
// redirigir al banco -- authorizePayment del modulo PSE devuelve
|
||||||
|
// "pending_authorization" a proposito, que es justo el mecanismo de
|
||||||
|
// Medusa para esto (ver AbstractPaymentProvider). La confirmacion real
|
||||||
|
// llega despues via el webhook nativo de Medusa, no por esta llamada.
|
||||||
|
export async function completeCart(cartId: string): Promise<void> {
|
||||||
|
const data = await medusaCartFetch(`/store/carts/${cartId}/complete`, { method: "POST" });
|
||||||
|
if (data.type === "cart") {
|
||||||
|
const error = (data as { error?: { message?: string } }).error;
|
||||||
|
throw new Error(error?.message || "No se pudo completar el pedido.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ interface CustomerState {
|
|||||||
setHasHydrated: (value: boolean) => void;
|
setHasHydrated: (value: boolean) => void;
|
||||||
register: (email: string, password: string, firstName: string, lastName: string) => Promise<boolean>;
|
register: (email: string, password: string, firstName: string, lastName: string) => Promise<boolean>;
|
||||||
login: (email: string, password: string) => Promise<boolean>;
|
login: (email: string, password: string) => Promise<boolean>;
|
||||||
|
loginWithGoogle: (code: string, state: string) => Promise<boolean>;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
syncCustomer: () => Promise<void>;
|
syncCustomer: () => Promise<void>;
|
||||||
}
|
}
|
||||||
@@ -77,6 +78,17 @@ export const useCustomerStore = create<CustomerState>()(
|
|||||||
return true;
|
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 }),
|
logout: () => set({ token: null, customer: null, error: null }),
|
||||||
|
|
||||||
// El token guardado en localStorage puede llevar dias o haber sido
|
// El token guardado en localStorage puede llevar dias o haber sido
|
||||||
|
|||||||
Reference in new issue
Block a user