feat(admin): redesign product form modal (Atelier des Récoltes)

Replace the basic add/edit product modal with an editorial two-column
layout featuring Fraunces display serif, IBM Plex Mono section labels,
a custom drop zone, visual type cards, and pill toggles. Add a brand
selector visible only to platform admins to fix the 'Brand ID is
required' / RLS error when creating products without an assigned brand.

- Add ProductFormModal with two-column layout (image hero + form)
- Add Fraunces / IBM Plex Mono / Inter Tight via next/font/google
- Add atelier-* design system to globals.css
- Wire brand picker through page server component -> client
- Convert ProductsClient image handling to callback shape
- Move all submit/validation/upload logic into the new modal
This commit is contained in:
2026-06-04 19:49:03 +00:00
parent 8bca9e86b1
commit 69767eb250
4 changed files with 1477 additions and 394 deletions
+673
View File
@@ -0,0 +1,673 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { createPortal } from "react-dom";
export type ProductFormModalProps = {
open: boolean;
mode: "add" | "edit";
onClose: () => void;
onSubmit: (values: ProductFormValues) => Promise<{ success: boolean; error?: string }>;
/** Defaults / initial values (edit mode passes the current product) */
initial?: Partial<ProductFormValues>;
/** List of selectable brands (only shown to platform admins) */
brands?: { id: string; name: string }[];
/** When true the brand picker is hidden and the admin's brand is used */
lockBrand?: boolean;
/** Hard-locked brand id (for brand_admin / store_employee) */
lockedBrandId?: string;
/** Pre-uploaded image URL (edit mode) */
initialImageUrl?: string | null;
/** Server action: upload a file and return the public URL */
onUploadImage: (file: File) => Promise<{ success: boolean; imageUrl?: string; error?: string }>;
};
export type ProductFormValues = {
name: string;
description: string;
price: string;
type: "pickup" | "wholesale" | "subscription";
brand_id: string;
active: boolean;
is_taxable: boolean;
image_url: string | null;
};
const TYPE_OPTIONS: Array<{
value: ProductFormValues["type"];
label: string;
italic: string;
icon: React.ReactNode;
}> = [
{
value: "pickup",
label: "Pickup",
italic: "Farm & stops",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M3 9l1.5-4h15L21 9" />
<path d="M3 9v11a1 1 0 001 1h16a1 1 0 001-1V9" />
<path d="M3 9h18" />
<path d="M9 14h6" />
</svg>
),
},
{
value: "wholesale",
label: "Wholesale",
italic: "B2B portal",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M3 7h18l-2 12H5L3 7z" />
<path d="M8 7V5a4 4 0 018 0v2" />
</svg>
),
},
{
value: "subscription",
label: "Subscription",
italic: "Recurring",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M21 12a9 9 0 11-3-6.7" />
<path d="M21 4v5h-5" />
</svg>
),
},
];
export default function ProductFormModal({
open,
mode,
onClose,
onSubmit,
initial,
brands = [],
lockBrand = false,
lockedBrandId = "",
initialImageUrl = null,
onUploadImage,
}: ProductFormModalProps) {
// Form state
const [name, setName] = useState(initial?.name ?? "");
const [description, setDescription] = useState(initial?.description ?? "");
const [price, setPrice] = useState(initial?.price ?? "");
const [type, setType] = useState<ProductFormValues["type"]>(initial?.type ?? "pickup");
const [brandId, setBrandId] = useState(
initial?.brand_id ?? lockedBrandId ?? brands[0]?.id ?? ""
);
const [active, setActive] = useState(initial?.active ?? true);
const [isTaxable, setIsTaxable] = useState(initial?.is_taxable ?? true);
// Image state
const [imagePreview, setImagePreview] = useState<string | null>(initialImageUrl);
const [imageUrl, setImageUrl] = useState<string | null>(initialImageUrl);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [isDrag, setIsDrag] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Submit state
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// Reset state when opening with new initial values
useEffect(() => {
if (!open) return;
setName(initial?.name ?? "");
setDescription(initial?.description ?? "");
setPrice(initial?.price ?? "");
setType((initial?.type as ProductFormValues["type"]) ?? "pickup");
setBrandId(initial?.brand_id ?? lockedBrandId ?? brands[0]?.id ?? "");
setActive(initial?.active ?? true);
setIsTaxable(initial?.is_taxable ?? true);
setImagePreview(initialImageUrl);
setImageUrl(initialImageUrl);
setUploading(false);
setUploadError(null);
setError(null);
setSaving(false);
setIsDrag(false);
}, [open, initial, initialImageUrl, lockedBrandId, brands]);
// Body scroll lock + escape key
useEffect(() => {
if (!open) return;
const original = document.body.style.overflow;
document.body.style.overflow = "hidden";
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => {
document.body.style.overflow = original;
window.removeEventListener("keydown", onKey);
};
}, [open, onClose]);
const handleFile = useCallback(
async (file: File) => {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
setUploadError("PNG, JPEG, or WebP only.");
return;
}
if (file.size > 5 * 1024 * 1024) {
setUploadError("File must be under 5MB.");
return;
}
setUploadError(null);
setUploading(true);
// Local preview first
const localUrl = URL.createObjectURL(file);
setImagePreview(localUrl);
const result = await onUploadImage(file);
setUploading(false);
if (result.success && result.imageUrl) {
setImageUrl(result.imageUrl);
setImagePreview(result.imageUrl);
URL.revokeObjectURL(localUrl);
} else {
setUploadError(result.error ?? "Upload failed.");
setImagePreview(imageUrl); // revert
}
},
[onUploadImage, imageUrl]
);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (!name.trim()) {
setError("Product name is required.");
return;
}
if (!price || isNaN(parseFloat(price)) || parseFloat(price) < 0) {
setError("Valid price is required.");
return;
}
if (!lockBrand && !brandId) {
setError("Please select a brand.");
return;
}
setSaving(true);
const res = await onSubmit({
name: name.trim(),
description: description.trim(),
price,
type,
brand_id: lockBrand ? lockedBrandId : brandId,
active,
is_taxable: isTaxable,
image_url: imageUrl,
});
setSaving(false);
if (!res.success) {
setError(res.error ?? "Something went wrong.");
return;
}
onClose();
}
if (!mounted || !open) return null;
const showBrandPicker = !lockBrand;
const lockedBrandName = brands.find((b) => b.id === lockedBrandId)?.name ?? lockedBrandId;
return createPortal(
<div
className="fixed inset-0 z-[80] flex items-center justify-center p-3 sm:p-6 atelier-backdrop"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
style={{
backgroundColor: "rgba(28, 25, 23, 0.55)",
backdropFilter: "blur(8px)",
WebkitBackdropFilter: "blur(8px)",
}}
>
<div
role="dialog"
aria-modal="true"
aria-label={mode === "add" ? "Add product" : "Edit product"}
className="atelier-enter atelier-canvas relative w-full max-w-5xl max-h-[calc(100vh-1.5rem)] sm:max-h-[calc(100vh-3rem)] rounded-2xl shadow-[0_30px_80px_-20px_rgba(28,25,23,0.45)] flex flex-col overflow-hidden border border-stone-200/60"
>
{/* grain overlay */}
<div className="atelier-grain" aria-hidden />
{/* HEADER */}
<div className="relative shrink-0 px-6 sm:px-10 pt-6 sm:pt-8 pb-5 sm:pb-6">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2.5 mb-3">
<span className="atelier-section-num">
{mode === "add" ? "Nouveau" : "Mise à jour"} · MMXXVI
</span>
</div>
<h2 className="atelier-title text-3xl sm:text-4xl md:text-5xl">
{mode === "add" ? (
<>
Add a <span className="atelier-italic">product</span>
</>
) : (
<>
Edit <span className="atelier-italic">{initial?.name || "product"}</span>
</>
)}
</h2>
<p className="atelier-italic mt-2 text-sm sm:text-[15px] max-w-md leading-relaxed">
{mode === "add"
? "Compose a new entry for the harvest catalog — every detail, like a recipe."
: "Refine the details of this entry. The catalog is a living record."}
</p>
</div>
<button
type="button"
onClick={onClose}
className="shrink-0 flex h-9 w-9 items-center justify-center rounded-full transition-all duration-200 hover:bg-stone-900 hover:text-white text-stone-500"
aria-label="Close"
>
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div className="relative shrink-0 px-6 sm:px-10">
<hr className="atelier-rule" />
</div>
{/* BODY — two columns */}
<form
onSubmit={handleSubmit}
className="relative flex-1 overflow-y-auto"
onDragEnter={(e) => {
e.preventDefault();
setIsDrag(true);
}}
>
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] gap-0">
{/* LEFT — Image hero */}
<div className="relative px-6 sm:px-10 pt-6 sm:pt-8 pb-6 lg:border-r border-stone-200/60 lg:pr-8">
<div className="atelier-section-num mb-4">01 · Media</div>
<div
onDragOver={(e) => {
e.preventDefault();
setIsDrag(true);
}}
onDragLeave={(e) => {
if (e.currentTarget === e.target) setIsDrag(false);
}}
onDrop={(e) => {
e.preventDefault();
setIsDrag(false);
const file = e.dataTransfer.files?.[0];
if (file) handleFile(file);
}}
onClick={() => !uploading && fileInputRef.current?.click()}
className={[
"atelier-drop",
isDrag ? "is-drag" : "",
uploadError ? "is-error" : "",
imagePreview ? "has-image" : "",
].join(" ")}
>
{/* status pill */}
<div
className={[
"atelier-status-pill",
imagePreview ? "" : "is-empty",
].join(" ")}
>
<span className="atelier-dot" />
{imagePreview
? uploading
? "Uploading"
: "Image set"
: "No image yet"}
</div>
{uploading ? (
<div className="flex flex-col items-center gap-3">
<div className="h-6 w-6 rounded-full border-2 border-stone-300 border-t-[#224E2F] animate-spin" />
<p className="atelier-drop-title">Pouring into the cellar</p>
</div>
) : imagePreview ? (
<div className="absolute inset-0 p-3 sm:p-4">
<div className="relative h-full w-full">
<Image
src={imagePreview}
alt="Product preview"
fill
style={{ objectFit: "contain" }}
className="rounded-md"
/>
</div>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setImagePreview(null);
setImageUrl(null);
}}
className="absolute bottom-4 left-1/2 -translate-x-1/2 inline-flex items-center gap-1.5 rounded-full bg-stone-900/85 backdrop-blur-sm px-3 py-1.5 text-[11px] font-mono uppercase tracking-wider text-white hover:bg-stone-900 transition-colors"
>
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
Remove
</button>
</div>
) : (
<>
{/* ornamental drop zone content */}
<svg
className="h-10 w-10 text-[#224E2F]/70"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.2}
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M12 3v13" />
<path d="M7 8l5-5 5 5" />
<path d="M4 16v3a2 2 0 002 2h12a2 2 0 002-2v-3" />
<circle cx="12" cy="20" r="0.8" fill="currentColor" />
</svg>
<p className="atelier-drop-eyebrow">Drag &amp; drop</p>
<p className="atelier-drop-title">
or click to choose<br />a harvest portrait
</p>
<p className="atelier-drop-hint">PNG · JPEG · WebP · 5MB max</p>
</>
)}
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFile(file);
e.target.value = "";
}}
/>
</div>
{uploadError && (
<p className="mt-3 atelier-hint" style={{ color: "#B91C1C" }}>
{uploadError}
</p>
)}
</div>
{/* RIGHT — Form fields */}
<div className="px-6 sm:px-10 pt-6 sm:pt-8 pb-6 lg:pl-10 space-y-7 atelier-stagger">
{error && (
<div className="atelier-error">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{error}</span>
</div>
)}
{/* 02 IDENTITY */}
<section>
<div className="flex items-baseline justify-between mb-4">
<div className="atelier-section-num">02 · Identity</div>
</div>
<div>
<label
htmlFor="atelier-name"
className="atelier-section-label block mb-1"
>
Product name
</label>
<input
id="atelier-name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Dozen Sweet Corn"
className="atelier-input atelier-input--display"
autoComplete="off"
/>
</div>
<div className="mt-5">
<label
htmlFor="atelier-desc"
className="atelier-section-label block mb-1"
>
Description
</label>
<textarea
id="atelier-desc"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="A note from the field — origin, variety, picking notes…"
rows={2}
className="atelier-input resize-none"
style={{ minHeight: 56 }}
/>
</div>
</section>
{/* 03 COMMERCE */}
<section>
<div className="atelier-section-num mb-4">03 · Commerce</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<div>
<label
htmlFor="atelier-price"
className="atelier-section-label block mb-1"
>
Price
</label>
<div className="relative">
<span className="atelier-price-sigil">$</span>
<input
id="atelier-price"
type="number"
step="0.01"
min="0"
value={price}
onChange={(e) => setPrice(e.target.value)}
placeholder="0.00"
className="atelier-price"
/>
</div>
</div>
{showBrandPicker ? (
<div>
<label
htmlFor="atelier-brand"
className="atelier-section-label block mb-1"
>
Brand
</label>
<select
id="atelier-brand"
value={brandId}
onChange={(e) => setBrandId(e.target.value)}
className="atelier-select"
>
{brands.length === 0 && <option value="">Loading brands</option>}
{brands.length > 0 && <option value="">Select a brand</option>}
{brands.map((b) => (
<option key={b.id} value={b.id}>
{b.name}
</option>
))}
</select>
<p className="atelier-hint">
You administer multiple brands choose the one this product belongs to.
</p>
</div>
) : (
<div>
<span className="atelier-section-label block mb-1">Brand</span>
<div className="py-2.5 border-b border-stone-300/40">
<span className="font-[family-name:var(--font-fraunces)] text-[15px] text-stone-700">
{lockedBrandName || "—"}
</span>
</div>
</div>
)}
</div>
<div className="mt-6">
<span className="atelier-section-label block mb-2">Type</span>
<div className="grid grid-cols-3 gap-2.5">
{TYPE_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => setType(opt.value)}
className={[
"atelier-type-card",
type === opt.value ? "is-selected" : "",
].join(" ")}
aria-pressed={type === opt.value}
>
<div className="flex items-center justify-between w-full">
<span className="atelier-type-icon">{opt.icon}</span>
<svg
className="atelier-type-check h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={3}
>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
</div>
<div>
<div className="atelier-type-name">{opt.label}</div>
<div
className={[
"text-[10px] font-[family-name:var(--font-fragment-mono)] uppercase tracking-wider mt-0.5",
type === opt.value ? "text-white/60" : "text-stone-500",
].join(" ")}
>
{opt.italic}
</div>
</div>
</button>
))}
</div>
</div>
</section>
{/* 04 SETTINGS */}
<section>
<div className="atelier-section-num mb-4">04 · Settings</div>
<div className="flex flex-wrap items-center gap-6 sm:gap-10">
<button
type="button"
onClick={() => setActive((v) => !v)}
className={["atelier-toggle", active ? "is-on" : ""].join(" ")}
aria-pressed={active}
>
<span className="atelier-toggle-track">
<span className="atelier-toggle-thumb" />
</span>
<span className="atelier-toggle-label">Active</span>
</button>
<button
type="button"
onClick={() => setIsTaxable((v) => !v)}
className={["atelier-toggle is-gold", isTaxable ? "is-on" : ""].join(" ")}
aria-pressed={isTaxable}
>
<span className="atelier-toggle-track">
<span className="atelier-toggle-thumb" />
</span>
<span className="atelier-toggle-label">Taxable</span>
</button>
<p className="atelier-hint flex-1 min-w-[200px]">
Active products appear in the storefront. Taxable items add sales tax at checkout.
</p>
</div>
</section>
</div>
</div>
</form>
{/* FOOTER */}
<div className="relative shrink-0 px-6 sm:px-10 pt-4 pb-6 sm:pb-7 border-t border-stone-200/60 bg-[#FAF7F0]/80 backdrop-blur-sm">
<div className="flex items-center justify-between gap-4">
<button
type="button"
onClick={onClose}
className="atelier-discard"
>
discard changes
</button>
<div className="flex items-center gap-3">
{/* readiness indicator */}
<div className="hidden sm:flex items-center gap-2 text-[11px] font-mono uppercase tracking-wider text-stone-500">
<span
className={[
"h-1.5 w-1.5 rounded-full",
name.trim() && price
? "bg-emerald-600 shadow-[0_0_0_3px_rgba(22,163,74,0.15)]"
: "bg-stone-300",
].join(" ")}
/>
{name.trim() && price ? "Ready" : "Required fields pending"}
</div>
<button
type="submit"
form="atelier-product-form"
onClick={handleSubmit}
disabled={saving || uploading || !name.trim() || !price}
className="atelier-cta"
>
<span className="atelier-cta-shimmer" />
{saving ? (
<>
<span className="h-3.5 w-3.5 rounded-full border-2 border-white/40 border-t-white animate-spin" />
{mode === "add" ? "Composing…" : "Saving…"}
</>
) : (
<>
{mode === "add" ? "Add to catalog" : "Save changes"}
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</>
)}
</button>
</div>
</div>
</div>
</div>
</div>,
document.body
);
}
+205 -392
View File
@@ -1,13 +1,14 @@
"use client";
import { useState, useCallback, useRef, useTransition } from "react";
import { useState, useCallback, useTransition, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { createProduct } from "@/actions/products/create-product";
import { updateProduct } from "@/actions/products/update-product";
import { deleteProduct } from "@/actions/products";
import { uploadProductImage } from "@/actions/products/upload-image";
import GlassModal from "@/components/admin/GlassModal";
import ProductFormModal, { type ProductFormValues } from "@/components/admin/ProductFormModal";
import { PageHeader, AdminButton, AdminIconButton, AdminSearchInput, AdminFilterTabs, AdminViewModeTabs, useToast, Skeleton } from "@/components/admin/design-system";
type Product = {
@@ -22,16 +23,6 @@ type Product = {
is_taxable: boolean;
};
type FormData = {
name: string;
description: string;
price: string;
type: string;
active: boolean;
image_url: string;
is_taxable: boolean;
};
type ViewMode = "table" | "cards";
// Icons
@@ -74,7 +65,17 @@ const PackageIconHeader = () => (
</svg>
);
export default function ProductsClient({ products, brandId }: { products: Product[]; brandId?: string }) {
export default function ProductsClient({
products,
brandId,
brands = [],
isPlatformAdmin = false,
}: {
products: Product[];
brandId?: string;
brands?: { id: string; name: string }[];
isPlatformAdmin?: boolean;
}) {
const router = useRouter();
const { success: showSuccess, error: showError } = useToast();
const [, startTransition] = useTransition();
@@ -83,28 +84,10 @@ export default function ProductsClient({ products, brandId }: { products: Produc
const [viewMode, setViewMode] = useState<ViewMode>("table");
const [showModal, setShowModal] = useState(false);
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
const [formData, setFormData] = useState<FormData>({
name: "",
description: "",
price: "",
type: "pickup",
active: true,
image_url: "",
is_taxable: true,
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
// Image upload states
const [imagePreview, setImagePreview] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [pendingImageUrl, setPendingImageUrl] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const filtered = products.filter((p) => {
const matchesSearch =
!search ||
@@ -147,165 +130,104 @@ export default function ProductsClient({ products, brandId }: { products: Produc
});
}
async function handleFileSelect(file: File) {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
setUploadError("Only PNG, JPEG, and WebP images are allowed.");
return;
}
if (file.size > 5 * 1024 * 1024) {
setUploadError("Image must be under 5MB.");
return;
}
const handleUploadImage = useCallback(
async (file: File): Promise<{ success: boolean; imageUrl?: string; error?: string }> => {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
return { success: false, error: "Only PNG, JPEG, and WebP images are allowed." };
}
if (file.size > 5 * 1024 * 1024) {
return { success: false, error: "Image must be under 5MB." };
}
setUploadError(null);
setUploading(true);
const resizedBuffer = await resizeImage(file, 1200);
const resizedFile = new File([resizedBuffer], file.name, { type: "image/jpeg" });
const resizedBuffer = await resizeImage(file, 1200);
const resizedFile = new File([resizedBuffer], file.name, { type: "image/jpeg" });
const productIdForUpload = editingProduct ? editingProduct.id : "__NEW__";
const result = await uploadProductImage(productIdForUpload, resizedFile);
setUploading(false);
if (result.success) {
setPendingImageUrl(result.imageUrl);
setImagePreview(result.imageUrl);
setFormData({ ...formData, image_url: result.imageUrl });
} else {
setUploadError(result.error ?? "Upload failed.");
}
}
const productIdForUpload = editingProduct ? editingProduct.id : "__NEW__";
const result = await uploadProductImage(productIdForUpload, resizedFile);
if (result.success) {
return { success: true, imageUrl: result.imageUrl };
}
return { success: false, error: result.error };
},
[editingProduct]
);
const openAddModal = useCallback(() => {
setEditingProduct(null);
setFormData({
name: "",
description: "",
price: "",
type: "pickup",
active: true,
image_url: "",
is_taxable: true,
});
setImagePreview(null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
setShowModal(true);
}, []);
const openEditModal = useCallback((product: Product) => {
setEditingProduct(product);
setFormData({
name: product.name,
description: product.description || "",
price: String(product.price),
type: product.type,
active: product.active,
image_url: product.image_url || "",
is_taxable: product.is_taxable,
});
setImagePreview(product.image_url || null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
setShowModal(true);
}, []);
const closeModal = useCallback(() => {
setShowModal(false);
setEditingProduct(null);
setImagePreview(null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSaving(true);
setIsLoading(true);
const price = parseFloat(formData.price);
if (isNaN(price) || price < 0) {
setError("Please enter a valid price");
setSaving(false);
setIsLoading(false);
return;
}
if (!formData.name.trim()) {
setError("Product name is required");
setSaving(false);
setIsLoading(false);
return;
}
try {
const imageUrl = pendingImageUrl || formData.image_url || null;
let result;
if (editingProduct) {
// Edits: scope to the product's own brand. The page-level brandId
// prop can be undefined for platform_admins viewing all brands, but
// the product record always carries its own brand_id.
const productBrandId = editingProduct.brand_id;
if (!productBrandId) {
setError("This product is missing a brand assignment");
setSaving(false);
setIsLoading(false);
return;
const handleModalSubmit = useCallback(
async (values: ProductFormValues): Promise<{ success: boolean; error?: string }> => {
setIsLoading(true);
try {
const price = parseFloat(values.price);
if (isNaN(price) || price < 0) {
return { success: false, error: "Please enter a valid price" };
}
result = await updateProduct(editingProduct.id, productBrandId, {
name: formData.name.trim(),
description: formData.description.trim(),
price,
type: formData.type,
active: formData.active,
image_url: imageUrl,
is_taxable: formData.is_taxable,
});
} else {
// Creates: require the page-level brandId prop (no product to pull from).
if (!brandId) {
setError("Brand ID is required");
setSaving(false);
setIsLoading(false);
return;
if (!values.name.trim()) {
return { success: false, error: "Product name is required" };
}
result = await createProduct(brandId, {
name: formData.name.trim(),
description: formData.description.trim(),
price,
type: formData.type,
active: formData.active,
image_url: imageUrl,
is_taxable: formData.is_taxable,
});
}
if (!result.success) {
setError(result.error ?? "Failed to save product");
showError("Failed to save product", result.error ?? "Please try again");
setSaving(false);
// Platform admins pick a brand in the modal; everyone else is locked.
const effectiveBrandId = isPlatformAdmin ? values.brand_id : brandId;
if (!effectiveBrandId) {
return { success: false, error: "Please choose a brand for this product." };
}
let result;
if (editingProduct) {
result = await updateProduct(editingProduct.id, effectiveBrandId, {
name: values.name.trim(),
description: values.description.trim(),
price,
type: values.type,
active: values.active,
image_url: values.image_url,
is_taxable: values.is_taxable,
});
} else {
result = await createProduct(effectiveBrandId, {
name: values.name.trim(),
description: values.description.trim(),
price,
type: values.type,
active: values.active,
image_url: values.image_url,
is_taxable: values.is_taxable,
});
}
if (!result.success) {
showError("Failed to save product", result.error ?? "Please try again");
return { success: false, error: result.error };
}
showSuccess(
editingProduct ? "Product updated" : "Product created",
`${values.name} has been saved`
);
startTransition(() => router.refresh());
return { success: true };
} catch {
return { success: false, error: "Network error. Please try again." };
} finally {
setIsLoading(false);
return;
}
showSuccess(editingProduct ? "Product updated" : "Product created", `${formData.name} has been saved`);
closeModal();
setIsLoading(false);
startTransition(() => router.refresh());
} catch {
setError("Network error. Please try again.");
showError("Network error", "Please check your connection and try again");
setSaving(false);
setIsLoading(false);
}
};
},
[editingProduct, brandId, isPlatformAdmin, router, showError, showSuccess]
);
const handleDelete = async (productId: string) => {
setDeletingId(productId);
@@ -409,203 +331,36 @@ export default function ProductsClient({ products, brandId }: { products: Produc
/>
)}
{/* Modal */}
{showModal && (
<GlassModal
title={editingProduct ? "Edit Product" : "Add Product"}
subtitle={editingProduct ? `Editing ${editingProduct.name}` : "Create a new product"}
onClose={closeModal}
>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-xl bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-600 flex items-start gap-3">
<svg className="h-5 w-5 shrink-0 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{error}
</div>
)}
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">
Name <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Product name"
className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 placeholder:text-[var(--admin-text-muted)] transition-colors ${
error && !formData.name.trim()
? "border-red-400 bg-red-50"
: "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
}`}
required
/>
</div>
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Description</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Product description"
rows={2}
className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20 placeholder:text-[var(--admin-text-muted)] resize-none"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">
Price <span className="text-red-500">*</span>
</label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-stone-400 text-sm">$</span>
<input
type="number"
step="0.01"
min="0"
value={formData.price}
onChange={(e) => setFormData({ ...formData, price: e.target.value })}
placeholder="0.00"
className={`w-full rounded-xl border pl-8 pr-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
error && (!formData.price || parseFloat(formData.price) < 0)
? "border-red-400 bg-red-50"
: "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
}`}
required
/>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Type</label>
<select
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
>
<option value="pickup">Pickup</option>
<option value="wholesale">Wholesale</option>
<option value="subscription">Subscription</option>
</select>
</div>
</div>
{/* Image Upload */}
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Product Image</label>
<p className="text-[10px] text-stone-500 mb-2">JPG, PNG, WebP · 1200px max width · max 5MB</p>
<div
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file) handleFileSelect(file);
}}
onClick={() => !uploading && fileInputRef.current?.click()}
className={`
flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed p-6 cursor-pointer transition-colors
${uploadError ? "border-red-400" : "border-[var(--admin-border)] hover:border-[var(--admin-accent)] hover:bg-[var(--admin-accent)]/5"}
${uploading ? "opacity-50 pointer-events-none" : ""}
`}
>
{uploading ? (
<>
<div className="h-5 w-5 rounded-full border-2 border-[var(--admin-accent)] border-t-transparent animate-spin" />
<span className="text-sm text-stone-500">Uploading...</span>
</>
) : imagePreview ? (
<div className="relative">
<div className="relative h-32 sm:h-40 w-auto">
<Image src={imagePreview} alt="Product preview" fill style={{ objectFit: "contain" }} className="rounded-lg" />
</div>
<span className="block text-center text-xs text-stone-500 mt-2">Click or drop to replace</span>
</div>
) : (
<>
{Icons.upload("h-8 w-8 text-stone-400")}
<span className="text-sm text-stone-500">Drag & drop or click to upload</span>
</>
)}
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file);
e.target.value = "";
}}
/>
</div>
{uploadError && (
<p className="mt-1 text-xs text-red-500">{uploadError}</p>
)}
{(imagePreview || formData.image_url) && (
<button
type="button"
onClick={() => {
setImagePreview(null);
setPendingImageUrl(null);
setFormData({ ...formData, image_url: "" });
}}
className="mt-2 text-xs text-red-500 hover:underline"
>
Remove image
</button>
)}
</div>
<div className="flex items-center gap-6">
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.active}
onChange={(e) => setFormData({ ...formData, active: e.target.checked })}
className="h-4 w-4 rounded border-[var(--admin-border)] text-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/30 focus:ring-offset-1 cursor-pointer"
/>
<span className="text-sm font-medium text-stone-700">Active</span>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.is_taxable}
onChange={(e) => setFormData({ ...formData, is_taxable: e.target.checked })}
className="h-4 w-4 rounded border-[var(--admin-border)] text-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/30 focus:ring-offset-1 cursor-pointer"
/>
<span className="text-sm font-medium text-stone-700">Taxable</span>
</label>
</div>
<div className="flex justify-end gap-3 pt-4 border-t border-stone-100">
<AdminButton
type="button"
variant="secondary"
onClick={closeModal}
>
Cancel
</AdminButton>
<AdminButton
type="submit"
variant="primary"
isLoading={saving}
disabled={!formData.name.trim() || !formData.price}
>
{editingProduct ? "Save Changes" : "Create Product"}
</AdminButton>
</div>
</form>
</GlassModal>
)}
{/* Modal — Atelier des Récoltes (editorial product form) */}
<ProductFormModal
open={showModal}
mode={editingProduct ? "edit" : "add"}
onClose={closeModal}
onSubmit={handleModalSubmit}
onUploadImage={handleUploadImage}
brands={brands}
lockBrand={!isPlatformAdmin}
lockedBrandId={brandId ?? ""}
initial={
editingProduct
? {
name: editingProduct.name,
description: editingProduct.description || "",
price: String(editingProduct.price),
type: (editingProduct.type as "pickup" | "wholesale" | "subscription") ?? "pickup",
brand_id: editingProduct.brand_id,
active: editingProduct.active,
is_taxable: editingProduct.is_taxable,
}
: undefined
}
initialImageUrl={editingProduct?.image_url ?? null}
/>
</div>
);
}
// ── Table View ─────────────────────────────────────────────────────────────────
function TableView({
@@ -625,8 +380,51 @@ function TableView({
onDeleteCancel: () => void;
deletingId: string | null;
}) {
// Track the position of the open row's three-dots button so the popup can be
// rendered via portal at body level (escapes any overflow:hidden ancestors
// and any table-row stacking-context quirks).
const [menuPos, setMenuPos] = useState<{ top: number; left: number; width: number } | null>(null);
const [mounted, setMounted] = useState(false);
const buttonRefs = useRef<Record<string, HTMLButtonElement | null>>({});
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!deleteConfirm) {
setMenuPos(null);
return;
}
const btn = buttonRefs.current[deleteConfirm];
if (btn) {
const rect = btn.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.right, width: rect.width });
}
}, [deleteConfirm]);
// Reposition on scroll/resize so the popup stays anchored to its button.
useEffect(() => {
if (!deleteConfirm) return;
const updatePos = () => {
const btn = buttonRefs.current[deleteConfirm];
if (btn) {
const rect = btn.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.right, width: rect.width });
}
};
window.addEventListener("scroll", updatePos, true);
window.addEventListener("resize", updatePos);
return () => {
window.removeEventListener("scroll", updatePos, true);
window.removeEventListener("resize", updatePos);
};
}, [deleteConfirm]);
const openProduct = deleteConfirm ? products.find((p) => p.id === deleteConfirm) : null;
return (
<div className="overflow-hidden rounded-xl border border-[var(--admin-border)] bg-white">
<div className="overflow-visible rounded-xl border border-[var(--admin-border)] bg-white">
<table className="w-full text-sm">
<thead className="bg-stone-50">
<tr>
@@ -710,44 +508,15 @@ function TableView({
Edit
</AdminButton>
<button
ref={(el) => { buttonRefs.current[product.id] = el; }}
onClick={() => onDelete(product.id)}
className="rounded-lg px-2 py-1.5 text-xs text-[var(--admin-text-muted)] hover:text-red-600 hover:bg-red-50 transition-colors"
aria-label="Product actions"
>
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
</svg>
</button>
{deleteConfirm === product.id && (
<>
<div className="fixed inset-0 z-30" onClick={onDeleteCancel} />
<div className="absolute right-0 top-full mt-1 z-40 w-72 rounded-xl bg-white border border-[var(--admin-border)] shadow-xl p-4">
<p className="text-sm font-semibold text-stone-900">
Delete &quot;{product.name}&quot;?
</p>
<p className="mt-1 text-xs text-stone-500">
This will remove the product. If attached to orders, it will be hidden.
</p>
<div className="mt-3 flex gap-2">
<button
onClick={onDeleteCancel}
className="flex-1 rounded-lg border border-[var(--admin-border)] bg-white px-3 py-2 text-xs font-semibold text-stone-700 hover:bg-stone-50"
>
Cancel
</button>
<AdminButton
onClick={() => onDeleteConfirm(product.id)}
disabled={deletingId === product.id}
variant="danger"
size="sm"
className="flex-1"
>
{deletingId === product.id ? "..." : "Delete"}
</AdminButton>
</div>
</div>
</>
)}
</div>
</td>
</tr>
@@ -755,6 +524,50 @@ function TableView({
)}
</tbody>
</table>
{/* Delete confirmation popup — rendered via portal at body level with
position: fixed so it sits above all table rows and escapes the
overflow-visible container. */}
{mounted && deleteConfirm && openProduct && menuPos &&
createPortal(
<>
<div
className="fixed inset-0 z-[60]"
onClick={onDeleteCancel}
/>
<div
role="dialog"
aria-label="Confirm delete"
className="fixed z-[70] w-72 rounded-xl bg-white border border-[var(--admin-border)] shadow-xl p-4"
style={{ top: menuPos.top, left: menuPos.left, transform: "translateX(-100%)" }}
>
<p className="text-sm font-semibold text-stone-900">
Delete &quot;{openProduct.name}&quot;?
</p>
<p className="mt-1 text-xs text-stone-500">
This will remove the product. If attached to orders, it will be hidden.
</p>
<div className="mt-3 flex gap-2">
<button
onClick={onDeleteCancel}
className="flex-1 rounded-lg border border-[var(--admin-border)] bg-white px-3 py-2 text-xs font-semibold text-stone-700 hover:bg-stone-50"
>
Cancel
</button>
<AdminButton
onClick={() => onDeleteConfirm(openProduct.id)}
disabled={deletingId === openProduct.id}
variant="danger"
size="sm"
className="flex-1"
>
{deletingId === openProduct.id ? "..." : "Delete"}
</AdminButton>
</div>
</div>
</>,
document.body
)}
</div>
);
}