'use client'; /** * Back-in-stock alert — "email me when this is back". * * ⛔ THIS IS NOT A NEWSLETTER SIGNUP. `stockAlerts.subscribe()` grants no * marketing consent, creates no customer account, and the person receives * exactly one message: the alert itself, about this item, carrying a link that * stops it. That is why the button says "Notify me" and never "Subscribe" — * and why a shopper who unsubscribed from the store's marketing can still use * it. Never gate it on consent. * * ⛔ RENDER IT ONLY WHERE IT APPLIES. `canOfferStockAlert()` below is the whole * gate. Requests for anything else are silently discarded server-side (the * response is uniform on purpose, so it cannot be used to read a store's stock * levels), which means a button in the wrong place looks like it worked and * does nothing. * * ⛔ THE RESPONSE CARRIES NO INFORMATION. `{ ok: true }` comes back identically * for a new request, a duplicate, a product id that does not exist, an item * already in stock, and an address suppressed after a hard bounce. There is * nothing to branch on — render one success state and stop. * * ⛔ DO NOT PROMISE TIMING. Availability is `total - reserved - unavailable`, so an expiring * cart briefly lifts a sold-out item above zero; the alert waits for stock to * hold, then goes out in waves sized to the units that came back, oldest * request first. A shopper can sit through a restock without hearing. "We'll * email you when it's back" is true; "you'll be the first to know" is not. * * Rate limited to 5 requests / 60s per IP, 25 open alerts per address per store. */ import { useMemo, useState } from 'react'; import type { InventoryInfo } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { useTranslations } from '@/core/lib/translations'; /** * The gate. Four ways the answer is no, and every one of them matters: * * - the merchant switched the feature off for this storefront * (`storeInfo.stockAlertsEnabled`, read once at boot); * - the item is in stock, so there is nothing to wait for; * - stock is not TRACKED — UNLIMITED never runs out, DISABLED is not for sale * and no restock changes that; * - the merchant allows backorders on it, so the storefront can already sell * it while out of stock and an alert would tell someone to come back and do * what they can already do. */ export function canOfferStockAlert( inventory: InventoryInfo | null | undefined, stockAlertsEnabled: boolean | undefined ): boolean { if (stockAlertsEnabled === false) return false; if (!inventory) return false; if (inventory.trackingMode !== 'TRACKED') return false; if (inventory.canPurchase) return false; // Older backends omit the field entirely; absent means no backorder. return (inventory.backorderMode ?? 'NONE') === 'NONE'; } interface BackInStockFormProps { productId: string; /** * ⛔ Pass the SELECTED variant on any product with variants. Without it the * alert waits on the product as a whole, so a shopper who wanted the medium * is mailed when the small returns and arrives to find their size still gone. */ variantId?: string; } export function BackInStockForm({ productId, variantId }: BackInStockFormProps) { const t = useTranslations('backInStock'); const [email, setEmail] = useState(''); const [honeypot, setHoneypot] = useState(''); const [loading, setLoading] = useState(false); const [done, setDone] = useState(false); const [error, setError] = useState(null); // Same source the newsletter form uses — is set from the active // locale, and passing it is what decides the language of the alert email. // Omit it on a Hebrew storefront and the shopper gets English. const locale = useMemo(() => { if (typeof document !== 'undefined') return document.documentElement.lang || undefined; return undefined; }, []); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (loading || !email.trim()) return; setLoading(true); setError(null); try { await getClient().stockAlerts.subscribe({ email: email.trim(), productId, variantId, locale, honeypot, }); setDone(true); setEmail(''); } catch { // A 429 lands here too — the copy stays generic rather than explaining // the rate limit, which would only tell an abuser where the edge is. setError(t('genericError')); } finally { setLoading(false); } } if (done) { return (

{t('doneTitle')}

{t('doneBody')}

); } return (

{t('subtitle')}

setEmail(e.target.value)} placeholder={t('placeholder')} className="border-border min-w-0 flex-1 rounded border px-3 py-2 text-sm" />
{/* Honeypot. Bots complete every text input; a human never sees this one, so a non-empty value rejects the request server-side. Positioned off-screen rather than `display:none` — some bots skip hidden inputs — and kept out of the tab order and the accessibility tree. */} setHoneypot(e.target.value)} style={HONEYPOT_STYLE} /> {error ? (

{error}

) : null}
); } /** * Honeypot field styling. It must stay in the DOM (bots fill any input) but never be seen or * reached. Do NOT park it at `left: -9999px`: in an RTL page that is the scrolling side, so it * stretches the document to ~10,000px and lets a Hebrew visitor scroll sideways into blank space. * A clipped 1px box inside its container adds no scrollable overflow in either direction. */ const HONEYPOT_STYLE = { position: 'absolute', insetInlineStart: 0, width: 1, height: 1, margin: -1, padding: 0, border: 0, overflow: 'hidden', opacity: 0, clipPath: 'inset(50%)', pointerEvents: 'none', } as const;