Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d543f5eb1 | ||
|
|
8fd0514e76 | ||
|
|
1cde29b344 | ||
|
|
8517102b63 |
No files matched your search
@@ -14,6 +14,7 @@ type RowResult = {
|
||||
row: number;
|
||||
title: string;
|
||||
ok: boolean;
|
||||
action?: "created" | "updated";
|
||||
error?: string;
|
||||
};
|
||||
|
||||
@@ -91,9 +92,11 @@ const ProductImportPanel = () => {
|
||||
<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. <code>categoria</code>/<code>coleccion</code> deben
|
||||
escribirse igual que en la tienda o se dejan vacías. Cada foto se descarga y se guarda en el almacenamiento
|
||||
propio de la tienda (no queda enlazada al sitio de origen).
|
||||
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>
|
||||
|
||||
@@ -122,7 +125,7 @@ const ProductImportPanel = () => {
|
||||
<td className="py-2">{result.title}</td>
|
||||
<td className="py-2">
|
||||
{result.ok ? (
|
||||
<Badge color="green">Importado</Badge>
|
||||
<Badge color="green">{result.action === "updated" ? "Actualizado (ya existía)" : "Importado"}</Badge>
|
||||
) : (
|
||||
<span className="text-rose-600">{result.error}</span>
|
||||
)}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
createInventoryItemsWorkflow,
|
||||
createProductCategoriesWorkflow,
|
||||
createProductsWorkflow,
|
||||
updateProductsWorkflow,
|
||||
uploadFilesWorkflow,
|
||||
} from "@medusajs/medusa/core-flows";
|
||||
import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
||||
@@ -31,6 +32,18 @@ import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
||||
// 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).
|
||||
@@ -61,6 +74,7 @@ type RowResult = {
|
||||
row: number;
|
||||
title: string;
|
||||
ok: boolean;
|
||||
action?: "created" | "updated";
|
||||
error?: string;
|
||||
};
|
||||
|
||||
@@ -150,7 +164,7 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
||||
const salesChannelService = req.scope.resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL);
|
||||
const productService = req.scope.resolve<IProductModuleService>(Modules.PRODUCT);
|
||||
|
||||
const [locations, shippingProfiles, salesChannels, categories, collections] = await Promise.all([
|
||||
const [locations, shippingProfiles, salesChannels, categories, collections, existingProducts] = await Promise.all([
|
||||
stockLocationService.listStockLocations({}),
|
||||
fulfillmentService.listShippingProfiles({}),
|
||||
salesChannelService.listSalesChannels({}),
|
||||
@@ -161,6 +175,7 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
||||
// 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;
|
||||
@@ -180,6 +195,9 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
||||
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[] = [];
|
||||
|
||||
@@ -210,6 +228,23 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
||||
},
|
||||
});
|
||||
|
||||
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: {
|
||||
@@ -283,7 +318,7 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
||||
},
|
||||
});
|
||||
|
||||
results.push({ row: rowNumber, title, ok: true });
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -2,19 +2,36 @@
|
||||
|
||||
import Image from "next/image";
|
||||
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";
|
||||
|
||||
interface Offset { x: number; y: 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 }) {
|
||||
const [selected, setSelected] = useState(images[0] ?? "");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [scale, setScale] = useState(1);
|
||||
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
|
||||
const [hoverZoom, setHoverZoom] = useState<HoverZoomOrigin | 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 value = Math.min(3, Math.max(1, Number(next.toFixed(2))));
|
||||
setScale(value);
|
||||
@@ -44,8 +61,24 @@ export function ProductGallery({ images, name }: { images: string[]; name: strin
|
||||
</div>
|
||||
<Dialog open={open} onOpenChange={changeOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<button type="button" className="group relative order-1 aspect-square overflow-hidden rounded-[2rem] bg-slate-50 lg:order-2">
|
||||
<Image src={selected} alt={name} fill priority sizes="(max-width: 1024px) 100vw, 50vw" className="object-cover transition duration-500 group-hover:scale-[1.03]" />
|
||||
<button
|
||||
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>
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
|
||||
Reference in new issue
Block a user