Wip stage M4

This commit is contained in:
Nông Đức Huy
2026-08-13 23:20:22 +07:00
parent 5386bc51d1
commit d5cacc1208
113 changed files with 9486 additions and 919 deletions
+2
View File
@@ -17,10 +17,12 @@
"@sport/ui": "workspace:*",
"@sport/validation": "workspace:*",
"@tanstack/react-query": "^5.101.4",
"lucide-react": "1.31.0",
"next": "catalog:",
"next-intl": "^4.13.6",
"react": "catalog:",
"react-dom": "catalog:",
"tw-animate-css": "1.4.0",
"zod": "catalog:",
"zustand": "^5.0.14"
},
@@ -1,22 +1,24 @@
import type { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import { PageScaffold } from '@/components/layout/page-scaffold';
import { InventoryTable } from '@/features/inventory/inventory-table';
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('pages.inventory');
return { title: t('title') };
}
export default async function InventoryPage() {
export default async function Page() {
const t = await getTranslations('pages.inventory');
return (
<PageScaffold
title={t('title')}
description={t('body')}
permission="inventory.read"
milestone="M3 — admin catalog"
/>
<div className="space-y-6 p-8">
<header>
<h1 className="text-2xl font-bold">{t('title')}</h1>
<p className="text-ink-500 mt-2 max-w-2xl text-sm">{t('body')}</p>
</header>
<InventoryTable />
</div>
);
}
+10 -8
View File
@@ -1,22 +1,24 @@
import type { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import { PageScaffold } from '@/components/layout/page-scaffold';
import { MediaLibrary } from '@/features/media/media-library';
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('pages.media');
return { title: t('title') };
}
export default async function MediaPage() {
export default async function Page() {
const t = await getTranslations('pages.media');
return (
<PageScaffold
title={t('title')}
description={t('body')}
permission="media.read"
milestone="M3 — admin catalog"
/>
<div className="space-y-6 p-8">
<header>
<h1 className="text-2xl font-bold">{t('title')}</h1>
<p className="text-ink-500 mt-2 max-w-2xl text-sm">{t('body')}</p>
</header>
<MediaLibrary />
</div>
);
}
@@ -0,0 +1,18 @@
import type { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import { ProductEditor } from '@/features/products/product-editor';
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('editor');
return { title: t('editTitle') };
}
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return (
<div className="p-8">
<ProductEditor productId={id} />
</div>
);
}
@@ -0,0 +1,34 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import { getTranslations } from 'next-intl/server';
import { ProductForm } from '@/features/products/product-form';
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('editor');
return { title: t('createTitle') };
}
/**
* Declared as a sibling of `[id]`, so Next matches this literal segment first —
* otherwise `/products/new` would load the editor for a product with the id
* "new".
*/
export default async function Page() {
const t = await getTranslations('editor');
return (
<div className="space-y-6 p-8">
<header className="flex flex-wrap items-center gap-3">
<Link href="/products" className="text-ink-500 hover:text-ink-950 text-sm">
← {t('backToList')}
</Link>
<h1 className="text-xl font-bold">{t('createTitle')}</h1>
</header>
<p className="text-ink-500 max-w-2xl text-sm">{t('createHint')}</p>
<ProductForm />
</div>
);
}
@@ -1,22 +1,24 @@
import type { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import { PageScaffold } from '@/components/layout/page-scaffold';
import { ProductsTable } from '@/features/products/products-table';
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations('pages.products');
return { title: t('title') };
}
export default async function ProductsPage() {
export default async function Page() {
const t = await getTranslations('pages.products');
return (
<PageScaffold
title={t('title')}
description={t('body')}
permission="product.read"
milestone="M3 — admin catalog"
/>
<div className="space-y-6 p-8">
<header>
<h1 className="text-2xl font-bold">{t('title')}</h1>
<p className="text-ink-500 mt-2 max-w-2xl text-sm">{t('body')}</p>
</header>
<ProductsTable />
</div>
);
}
+2 -2
View File
@@ -71,7 +71,7 @@ export function LoginForm() {
required
value={email}
onChange={(event) => setEmail(event.target.value)}
invalid={Boolean(error)}
aria-invalid={Boolean(error)}
/>
</div>
@@ -87,7 +87,7 @@ export function LoginForm() {
required
value={password}
onChange={(event) => setPassword(event.target.value)}
invalid={Boolean(error)}
aria-invalid={Boolean(error)}
/>
</div>
@@ -0,0 +1,189 @@
'use client';
import { useTranslations } from 'next-intl';
import { useCallback, useEffect, useState } from 'react';
import { isApiClientError, type StockAdjustment } from '@sport/api-client';
import { PERMISSIONS, type InventoryLevel } from '@sport/types';
import { Badge, Button, Input, Skeleton, cn } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
const LOW_STOCK = 5;
export function InventoryTable() {
const t = useTranslations('inventory');
const { can } = useSession();
const [levels, setLevels] = useState<InventoryLevel[] | null>(null);
const [query, setQuery] = useState('');
const [lowOnly, setLowOnly] = useState(false);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const [delta, setDelta] = useState('');
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
const result = await browserApi.catalogAdmin.listInventory({
perPage: 50,
...(query ? { q: query } : {}),
...(lowOnly ? { lowStockOnly: true } : {}),
});
setLevels([...result.items]);
setError(null);
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}, [query, lowOnly, t]);
useEffect(() => {
const timer = setTimeout(() => void load(), 250);
return () => clearTimeout(timer);
}, [load]);
async function adjust(level: InventoryLevel) {
const amount = Number.parseInt(delta, 10);
if (!Number.isInteger(amount) || amount === 0) return;
setBusy(true);
try {
const payload: StockAdjustment = {
variantId: level.variantId,
// A manual correction from this screen is exactly that. Receipts,
// returns and damage are separate reasons the fuller inventory screen
// will offer — mislabelling them here would poison the ledger.
reason: 'MANUAL_ADJUSTMENT',
quantityDelta: amount,
note: 'Adjusted from the inventory table',
};
await browserApi.catalogAdmin.adjustStock(payload);
setEditing(null);
setDelta('');
await load();
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('adjustFailed'));
} finally {
setBusy(false);
}
}
if (!can(PERMISSIONS.INVENTORY_READ)) {
return <p className="text-ink-500 text-sm">{t('noPermission')}</p>;
}
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<Input
type="search"
placeholder={t('searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
className="max-w-xs"
/>
<label className="text-ink-600 flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={lowOnly}
onChange={(event) => setLowOnly(event.target.checked)}
/>
{t('lowStockOnly')}
</label>
</div>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
{!levels ? (
<div className="space-y-2" aria-busy="true">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
) : (
<div className="border-ink-200 overflow-x-auto border bg-white">
<table className="min-w-3xl w-full text-sm">
<thead className="border-ink-200 bg-ink-50 border-b text-left">
<tr className="text-ink-500 text-[0.625rem] uppercase tracking-widest">
<th className="px-4 py-3 font-semibold">{t('table.sku')}</th>
<th className="px-4 py-3 font-semibold">{t('table.product')}</th>
<th className="px-4 py-3 font-semibold">{t('table.onHand')}</th>
<th className="px-4 py-3 font-semibold">{t('table.reserved')}</th>
<th className="px-4 py-3 font-semibold">{t('table.available')}</th>
<th className="px-4 py-3 font-semibold" />
</tr>
</thead>
<tbody className="divide-ink-100 divide-y">
{levels.map((level) => (
<tr key={`${level.variantId}-${level.locationId}`}>
<td className="px-4 py-3 font-mono text-xs">{level.sku}</td>
<td className="px-4 py-3">
<p className="truncate">{level.productName}</p>
<p className="text-ink-400 text-xs">{level.variantTitle}</p>
</td>
<td className="px-4 py-3">{level.onHand}</td>
<td className="text-ink-500 px-4 py-3">{level.reserved}</td>
<td className="px-4 py-3">
<span
className={cn(
'font-medium',
level.available === 0
? 'text-danger'
: level.available <= LOW_STOCK
? 'text-warning'
: '',
)}
>
{level.available}
</span>
{level.available === 0 ? (
<Badge variant="neutral" className="ml-2">
{t('outOfStock')}
</Badge>
) : null}
</td>
<td className="px-4 py-3 text-right">
{!can(PERMISSIONS.INVENTORY_UPDATE) ? null : editing === level.variantId ? (
<div className="flex items-center justify-end gap-2">
<Input
type="number"
value={delta}
onChange={(event) => setDelta(event.target.value)}
placeholder="+10"
className="h-9 w-24"
aria-label={t('deltaLabel')}
/>
<Button size="sm" disabled={busy} onClick={() => void adjust(level)}>
{t('apply')}
</Button>
<Button size="sm" variant="ghost" onClick={() => setEditing(null)}>
{t('cancel')}
</Button>
</div>
) : (
<Button
size="sm"
variant="secondary"
onClick={() => {
setEditing(level.variantId);
setDelta('');
}}
>
{t('adjust')}
</Button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,197 @@
'use client';
import Image from 'next/image';
import { useTranslations } from 'next-intl';
import { useCallback, useEffect, useRef, useState } from 'react';
import { isApiClientError } from '@sport/api-client';
import { PERMISSIONS, type MediaAssetSummary } from '@sport/types';
import { Button, Skeleton } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
interface UploadState {
name: string;
status: 'uploading' | 'failed';
error?: string;
}
/**
* Asset library with direct-to-storage upload.
*
* The browser gets a presigned URL, PUTs the file straight to object storage,
* then tells the API the asset exists (ADR-0009). Nothing streams through the
* API, so a 20 MB file is the storage provider's problem, not ours.
*/
export function MediaLibrary() {
const t = useTranslations('media');
const { can } = useSession();
const inputRef = useRef<HTMLInputElement>(null);
const [assets, setAssets] = useState<MediaAssetSummary[] | null>(null);
const [uploads, setUploads] = useState<UploadState[]>([]);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const result = await browserApi.catalogAdmin.listMedia({ perPage: 60 });
setAssets([...result.items]);
setError(null);
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}, [t]);
useEffect(() => {
let cancelled = false;
// Declared inside the effect and guarded, rather than calling `load()`
// directly: the lint rule cannot see that every setState here happens after
// an await, and the cancellation flag is what stops a slow response from
// writing into an unmounted component anyway.
async function initialLoad() {
try {
const result = await browserApi.catalogAdmin.listMedia({ perPage: 60 });
if (cancelled) return;
setAssets([...result.items]);
setError(null);
} catch (caught) {
if (cancelled) return;
setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}
void initialLoad();
return () => {
cancelled = true;
};
}, [t]);
async function handleFiles(files: FileList | null) {
if (!files || files.length === 0) return;
const list = [...files];
setUploads(list.map((file) => ({ name: file.name, status: 'uploading' as const })));
// Sequential rather than parallel: a merchandiser dropping 30 photos at
// once would otherwise open 30 simultaneous uploads and starve the rest of
// the page's requests.
for (const file of list) {
try {
await browserApi.catalogAdmin.uploadFile(file);
setUploads((current) => current.filter((upload) => upload.name !== file.name));
} catch (caught) {
const message = isApiClientError(caught) ? caught.message : t('uploadFailed');
setUploads((current) =>
current.map((upload) =>
upload.name === file.name ? { ...upload, status: 'failed', error: message } : upload,
),
);
}
}
await load();
if (inputRef.current) inputRef.current.value = '';
}
async function remove(asset: MediaAssetSummary) {
try {
await browserApi.catalogAdmin.deleteMedia(asset.id);
await load();
} catch (caught) {
// The API refuses to delete an asset a product still uses — surface that
// reason rather than a generic failure.
setError(isApiClientError(caught) ? caught.message : t('deleteFailed'));
}
}
if (!can(PERMISSIONS.MEDIA_READ)) {
return <p className="text-ink-500 text-sm">{t('noPermission')}</p>;
}
return (
<div className="space-y-6">
{can(PERMISSIONS.MEDIA_UPLOAD) ? (
<div className="border-ink-300 flex flex-wrap items-center gap-3 border border-dashed bg-white p-6">
<input
ref={inputRef}
id="media-upload"
aria-label={t('chooseFiles')}
type="file"
multiple
accept="image/png,image/jpeg,image/webp,image/avif"
className="sr-only"
onChange={(event) => void handleFiles(event.target.files)}
/>
<Button type="button" onClick={() => inputRef.current?.click()}>
{t('chooseFiles')}
</Button>
<p className="text-ink-500 text-sm">{t('uploadHint')}</p>
</div>
) : null}
{uploads.length > 0 ? (
<ul className="space-y-1 text-sm">
{uploads.map((upload) => (
<li
key={upload.name}
className={upload.status === 'failed' ? 'text-danger' : 'text-ink-500'}
>
{upload.name} — {upload.status === 'failed' ? upload.error : t('uploading')}
</li>
))}
</ul>
) : null}
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
{!assets ? (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6" aria-busy="true">
{Array.from({ length: 6 }, (_, index) => (
<Skeleton key={index} className="aspect-square w-full" />
))}
</div>
) : assets.length === 0 ? (
<p className="text-ink-500 py-12 text-center text-sm">{t('empty')}</p>
) : (
<ul className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
{assets.map((asset) => (
<li key={asset.id} className="border-ink-200 group relative border bg-white">
<div className="bg-ink-100 relative aspect-square overflow-hidden">
<Image
src={asset.url}
alt={asset.altText ?? ''}
fill
sizes="(min-width: 1024px) 16vw, 33vw"
className="object-cover"
/>
</div>
<div className="p-2">
<p className="text-ink-600 truncate text-xs">{asset.altText ?? asset.storageKey}</p>
<p className="text-ink-400 text-[0.625rem]">
{asset.width && asset.height ? `${asset.width}×${asset.height} · ` : ''}
{Math.round(asset.sizeBytes / 1024)} KB
</p>
</div>
{can(PERMISSIONS.MEDIA_DELETE) ? (
<button
type="button"
onClick={() => void remove(asset)}
className="rounded-card bg-ink-950/80 absolute right-1 top-1 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-widest text-white opacity-0 transition-opacity group-hover:opacity-100"
>
{t('delete')}
</button>
) : null}
</li>
))}
</ul>
)}
</div>
);
}
@@ -0,0 +1,262 @@
'use client';
import Image from 'next/image';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { isApiClientError } from '@sport/api-client';
import {
DEFAULT_LOCALE,
PERMISSIONS,
type AdminProductDetail,
type MediaAssetSummary,
} from '@sport/types';
import { Button, Skeleton, cn } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
interface Slot {
mediaId: string;
url: string;
optionValueId: string | null;
}
/**
* Product imagery: which assets, in what order, and which colourway each belongs
* to.
*
* That last part is what makes the storefront gallery swap when a shopper picks
* a colour — `ProductImage.optionValueId` is the link, and this is the only
* place it gets set.
*/
export function ImageManager({
product,
onChange,
}: {
product: AdminProductDetail;
onChange: (product: AdminProductDetail) => void;
}) {
const t = useTranslations('editor');
const { can } = useSession();
const [slots, setSlots] = useState<Slot[]>(() =>
product.images.map((image) => ({
mediaId: image.mediaId,
url: image.url,
optionValueId: image.optionValueId,
})),
);
const [library, setLibrary] = useState<MediaAssetSummary[] | null>(null);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string | null>(null);
// Colourway options an image can be attached to.
const colourValues = product.options.find((option) => option.key === 'colour')?.values ?? [];
useEffect(() => {
let cancelled = false;
async function loadLibrary() {
try {
const result = await browserApi.catalogAdmin.listMedia({ perPage: 60 });
if (!cancelled) setLibrary([...result.items]);
} catch (caught) {
if (!cancelled) setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}
void loadLibrary();
return () => {
cancelled = true;
};
}, [t]);
async function save() {
setSaving(true);
setError(null);
setSaved(false);
try {
const updated = await browserApi.catalogAdmin.setImages(
product.id,
// Position is the array index — the order shown is the order stored.
slots.map((slot, index) => ({
mediaId: slot.mediaId,
position: index,
optionValueId: slot.optionValueId,
})),
);
setSlots(
updated.images.map((image) => ({
mediaId: image.mediaId,
url: image.url,
optionValueId: image.optionValueId,
})),
);
onChange(updated);
setSaved(true);
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('saveFailed'));
} finally {
setSaving(false);
}
}
function move(index: number, direction: -1 | 1) {
const target = index + direction;
if (target < 0 || target >= slots.length) return;
setSlots((current) => {
const moved = current[index];
if (!moved) return current;
const next = [...current];
next.splice(index, 1);
next.splice(target, 0, moved);
return next;
});
}
const editable = can(PERMISSIONS.PRODUCT_UPDATE);
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<h3 className="text-sm font-semibold uppercase tracking-widest">{t('attached')}</h3>
{saved ? <span className="text-success ml-auto text-xs">{t('saved')}</span> : null}
{editable ? (
<Button
size="sm"
className={cn(!saved && 'ml-auto')}
disabled={saving}
onClick={() => void save()}
>
{saving ? t('saving') : t('saveImages')}
</Button>
) : null}
</div>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
{slots.length === 0 ? (
<p className="text-ink-500 text-sm">{t('noImages')}</p>
) : (
<ul className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
{slots.map((slot, index) => (
<li key={`${slot.mediaId}-${index}`} className="border-ink-200 space-y-2 border p-2">
<div className="bg-ink-100 relative aspect-square overflow-hidden">
<Image src={slot.url} alt="" fill sizes="16vw" className="object-cover" />
{index === 0 ? (
<span className="bg-ink-950 absolute left-1 top-1 px-1.5 py-0.5 text-[0.5rem] font-semibold uppercase tracking-widest text-white">
{t('primary')}
</span>
) : null}
</div>
{colourValues.length > 0 ? (
<select
value={slot.optionValueId ?? ''}
disabled={!editable}
onChange={(event) =>
setSlots((current) =>
current.map((item, i) =>
i === index ? { ...item, optionValueId: event.target.value || null } : item,
),
)
}
aria-label={t('colourway')}
className="border-ink-200 w-full border px-1 py-1 text-xs"
>
<option value="">{t('anyColourway')}</option>
{colourValues.map((value) => (
<option key={value.id} value={value.id}>
{value.labels[DEFAULT_LOCALE] ?? value.value}
</option>
))}
</select>
) : null}
{editable ? (
<div className="flex justify-between gap-1">
<button
type="button"
onClick={() => move(index, -1)}
className="text-ink-500 hover:text-ink-950 px-1 text-xs"
aria-label={t('moveLeft')}
>
←
</button>
<button
type="button"
onClick={() => setSlots((c) => c.filter((_, i) => i !== index))}
className="text-danger text-xs"
>
{t('remove')}
</button>
<button
type="button"
onClick={() => move(index, 1)}
className="text-ink-500 hover:text-ink-950 px-1 text-xs"
aria-label={t('moveRight')}
>
→
</button>
</div>
) : null}
</li>
))}
</ul>
)}
{editable ? (
<div className="space-y-3">
<h3 className="text-sm font-semibold uppercase tracking-widest">{t('library')}</h3>
{!library ? (
<div className="grid grid-cols-4 gap-3 lg:grid-cols-8" aria-busy="true">
{Array.from({ length: 8 }, (_, index) => (
<Skeleton key={index} className="aspect-square w-full" />
))}
</div>
) : (
<ul className="grid grid-cols-4 gap-3 lg:grid-cols-8">
{library.map((asset) => {
const used = slots.some((slot) => slot.mediaId === asset.id);
return (
<li key={asset.id}>
<button
type="button"
disabled={used}
onClick={() =>
setSlots((current) => [
...current,
{ mediaId: asset.id, url: asset.url, optionValueId: null },
])
}
className={cn(
'bg-ink-100 relative block aspect-square w-full overflow-hidden border transition-colors',
used
? 'border-ink-200 cursor-not-allowed opacity-30'
: 'border-ink-200 hover:border-ink-950',
)}
title={asset.altText ?? asset.storageKey}
>
<Image src={asset.url} alt="" fill sizes="12vw" className="object-cover" />
</button>
</li>
);
})}
</ul>
)}
</div>
) : null}
</div>
);
}
@@ -0,0 +1,174 @@
'use client';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { isApiClientError } from '@sport/api-client';
import { PERMISSIONS, type AdminProductDetail } from '@sport/types';
import { Badge, Button, Skeleton, cn } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
import { ImageManager } from './image-manager';
import { ProductForm } from './product-form';
import { VariantGrid } from './variant-grid';
type Tab = 'details' | 'variants' | 'images';
const STATUS_VARIANT = { ACTIVE: 'success', DRAFT: 'warning', ARCHIVED: 'neutral' } as const;
/**
* The editor shell.
*
* Loads the product client-side rather than on the server because every tab
* mutates it and then needs the authoritative version back — the API returns
* the full product from each write, so the page can stay in step without a
* round-trip through server rendering.
*/
export function ProductEditor({ productId }: { productId: string }) {
const t = useTranslations('editor');
const { can } = useSession();
const [product, setProduct] = useState<AdminProductDetail | null>(null);
const [tab, setTab] = useState<Tab>('details');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
let cancelled = false;
async function load() {
try {
const result = await browserApi.catalogAdmin.getProduct(productId);
if (!cancelled) setProduct(result);
} catch (caught) {
if (!cancelled) setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}
void load();
return () => {
cancelled = true;
};
}, [productId, t]);
async function setStatus(status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED') {
setBusy(true);
setError(null);
try {
setProduct(await browserApi.catalogAdmin.setStatus(productId, status));
} catch (caught) {
// Publishing without variants is rejected by the API — surface that
// reason rather than a generic failure.
setError(isApiClientError(caught) ? caught.message : t('saveFailed'));
} finally {
setBusy(false);
}
}
if (error && !product) {
return (
<p role="alert" className="text-danger text-sm">
{error}
</p>
);
}
if (!product) {
return (
<div className="space-y-4" aria-busy="true">
<Skeleton className="h-10 w-72" />
<Skeleton className="h-64 w-full" />
</div>
);
}
const name = product.translations.vi?.name ?? product.translations.en?.name ?? '—';
return (
<div className="space-y-6">
<header className="flex flex-wrap items-center gap-3">
<Link href="/products" className="text-ink-500 hover:text-ink-950 text-sm">
← {t('backToList')}
</Link>
<h1 className="text-xl font-bold">{name}</h1>
<Badge variant={STATUS_VARIANT[product.status]}>{product.status}</Badge>
{can(PERMISSIONS.PRODUCT_PUBLISH) ? (
<div className="ml-auto flex gap-2">
{product.status === 'ACTIVE' ? (
<Button
size="sm"
variant="secondary"
disabled={busy}
onClick={() => void setStatus('DRAFT')}
>
{t('unpublish')}
</Button>
) : (
<Button size="sm" disabled={busy} onClick={() => void setStatus('ACTIVE')}>
{t('publish')}
</Button>
)}
{product.status !== 'ARCHIVED' ? (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => void setStatus('ARCHIVED')}
>
{t('archive')}
</Button>
) : null}
</div>
) : null}
</header>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
<nav className="border-ink-200 flex gap-1 border-b">
{(['details', 'variants', 'images'] as const).map((value) => (
<button
key={value}
type="button"
onClick={() => setTab(value)}
aria-current={tab === value ? 'page' : undefined}
className={cn(
'-mb-px border-b-2 px-4 py-2 text-sm font-medium transition-colors',
tab === value
? 'border-ink-950 text-ink-950'
: 'text-ink-500 hover:text-ink-950 border-transparent',
)}
>
{t(`tab.${value}`)}
{value === 'variants' ? (
<span className="text-ink-400 ml-2 text-xs">{product.variants.length}</span>
) : null}
</button>
))}
</nav>
{tab === 'details' ? <ProductForm product={product} onChange={setProduct} /> : null}
{/*
Keyed on the matrix shape: editing the options regenerates variants, and
the grid seeds its draft from props exactly once. Remounting it when the
set of variant ids changes is what keeps the inputs honest.
*/}
{tab === 'variants' ? (
<VariantGrid
key={product.variants.map((variant) => variant.id).join(',')}
product={product}
onChange={setProduct}
/>
) : null}
{tab === 'images' ? <ImageManager product={product} onChange={setProduct} /> : null}
</div>
);
}
@@ -0,0 +1,523 @@
'use client';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { isApiClientError } from '@sport/api-client';
import {
DEFAULT_LOCALE,
LOCALES,
LOCALE_LABELS,
type AdminProductDetail,
type Locale,
} from '@sport/types';
import { Badge, Button, Input, cn } from '@sport/ui';
import { browserApi } from '@/lib/api';
const GENDERS = ['MEN', 'WOMEN', 'KIDS', 'UNISEX'] as const;
const SPORTS = ['RUNNING', 'FOOTBALL', 'TRAINING', 'GYM', 'BADMINTON', 'LIFESTYLE'] as const;
interface DraftTranslation {
name: string;
shortDescription: string;
description: string;
}
interface DraftValue {
value: string;
swatchHex: string;
labels: Record<Locale, string>;
}
interface DraftOption {
key: string;
names: Record<Locale, string>;
values: DraftValue[];
}
const emptyTranslations = (): Record<Locale, DraftTranslation> =>
Object.fromEntries(
LOCALES.map((locale) => [locale, { name: '', shortDescription: '', description: '' }]),
) as Record<Locale, DraftTranslation>;
/** A sensible starting point: every apparel product has these two axes. */
const starterOptions = (): DraftOption[] => [
{
key: 'colour',
names: { vi: 'Màu sắc', en: 'Colour' },
values: [{ value: 'black', swatchHex: '#111111', labels: { vi: 'Đen', en: 'Black' } }],
},
{
key: 'size',
names: { vi: 'Kích cỡ', en: 'Size' },
values: [{ value: 'm', swatchHex: '', labels: { vi: 'M', en: 'M' } }],
},
];
/**
* Create and edit form for a product's content and option axes.
*
* Saving options re-runs the variant matrix on the server, so this form owns
* *what varies* while the variant grid owns *what each combination costs*.
* Splitting them that way means editing a price never risks regenerating the
* matrix, and adding a colour never silently overwrites a price.
*/
export function ProductForm({
product,
onChange,
}: {
product?: AdminProductDetail;
/**
* Hands the saved product back to the editor shell, which owns it. Without
* this the shell keeps rendering the version it loaded, and a tab that
* compares its draft against that stale prop never sees its own save.
*/
onChange?: (product: AdminProductDetail) => void;
}) {
const t = useTranslations('editor');
const router = useRouter();
const [locale, setLocale] = useState<Locale>(DEFAULT_LOCALE);
const [translations, setTranslations] = useState<Record<Locale, DraftTranslation>>(() => {
if (!product) return emptyTranslations();
const seeded = emptyTranslations();
for (const key of LOCALES) {
const existing = product.translations[key];
if (existing) {
seeded[key] = {
name: existing.name,
shortDescription: existing.shortDescription ?? '',
description: existing.description ?? '',
};
}
}
return seeded;
});
const [genders, setGenders] = useState<string[]>(() => [...(product?.genderTargets ?? [])]);
const [sports, setSports] = useState<string[]>(() => [...(product?.sportTypes ?? [])]);
const [skuPrefix, setSkuPrefix] = useState('');
const [basePrice, setBasePrice] = useState('0');
const [options, setOptions] = useState<DraftOption[]>(() => {
if (!product || product.options.length === 0) return starterOptions();
return product.options.map((option) => ({
key: option.key,
names: Object.fromEntries(LOCALES.map((key) => [key, option.names[key] ?? ''])) as Record<
Locale,
string
>,
values: option.values.map((value) => ({
value: value.value,
swatchHex: value.swatchHex ?? '',
labels: Object.fromEntries(LOCALES.map((key) => [key, value.labels[key] ?? ''])) as Record<
Locale,
string
>,
})),
}));
});
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string | null>(null);
function buildPayload() {
// Only locales the operator actually filled in are sent. Posting an empty
// name would create a translation row that resolves to a blank product page
// in that language — worse than having no translation at all, because the
// fallback would no longer apply.
const filled = Object.fromEntries(
LOCALES.filter((key) => translations[key].name.trim().length > 0).map((key) => [
key,
{
name: translations[key].name.trim(),
shortDescription: translations[key].shortDescription.trim() || null,
description: translations[key].description.trim() || null,
},
]),
);
return {
translations: filled,
genderTargets: genders,
sportTypes: sports,
...(skuPrefix.trim() ? { skuPrefix: skuPrefix.trim() } : {}),
basePriceAmount: Number.parseInt(basePrice, 10) || 0,
options: options.map((option, index) => ({
key: option.key,
position: index,
names: Object.fromEntries(
LOCALES.filter((key) => option.names[key].trim()).map((key) => [
key,
option.names[key].trim(),
]),
),
values: option.values.map((value, valueIndex) => ({
value: value.value,
position: valueIndex,
swatchHex: value.swatchHex.trim() || null,
labels: Object.fromEntries(
LOCALES.filter((key) => value.labels[key].trim()).map((key) => [
key,
value.labels[key].trim(),
]),
),
})),
})),
};
}
async function save() {
setSaving(true);
setError(null);
setSaved(false);
try {
const payload = buildPayload();
if (product) {
onChange?.(await browserApi.catalogAdmin.updateProduct(product.id, payload));
setSaved(true);
} else {
const created = await browserApi.catalogAdmin.createProduct(payload);
// Straight into the editor: the operator's next step is always pricing
// the matrix that was just generated.
router.push(`/products/${created.id}`);
}
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('saveFailed'));
} finally {
setSaving(false);
}
}
return (
<div className="space-y-8">
{/* ---- Content, per locale ---- */}
<section className="border-ink-200 space-y-4 border bg-white p-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="text-sm font-semibold uppercase tracking-widest">{t('content')}</h2>
<div className="flex gap-1">
{LOCALES.map((key) => (
<button
key={key}
type="button"
onClick={() => setLocale(key)}
className={cn(
'rounded-card border px-3 py-1.5 text-xs font-medium transition-colors',
locale === key
? 'border-ink-950 bg-ink-950 text-white'
: 'border-ink-200 text-ink-600 hover:border-ink-400',
)}
>
{LOCALE_LABELS[key]}
{translations[key].name.trim() ? '' : ' •'}
</button>
))}
</div>
</div>
<p className="text-ink-400 text-xs">{t('localeHint')}</p>
<label className="block space-y-1.5">
<span className="text-xs font-semibold uppercase tracking-widest">{t('name')}</span>
<Input
value={translations[locale].name}
onChange={(event) =>
setTranslations((current) => ({
...current,
[locale]: { ...current[locale], name: event.target.value },
}))
}
/>
</label>
<label className="block space-y-1.5">
<span className="text-xs font-semibold uppercase tracking-widest">
{t('shortDescription')}
</span>
<Input
value={translations[locale].shortDescription}
onChange={(event) =>
setTranslations((current) => ({
...current,
[locale]: { ...current[locale], shortDescription: event.target.value },
}))
}
/>
</label>
<label className="block space-y-1.5">
<span className="text-xs font-semibold uppercase tracking-widest">
{t('description')}
</span>
<textarea
rows={5}
value={translations[locale].description}
onChange={(event) =>
setTranslations((current) => ({
...current,
[locale]: { ...current[locale], description: event.target.value },
}))
}
className="border-ink-300 focus:border-ink-950 w-full border bg-white px-4 py-3 text-sm focus:outline-none"
/>
</label>
</section>
{/* ---- Merchandising facets ---- */}
<section className="border-ink-200 space-y-4 border bg-white p-6">
<h2 className="text-sm font-semibold uppercase tracking-widest">{t('facets')}</h2>
<Chips label={t('gender')} all={GENDERS} selected={genders} onChange={setGenders} />
<Chips label={t('sport')} all={SPORTS} selected={sports} onChange={setSports} />
</section>
{/* ---- Options ---- */}
<section className="border-ink-200 space-y-4 border bg-white p-6">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold uppercase tracking-widest">{t('options')}</h2>
<Button
size="sm"
variant="secondary"
onClick={() =>
setOptions((current) => [
...current,
{ key: `option_${current.length + 1}`, names: { vi: '', en: '' }, values: [] },
])
}
>
{t('addOption')}
</Button>
</div>
<p className="text-ink-400 text-xs">{t('optionsHint')}</p>
{options.map((option, optionIndex) => (
<OptionEditor
key={optionIndex}
option={option}
locale={locale}
onChange={(next) =>
setOptions((current) => current.map((item, i) => (i === optionIndex ? next : item)))
}
onRemove={() => setOptions((current) => current.filter((_, i) => i !== optionIndex))}
/>
))}
</section>
{!product ? (
<section className="border-ink-200 space-y-4 border bg-white p-6">
<h2 className="text-sm font-semibold uppercase tracking-widest">{t('generation')}</h2>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block space-y-1.5">
<span className="text-xs font-semibold uppercase tracking-widest">
{t('skuPrefix')}
</span>
<Input
value={skuPrefix}
onChange={(event) => setSkuPrefix(event.target.value)}
placeholder="VEL-ART"
/>
</label>
<label className="block space-y-1.5">
<span className="text-xs font-semibold uppercase tracking-widest">
{t('basePrice')}
</span>
<Input
type="number"
value={basePrice}
onChange={(event) => setBasePrice(event.target.value)}
/>
</label>
</div>
<p className="text-ink-400 text-xs">{t('generationHint')}</p>
</section>
) : null}
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
<div className="flex items-center gap-3">
<Button size="lg" disabled={saving} onClick={() => void save()}>
{saving ? t('saving') : product ? t('save') : t('create')}
</Button>
{product ? <Badge variant="outline">{t('matrixWarning')}</Badge> : null}
{saved ? <span className="text-success text-xs">{t('saved')}</span> : null}
</div>
</div>
);
}
function Chips({
label,
all,
selected,
onChange,
}: {
label: string;
all: readonly string[];
selected: string[];
onChange: (next: string[]) => void;
}) {
return (
<div className="space-y-2">
<span className="text-xs font-semibold uppercase tracking-widest">{label}</span>
<div className="flex flex-wrap gap-2">
{all.map((item) => {
const active = selected.includes(item);
return (
<button
key={item}
type="button"
aria-pressed={active}
onClick={() =>
onChange(active ? selected.filter((x) => x !== item) : [...selected, item])
}
className={cn(
'rounded-card border px-3 py-1.5 text-xs font-medium transition-colors',
active
? 'border-ink-950 bg-ink-950 text-white'
: 'border-ink-200 text-ink-600 hover:border-ink-400',
)}
>
{item}
</button>
);
})}
</div>
</div>
);
}
function OptionEditor({
option,
locale,
onChange,
onRemove,
}: {
option: DraftOption;
locale: Locale;
onChange: (next: DraftOption) => void;
onRemove: () => void;
}) {
const t = useTranslations('editor');
return (
<div className="border-ink-200 space-y-3 border p-4">
<div className="flex flex-wrap items-end gap-3">
<label className="space-y-1.5">
<span className="text-ink-500 text-[0.625rem] font-semibold uppercase tracking-widest">
{t('optionKey')}
</span>
<Input
value={option.key}
onChange={(event) => onChange({ ...option, key: event.target.value })}
className="w-40"
/>
</label>
<label className="space-y-1.5">
<span className="text-ink-500 text-[0.625rem] font-semibold uppercase tracking-widest">
{t('optionName')}
</span>
<Input
value={option.names[locale]}
onChange={(event) =>
onChange({ ...option, names: { ...option.names, [locale]: event.target.value } })
}
className="w-56"
/>
</label>
<Button size="sm" variant="ghost" onClick={onRemove} className="ml-auto">
{t('removeOption')}
</Button>
</div>
<ul className="space-y-2">
{option.values.map((value, index) => (
<li key={index} className="flex flex-wrap items-end gap-2">
<Input
value={value.value}
onChange={(event) =>
onChange({
...option,
values: option.values.map((item, i) =>
i === index ? { ...item, value: event.target.value } : item,
),
})
}
placeholder={t('valueKey')}
aria-label={t('valueKey')}
className="w-32"
/>
<Input
value={value.labels[locale]}
onChange={(event) =>
onChange({
...option,
values: option.values.map((item, i) =>
i === index
? { ...item, labels: { ...item.labels, [locale]: event.target.value } }
: item,
),
})
}
placeholder={t('valueLabel')}
aria-label={t('valueLabel')}
className="w-44"
/>
<Input
value={value.swatchHex}
onChange={(event) =>
onChange({
...option,
values: option.values.map((item, i) =>
i === index ? { ...item, swatchHex: event.target.value } : item,
),
})
}
placeholder="#111111"
aria-label={t('swatch')}
className="w-28"
/>
{value.swatchHex ? (
<span
className="border-ink-200 size-8 shrink-0 rounded-full border"
style={{ backgroundColor: value.swatchHex }}
aria-hidden
/>
) : null}
<Button
size="sm"
variant="ghost"
onClick={() =>
onChange({ ...option, values: option.values.filter((_, i) => i !== index) })
}
>
{t('removeValue')}
</Button>
</li>
))}
</ul>
<Button
size="sm"
variant="secondary"
onClick={() =>
onChange({
...option,
values: [...option.values, { value: '', swatchHex: '', labels: { vi: '', en: '' } }],
})
}
>
{t('addValue')}
</Button>
</div>
);
}
@@ -0,0 +1,220 @@
'use client';
import Image from 'next/image';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { useCallback, useEffect, useState } from 'react';
import { isApiClientError } from '@sport/api-client';
import { MINOR_UNIT_SCALE, PERMISSIONS, type AdminProductListItem, type Money } from '@sport/types';
import { Badge, Button, Input, Skeleton, cn } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
const STATUS_VARIANT = {
ACTIVE: 'success',
DRAFT: 'warning',
ARCHIVED: 'neutral',
} as const;
/** Admin money display. VND has no minor unit, so this is a plain group format. */
function formatMoney(money: Money): string {
const scale = MINOR_UNIT_SCALE[money.currency];
return new Intl.NumberFormat('vi-VN', {
style: 'currency',
currency: money.currency,
minimumFractionDigits: scale,
maximumFractionDigits: scale,
}).format(money.amount / 10 ** scale);
}
export function ProductsTable() {
const t = useTranslations('catalog');
const { can } = useSession();
const [items, setItems] = useState<AdminProductListItem[] | null>(null);
const [total, setTotal] = useState(0);
const [query, setQuery] = useState('');
const [status, setStatus] = useState<'' | 'DRAFT' | 'ACTIVE' | 'ARCHIVED'>('');
const [error, setError] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const result = await browserApi.catalogAdmin.listProducts({
perPage: 50,
...(query ? { q: query } : {}),
...(status ? { status } : {}),
});
setItems([...result.items]);
setTotal(result.pageInfo.totalItems);
setError(null);
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
}
}, [query, status, t]);
useEffect(() => {
// Debounced so typing in the search box does not fire a request per keystroke.
const timer = setTimeout(() => void load(), 250);
return () => clearTimeout(timer);
}, [load]);
async function toggleStatus(product: AdminProductListItem) {
setBusyId(product.id);
try {
await browserApi.catalogAdmin.setStatus(
product.id,
product.status === 'ACTIVE' ? 'DRAFT' : 'ACTIVE',
);
await load();
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('actionFailed'));
} finally {
setBusyId(null);
}
}
if (!can(PERMISSIONS.PRODUCT_READ)) {
return <p className="text-ink-500 text-sm">{t('noPermission')}</p>;
}
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<Input
type="search"
placeholder={t('searchPlaceholder')}
value={query}
onChange={(event) => setQuery(event.target.value)}
className="max-w-xs"
/>
<div className="flex gap-1">
{(['', 'ACTIVE', 'DRAFT', 'ARCHIVED'] as const).map((value) => (
<button
key={value || 'all'}
type="button"
onClick={() => setStatus(value)}
className={cn(
'rounded-card border px-3 py-1.5 text-xs font-medium transition-colors',
status === value
? 'border-ink-950 bg-ink-950 text-white'
: 'border-ink-200 text-ink-600 hover:border-ink-400',
)}
>
{value ? t(`status.${value}`) : t('status.ALL')}
</button>
))}
</div>
<span className="text-ink-500 ml-auto text-xs">{t('count', { count: total })}</span>
{can(PERMISSIONS.PRODUCT_CREATE) ? (
<Button size="sm" asChild>
<Link href="/products/new">{t('newProduct')}</Link>
</Button>
) : null}
</div>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
{!items ? (
<div className="space-y-2" aria-busy="true">
<Skeleton className="h-14 w-full" />
<Skeleton className="h-14 w-full" />
<Skeleton className="h-14 w-full" />
</div>
) : items.length === 0 ? (
<p className="text-ink-500 py-12 text-center text-sm">{t('empty')}</p>
) : (
<div className="border-ink-200 overflow-x-auto border bg-white">
<table className="min-w-4xl w-full text-sm">
<thead className="border-ink-200 bg-ink-50 border-b text-left">
<tr className="text-ink-500 text-[0.625rem] uppercase tracking-widest">
<th className="px-4 py-3 font-semibold">{t('table.product')}</th>
<th className="px-4 py-3 font-semibold">{t('table.status')}</th>
<th className="px-4 py-3 font-semibold">{t('table.variants')}</th>
<th className="px-4 py-3 font-semibold">{t('table.stock')}</th>
<th className="px-4 py-3 font-semibold">{t('table.price')}</th>
<th className="px-4 py-3 font-semibold" />
</tr>
</thead>
<tbody className="divide-ink-100 divide-y">
{items.map((product) => (
<tr key={product.id}>
<td className="px-4 py-3">
<div className="flex items-center gap-3">
<div className="bg-ink-100 relative size-10 shrink-0 overflow-hidden">
{product.thumbnailUrl ? (
<Image
src={product.thumbnailUrl}
alt=""
fill
sizes="40px"
className="object-cover"
/>
) : null}
</div>
<div className="min-w-0">
<Link
href={`/products/${product.id}`}
className="block truncate font-medium hover:underline"
>
{product.name}
</Link>
<p className="text-ink-400 truncate text-xs">
{product.brandName ?? '—'} · {product.slug}
</p>
</div>
</div>
</td>
<td className="px-4 py-3">
<Badge variant={STATUS_VARIANT[product.status]}>
{t(`status.${product.status}`)}
</Badge>
</td>
<td className="text-ink-600 px-4 py-3">{product.variantCount}</td>
<td className="px-4 py-3">
<span className={cn(product.totalStock === 0 && 'text-danger')}>
{product.totalStock}
</span>
</td>
<td className="text-ink-600 px-4 py-3">
{product.priceRange
? product.priceRange.min.amount === product.priceRange.max.amount
? formatMoney(product.priceRange.min)
: `${formatMoney(product.priceRange.min)} – ${formatMoney(product.priceRange.max)}`
: '—'}
</td>
<td className="px-4 py-3">
{/* Flex, not inline spacing: the labels are translated, and
in Vietnamese "NGỪNG BÁN" is long enough to wrap the two
buttons onto separate lines without an explicit row. */}
<div className="flex items-center justify-end gap-2">
<Button size="sm" variant="secondary" asChild>
<Link href={`/products/${product.id}`}>{t('edit')}</Link>
</Button>
{can(PERMISSIONS.PRODUCT_PUBLISH) ? (
<Button
size="sm"
variant={product.status === 'ACTIVE' ? 'ghost' : 'default'}
disabled={busyId === product.id}
onClick={() => void toggleStatus(product)}
>
{product.status === 'ACTIVE' ? t('unpublish') : t('publish')}
</Button>
) : null}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,217 @@
'use client';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { isApiClientError, type VariantPatch } from '@sport/api-client';
import { PERMISSIONS, type AdminProductDetail, type AdminProductVariant } from '@sport/types';
import { Badge, Button, Input, cn } from '@sport/ui';
import { useSession } from '@/features/auth/session-provider';
import { browserApi } from '@/lib/api';
type Draft = Record<string, { sku: string; price: string; sale: string }>;
function toDraft(variants: readonly AdminProductVariant[]): Draft {
return Object.fromEntries(
variants.map((variant) => [
variant.id,
{
sku: variant.sku,
price: String(variant.priceAmount),
sale: variant.salePriceAmount === null ? '' : String(variant.salePriceAmount),
},
]),
);
}
/**
* The variant matrix, editable in place.
*
* This is where ADR-0003 becomes an interface: one row per purchasable
* combination, each with its own SKU, price and stock. Stock is shown but not
* editable here — it moves through inventory so that every change carries a
* reason and lands in the ledger.
*
* Only rows the operator actually changed are sent. Posting all 60 rows on
* every save would make the audit entry useless and would overwrite a
* colleague's concurrent edit with stale values from this page's load.
*/
export function VariantGrid({
product,
onChange,
}: {
product: AdminProductDetail;
onChange: (product: AdminProductDetail) => void;
}) {
const t = useTranslations('editor');
const { can } = useSession();
const [draft, setDraft] = useState<Draft>(() => toDraft(product.variants));
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const active = product.variants.filter((variant) => variant.status === 'ACTIVE');
const archived = product.variants.filter((variant) => variant.status === 'ARCHIVED');
// Pairs rather than variants alone: carrying the draft row along proves it
// exists, so building the patch below needs no assertion.
const dirty = product.variants.flatMap((variant) => {
const row = draft[variant.id];
if (!row) return [];
const changed =
row.sku !== variant.sku ||
row.price !== String(variant.priceAmount) ||
row.sale !== (variant.salePriceAmount === null ? '' : String(variant.salePriceAmount));
return changed ? [{ variant, row }] : [];
});
function patchRow(id: string, patch: Partial<Draft[string]>) {
setDraft((current) => {
const row = current[id];
return row ? { ...current, [id]: { ...row, ...patch } } : current;
});
}
async function save() {
if (dirty.length === 0) return;
setSaving(true);
setError(null);
setSaved(false);
try {
const patches: VariantPatch[] = dirty.map(({ variant, row }) => {
return {
id: variant.id,
sku: row.sku.trim(),
priceAmount: Number.parseInt(row.price, 10) || 0,
// An empty sale field means "no sale", which is null rather than 0 —
// a sale price of zero would make the product free.
salePriceAmount: row.sale.trim() === '' ? null : Number.parseInt(row.sale, 10),
};
});
const updated = await browserApi.catalogAdmin.updateVariants(product.id, patches);
// Both, and in this order: the draft holds what the inputs display, and
// `dirty` compares it against the product. Resetting only the draft would
// leave every saved row comparing against pre-save values and therefore
// still marked dirty.
setDraft(toDraft(updated.variants));
onChange(updated);
setSaved(true);
} catch (caught) {
setError(isApiClientError(caught) ? caught.message : t('saveFailed'));
} finally {
setSaving(false);
}
}
if (product.variants.length === 0) {
return <p className="text-ink-500 text-sm">{t('noVariants')}</p>;
}
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<p className="text-ink-500 text-xs">{t('variantCount', { count: active.length })}</p>
{archived.length > 0 ? (
<Badge variant="neutral">{t('archivedCount', { count: archived.length })}</Badge>
) : null}
<span className="ml-auto flex items-center gap-3">
{saved ? <span className="text-success text-xs">{t('saved')}</span> : null}
{can(PERMISSIONS.PRODUCT_UPDATE) ? (
<Button size="sm" disabled={saving || dirty.length === 0} onClick={() => void save()}>
{saving ? t('saving') : t('saveChanged', { count: dirty.length })}
</Button>
) : null}
</span>
</div>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
<div className="border-ink-200 overflow-x-auto border bg-white">
<table className="min-w-3xl w-full text-sm">
<thead className="border-ink-200 bg-ink-50 border-b text-left">
<tr className="text-ink-500 text-[0.625rem] uppercase tracking-widest">
<th className="px-4 py-3 font-semibold">{t('grid.variant')}</th>
<th className="px-4 py-3 font-semibold">{t('grid.sku')}</th>
<th className="px-4 py-3 font-semibold">{t('grid.price')}</th>
<th className="px-4 py-3 font-semibold">{t('grid.sale')}</th>
<th className="px-4 py-3 font-semibold">{t('grid.stock')}</th>
</tr>
</thead>
<tbody className="divide-ink-100 divide-y">
{product.variants.map((variant) => {
const row = draft[variant.id];
const isArchived = variant.status === 'ARCHIVED';
const changed = dirty.some((item) => item.variant.id === variant.id);
return (
<tr
key={variant.id}
className={cn(isArchived && 'opacity-50', changed && 'bg-volt-50')}
>
<td className="px-4 py-2">
<span className="font-medium">{variant.title}</span>
{isArchived ? (
<Badge variant="neutral" className="ml-2">
{t('archived')}
</Badge>
) : null}
</td>
<td className="px-4 py-2">
<Input
value={row?.sku ?? ''}
disabled={isArchived || !can(PERMISSIONS.PRODUCT_UPDATE)}
onChange={(event) => patchRow(variant.id, { sku: event.target.value })}
aria-label={`${t('grid.sku')} ${variant.title}`}
className="h-9 w-44 font-mono text-xs"
/>
</td>
<td className="px-4 py-2">
<Input
type="number"
value={row?.price ?? ''}
disabled={isArchived || !can(PERMISSIONS.PRODUCT_UPDATE)}
onChange={(event) => patchRow(variant.id, { price: event.target.value })}
aria-label={`${t('grid.price')} ${variant.title}`}
className="h-9 w-32"
/>
</td>
<td className="px-4 py-2">
<Input
type="number"
value={row?.sale ?? ''}
placeholder="—"
disabled={isArchived || !can(PERMISSIONS.PRODUCT_UPDATE)}
onChange={(event) => patchRow(variant.id, { sale: event.target.value })}
aria-label={`${t('grid.sale')} ${variant.title}`}
className="h-9 w-32"
/>
</td>
<td className="px-4 py-2">
{/* Read-only by design: stock moves through inventory. */}
<span className={cn(variant.available === 0 && 'text-danger')}>
{variant.available}
</span>
<span className="text-ink-400 ml-1 text-xs">/ {variant.onHand}</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p className="text-ink-400 text-xs">{t('stockHint')}</p>
</div>
);
}
+122
View File
@@ -104,5 +104,127 @@
"status": "Status",
"lastLogin": "Last sign-in"
}
},
"catalog": {
"searchPlaceholder": "Search name or SKU",
"count": "{count} products",
"empty": "No products match.",
"loadFailed": "Could not load products.",
"actionFailed": "That action failed.",
"noPermission": "You do not have permission to view this.",
"publish": "Publish",
"unpublish": "Unpublish",
"status": {
"ALL": "All",
"ACTIVE": "Active",
"DRAFT": "Draft",
"ARCHIVED": "Archived"
},
"table": {
"product": "Product",
"status": "Status",
"variants": "Variants",
"stock": "Stock",
"price": "Price"
},
"newProduct": "New product",
"edit": "Edit"
},
"media": {
"chooseFiles": "Choose files",
"uploadHint": "PNG, JPEG, WebP or AVIF, up to 25 MB. Uploaded straight to storage.",
"uploading": "uploading…",
"uploadFailed": "Upload failed.",
"deleteFailed": "Could not delete.",
"loadFailed": "Could not load the library.",
"empty": "No media yet.",
"delete": "Delete",
"noPermission": "You do not have permission to view this."
},
"inventory": {
"searchPlaceholder": "Search SKU or product",
"lowStockOnly": "Low stock only",
"loadFailed": "Could not load stock levels.",
"adjustFailed": "Adjustment failed.",
"noPermission": "You do not have permission to view this.",
"adjust": "Adjust",
"apply": "Apply",
"cancel": "Cancel",
"outOfStock": "Out of stock",
"deltaLabel": "Quantity change",
"table": {
"sku": "SKU",
"product": "Product",
"onHand": "On hand",
"reserved": "Reserved",
"available": "Available"
}
},
"editor": {
"createTitle": "New product",
"editTitle": "Edit product",
"createHint": "Fill in the content and the option axes. Saving generates one variant per combination, which you then price on the Variants tab.",
"backToList": "Products",
"content": "Content",
"facets": "Merchandising",
"options": "Options",
"generation": "Variant generation",
"localeHint": "A language with no name is skipped — the storefront falls back per field.",
"name": "Name",
"shortDescription": "Short description",
"description": "Description",
"gender": "Gender",
"sport": "Sport",
"optionsHint": "Every combination of these values becomes a purchasable variant with its own SKU, price and stock.",
"addOption": "Add option",
"removeOption": "Remove",
"optionKey": "Key",
"optionName": "Label",
"addValue": "Add value",
"removeValue": "Remove",
"valueKey": "value",
"valueLabel": "Label",
"swatch": "Swatch",
"skuPrefix": "SKU prefix",
"basePrice": "Base price (VND)",
"generationHint": "Applied to every generated variant. Adjust individual prices afterwards.",
"save": "Save changes",
"create": "Create product",
"saving": "Saving…",
"saved": "Saved",
"saveFailed": "Could not save.",
"loadFailed": "Could not load this product.",
"matrixWarning": "Saving re-runs the variant matrix",
"publish": "Publish",
"unpublish": "Unpublish",
"archive": "Archive",
"tab": {
"details": "Details",
"variants": "Variants",
"images": "Images"
},
"noVariants": "No variants yet. Add option values on the Details tab.",
"variantCount": "{count} active",
"archivedCount": "{count} archived",
"archived": "Archived",
"saveChanged": "Save {count} change(s)",
"grid": {
"variant": "Variant",
"sku": "SKU",
"price": "Price",
"sale": "Sale price",
"stock": "Available / on hand"
},
"stockHint": "Stock is read-only here. Adjust it from Inventory so every change lands in the ledger with a reason.",
"attached": "Attached images",
"library": "Library",
"noImages": "No images attached yet.",
"saveImages": "Save images",
"primary": "Primary",
"remove": "Remove",
"colourway": "Colourway",
"anyColourway": "All colourways",
"moveLeft": "Move earlier",
"moveRight": "Move later"
}
}
+122
View File
@@ -104,5 +104,127 @@
"status": "Trạng thái",
"lastLogin": "Đăng nhập gần nhất"
}
},
"catalog": {
"searchPlaceholder": "Tìm theo tên hoặc SKU",
"count": "{count} sản phẩm",
"empty": "Không có sản phẩm phù hợp.",
"loadFailed": "Không tải được danh sách sản phẩm.",
"actionFailed": "Thao tác thất bại.",
"noPermission": "Bạn không có quyền xem mục này.",
"publish": "Đăng bán",
"unpublish": "Ngừng bán",
"status": {
"ALL": "Tất cả",
"ACTIVE": "Đang bán",
"DRAFT": "Nháp",
"ARCHIVED": "Lưu trữ"
},
"table": {
"product": "Sản phẩm",
"status": "Trạng thái",
"variants": "Phiên bản",
"stock": "Tồn kho",
"price": "Giá"
},
"newProduct": "Sản phẩm mới",
"edit": "Sửa"
},
"media": {
"chooseFiles": "Chọn tệp",
"uploadHint": "PNG, JPEG, WebP hoặc AVIF, tối đa 25 MB. Tải thẳng lên kho lưu trữ.",
"uploading": "đang tải lên…",
"uploadFailed": "Tải lên thất bại.",
"deleteFailed": "Không xoá được.",
"loadFailed": "Không tải được thư viện.",
"empty": "Chưa có media.",
"delete": "Xoá",
"noPermission": "Bạn không có quyền xem mục này."
},
"inventory": {
"searchPlaceholder": "Tìm SKU hoặc sản phẩm",
"lowStockOnly": "Chỉ hàng sắp hết",
"loadFailed": "Không tải được tồn kho.",
"adjustFailed": "Điều chỉnh thất bại.",
"noPermission": "Bạn không có quyền xem mục này.",
"adjust": "Điều chỉnh",
"apply": "Áp dụng",
"cancel": "Huỷ",
"outOfStock": "Hết hàng",
"deltaLabel": "Thay đổi số lượng",
"table": {
"sku": "SKU",
"product": "Sản phẩm",
"onHand": "Tồn kho",
"reserved": "Đang giữ",
"available": "Có sẵn"
}
},
"editor": {
"createTitle": "Sản phẩm mới",
"editTitle": "Sửa sản phẩm",
"createHint": "Điền nội dung và các trục tuỳ chọn. Khi lưu, hệ thống sinh một phiên bản cho mỗi tổ hợp để bạn đặt giá ở tab Phiên bản.",
"backToList": "Sản phẩm",
"content": "Nội dung",
"facets": "Phân loại",
"options": "Tuỳ chọn",
"generation": "Sinh phiên bản",
"localeHint": "Ngôn ngữ chưa có tên sẽ được bỏ qua — storefront tự dùng nội dung thay thế theo từng trường.",
"name": "Tên",
"shortDescription": "Mô tả ngắn",
"description": "Mô tả",
"gender": "Giới tính",
"sport": "Môn thể thao",
"optionsHint": "Mỗi tổ hợp giá trị sẽ thành một phiên bản bán được, có SKU, giá và tồn kho riêng.",
"addOption": "Thêm tuỳ chọn",
"removeOption": "Xoá",
"optionKey": "Mã",
"optionName": "Nhãn",
"addValue": "Thêm giá trị",
"removeValue": "Xoá",
"valueKey": "giá trị",
"valueLabel": "Nhãn",
"swatch": "Màu",
"skuPrefix": "Tiền tố SKU",
"basePrice": "Giá cơ bản (VND)",
"generationHint": "Áp dụng cho mọi phiên bản được sinh ra. Bạn có thể chỉnh từng giá sau.",
"save": "Lưu thay đổi",
"create": "Tạo sản phẩm",
"saving": "Đang lưu…",
"saved": "Đã lưu",
"saveFailed": "Không lưu được.",
"loadFailed": "Không tải được sản phẩm này.",
"matrixWarning": "Lưu sẽ sinh lại ma trận phiên bản",
"publish": "Đăng bán",
"unpublish": "Ngừng bán",
"archive": "Lưu trữ",
"tab": {
"details": "Chi tiết",
"variants": "Phiên bản",
"images": "Hình ảnh"
},
"noVariants": "Chưa có phiên bản. Thêm giá trị tuỳ chọn ở tab Chi tiết.",
"variantCount": "{count} đang bán",
"archivedCount": "{count} đã lưu trữ",
"archived": "Lưu trữ",
"saveChanged": "Lưu {count} thay đổi",
"grid": {
"variant": "Phiên bản",
"sku": "SKU",
"price": "Giá",
"sale": "Giá giảm",
"stock": "Có sẵn / tồn kho"
},
"stockHint": "Tồn kho chỉ để xem ở đây. Điều chỉnh ở mục Kho hàng để mọi thay đổi được ghi vào sổ nhật ký kèm lý do.",
"attached": "Hình đã gắn",
"library": "Thư viện",
"noImages": "Chưa gắn hình nào.",
"saveImages": "Lưu hình ảnh",
"primary": "Chính",
"remove": "Xoá",
"colourway": "Màu",
"anyColourway": "Mọi màu",
"moveLeft": "Chuyển lên trước",
"moveRight": "Chuyển xuống sau"
}
}
+4
View File
@@ -1,5 +1,9 @@
@import 'tailwindcss';
@import '@sport/config/tailwind/theme.css';
/* Supplies the enter/exit utilities Radix-driven overlays animate with
(`animate-in`, `fade-in-0`, `slide-in-from-right`). Registry components
assume these exist; without it Dialog and Sheet appear instantly. */
@import 'tw-animate-css';
@source "../../../../packages/ui/src";
+2
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { AuditModule } from './common/audit/audit.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { ResponseEnvelopeInterceptor } from './common/interceptors/response-envelope.interceptor';
import { MediaUrlModule } from './common/media/media.module';
@@ -57,6 +58,7 @@ import { WishlistModule } from './modules/wishlist/wishlist.module';
EventsModule,
MediaUrlModule,
SecurityModule,
AuditModule,
ThrottlerModule.forRootAsync({
inject: [APP_CONFIG],
+11
View File
@@ -0,0 +1,11 @@
import { Global, Module } from '@nestjs/common';
import { AuditService } from './audit.service';
/** Global: every write path in the admin records what it did. */
@Global()
@Module({
providers: [AuditService],
exports: [AuditService],
})
export class AuditModule {}
@@ -0,0 +1,60 @@
import { Injectable, Logger } from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { PrismaService } from '@/infrastructure/prisma/prisma.service';
export interface AuditEntry {
actorUserId: string | null;
action: string;
resourceType: string;
resourceId: string | null;
changes?: Prisma.InputJsonValue;
ipAddress?: string | null;
}
/**
* Append-only record of who changed what.
*
* Two deliberate properties:
*
* 1. **Writing an audit row never fails the operation.** If the log write
* throws, the product edit that succeeded must still stand — losing an audit
* row is bad, silently rolling back an operator's work because of it is
* worse. Failures are logged loudly instead.
*
* 2. **It is fire-and-forget from the caller's perspective.** Audit writes must
* not add latency to the write path.
*
* If audit completeness ever becomes a compliance requirement, this becomes an
* outbox row inside the same transaction as the change. That is a deliberate
* future step, not an oversight.
*/
@Injectable()
export class AuditService {
private readonly logger = new Logger(AuditService.name);
constructor(private readonly prisma: PrismaService) {}
record(entry: AuditEntry): void {
void this.write(entry);
}
private async write(entry: AuditEntry): Promise<void> {
try {
await this.prisma.auditLog.create({
data: {
actorUserId: entry.actorUserId,
action: entry.action,
resourceType: entry.resourceType,
resourceId: entry.resourceId,
changes: entry.changes,
ipAddress: entry.ipAddress ?? null,
},
});
} catch (error) {
this.logger.error(
`Failed to write audit entry ${entry.action} on ${entry.resourceType}: ${String(error)}`,
);
}
}
}
@@ -98,6 +98,43 @@ export class RedisService implements OnModuleDestroy {
return typeof count === 'number' ? count : 0;
}
/**
* Drops every key under a prefix.
*
* SCAN, never KEYS: KEYS blocks the entire Redis server for the duration of
* the scan, and this runs on the admin write path where a catalog import can
* fire it hundreds of times.
*
* Note the prefix handling — the client is configured with `keyPrefix`, so
* SCAN returns fully-prefixed keys while `del` would prefix them again. The
* prefix is stripped before deleting.
*/
async deleteByPrefix(prefix: string): Promise<number> {
const keyPrefix = this.client.options.keyPrefix ?? '';
let cursor = '0';
let removed = 0;
do {
const [next, keys] = await this.client.scan(
cursor,
'MATCH',
`${keyPrefix}${prefix}*`,
'COUNT',
500,
);
cursor = next;
if (keys.length > 0) {
const unprefixed = keys.map((key) =>
keyPrefix && key.startsWith(keyPrefix) ? key.slice(keyPrefix.length) : key,
);
removed += await this.client.del(...unprefixed);
}
} while (cursor !== '0');
return removed;
}
async ping(): Promise<void> {
await this.client.ping();
}
@@ -0,0 +1,131 @@
import type { InventoryListQuery } from '@sport/validation';
import type { AuditService } from '@/common/audit/audit.service';
import type { PrismaService } from '@/infrastructure/prisma/prisma.service';
import type { RedisService } from '@/infrastructure/redis/redis.service';
import { InventoryService } from './inventory.service';
/**
* Pins the one thing that made stock unreachable in the admin: the list is
* driven by `ProductVariant`, not by `StockLevel`.
*
* A variant that has never moved has no level row — the level is a projection
* of the ledger. Listing the projection hid every freshly created variant, and
* since this screen is the only route to `adjust`, those variants could never
* be given stock at all. That is invisible from the API contract, so it is
* asserted here rather than left to inspection.
*/
const location = { id: 'loc-main', name: 'Main Warehouse' };
interface Stub {
service: InventoryService;
variantArgs: () => Record<string, unknown>;
stockLevelTouched: () => boolean;
}
function stubService(rows: unknown[]): Stub {
let variantArgs: Record<string, unknown> = {};
let stockLevelTouched = false;
const prisma = {
inventoryLocation: { findFirst: async () => location },
productVariant: {
findMany: async (args: Record<string, unknown>) => {
variantArgs = args;
return rows;
},
count: async () => rows.length,
},
stockLevel: {
findMany: async () => {
stockLevelTouched = true;
return [];
},
count: async () => {
stockLevelTouched = true;
return 0;
},
},
} as unknown as PrismaService;
return {
service: new InventoryService(prisma, {} as RedisService, {} as AuditService),
variantArgs: () => variantArgs,
stockLevelTouched: () => stockLevelTouched,
};
}
const query = (overrides: Partial<InventoryListQuery> = {}): InventoryListQuery =>
({ page: 1, perPage: 24, lowStockOnly: false, ...overrides }) as InventoryListQuery;
describe('InventoryService.list', () => {
it('reports a variant with no level row as zero rather than omitting it', async () => {
const updatedAt = new Date('2026-08-12T03:00:00.000Z');
const stub = stubService([
{
id: 'v-1',
sku: 'VEL-NOC-BLACK-M',
title: 'Black / M',
updatedAt,
product: { name: 'Nocturne Jacket' },
stockLevels: [],
},
]);
const result = await stub.service.list(query());
expect(stub.stockLevelTouched()).toBe(false);
expect(result.items).toHaveLength(1);
expect(result.items[0]).toMatchObject({
variantId: 'v-1',
sku: 'VEL-NOC-BLACK-M',
locationId: location.id,
locationName: location.name,
onHand: 0,
reserved: 0,
available: 0,
// Nothing has moved, so the variant's own timestamp is the most recent
// thing that is true about its stock.
updatedAt: updatedAt.toISOString(),
});
});
it('derives available from the level when one exists', async () => {
const stub = stubService([
{
id: 'v-2',
sku: 'VEL-NOC-VOLT-L',
title: 'Volt / L',
updatedAt: new Date('2026-08-01T00:00:00.000Z'),
product: { name: 'Nocturne Jacket' },
stockLevels: [{ onHand: 12, reserved: 5, updatedAt: new Date('2026-08-12T00:00:00.000Z') }],
},
]);
const result = await stub.service.list(query());
expect(result.items[0]).toMatchObject({ onHand: 12, reserved: 5, available: 7 });
});
it('counts a missing level row as low stock', async () => {
const stub = stubService([]);
await stub.service.list(query({ lowStockOnly: true }));
// A variant sitting at an implicit zero is the most urgent kind of low, not
// an absent one — so the filter must reach rows with no level at all.
expect(JSON.stringify(stub.variantArgs().where)).toContain('"none"');
});
it('keeps search and low-stock filters independent', async () => {
const stub = stubService([]);
await stub.service.list(query({ q: 'VEL-NOC', lowStockOnly: true }));
// Both are `OR` groups; combining them at the same level would let a
// low-stock match escape the search term. They must be `AND`ed.
const where = stub.variantArgs().where as { AND?: unknown[] };
expect(where.AND).toHaveLength(2);
});
});
@@ -0,0 +1,60 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
PERMISSIONS,
TOKEN_AUDIENCES,
type AuthenticatedActor,
type InventoryLevel,
type OffsetPaginated,
type StockMovementEntry,
} from '@sport/types';
import {
adjustStockSchema,
inventoryListQuerySchema,
type AdjustStockInput,
type InventoryListQuery,
} from '@sport/validation';
import { CurrentActor } from '@/common/decorators/current-actor.decorator';
import {
RequireAudience,
RequirePermissions,
} from '@/common/decorators/require-permissions.decorator';
import { ZodValidationPipe } from '@/common/pipes/zod-validation.pipe';
import { InventoryService } from './inventory.service';
@ApiTags('admin/inventory')
@ApiBearerAuth()
@RequireAudience(TOKEN_AUDIENCES.ADMIN)
@Controller('admin/inventory')
export class InventoryController {
constructor(private readonly service: InventoryService) {}
@Get()
@RequirePermissions(PERMISSIONS.INVENTORY_READ)
@ApiOperation({ summary: 'Stock levels by variant and location' })
list(
@Query(new ZodValidationPipe(inventoryListQuerySchema)) query: InventoryListQuery,
): Promise<OffsetPaginated<InventoryLevel>> {
return this.service.list(query);
}
@Get('movements/:variantId')
@RequirePermissions(PERMISSIONS.INVENTORY_READ)
@ApiOperation({ summary: 'Movement ledger for one variant' })
movements(@Param('variantId') variantId: string): Promise<StockMovementEntry[]> {
return this.service.movements(variantId);
}
@Post('adjust')
@RequirePermissions(PERMISSIONS.INVENTORY_UPDATE)
@ApiOperation({ summary: 'Adjust stock; always writes a ledger entry' })
adjust(
@Body(new ZodValidationPipe(adjustStockSchema)) body: AdjustStockInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<InventoryLevel> {
return this.service.adjust(body, actor.userId);
}
}
@@ -1,23 +1,19 @@
import { Module } from '@nestjs/common';
import { InventoryController } from './inventory.controller';
import { InventoryService } from './inventory.service';
/**
* InventoryModule — boundary declared, implementation pending.
* InventoryModule — owns `inventory_locations`, `stock_levels` and
* `stock_movements`.
*
* Owns (exclusively): `inventory_locations`, `stock_levels`, `stock_movements`
*
* Stock ledger, reservations and release. Consumes order events rather than being called by OrdersModule.
*
* EXTRACTION CANDIDATE: designed so it could become its own service. It must
* therefore never read another module’s tables directly, and it communicates
* outward through domain events.
*
* Anatomy once implemented (see ../README.md):
* inventory.module.ts wiring only
* inventory.controller.ts HTTP surface, no logic
* inventory.service.ts business rules
* inventory.repository.ts the only file that touches Prisma
* dto/ request/response shapes
* public/ what other modules may import
* The stock level is a projection of the append-only movement ledger, which is
* what makes a discrepancy answerable. EXTRACTION CANDIDATE: it communicates
* outward through events and reads no other module's tables.
*/
@Module({})
@Module({
controllers: [InventoryController],
providers: [InventoryService],
exports: [InventoryService],
})
export class InventoryModule {}
@@ -0,0 +1,316 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import type { InventoryLevel, OffsetPaginated, StockMovementEntry } from '@sport/types';
import type { AdjustStockInput, InventoryListQuery } from '@sport/validation';
import { AuditService } from '@/common/audit/audit.service';
import { AppException } from '@/common/errors/app.exception';
import { PrismaService } from '@/infrastructure/prisma/prisma.service';
import { CACHE_KEYS } from '@/infrastructure/redis/cache-keys';
import { RedisService } from '@/infrastructure/redis/redis.service';
/** Below this, the admin flags a variant as needing attention. */
const LOW_STOCK_THRESHOLD = 5;
@Injectable()
export class InventoryService {
private readonly logger = new Logger(InventoryService.name);
constructor(
private readonly prisma: PrismaService,
private readonly redis: RedisService,
private readonly audit: AuditService,
) {}
/**
* Lists sellable variants with what the ledger says about them.
*
* Driven by `ProductVariant`, not `StockLevel`, because the level is a
* projection and a variant that has never moved has no row yet. Listing the
* projection made freshly created variants invisible here — and since this
* screen is the only way to reach `adjust`, they could never be given stock
* at all. A missing projection means zero, which is exactly what it means
* everywhere else.
*/
async list(query: InventoryListQuery): Promise<OffsetPaginated<InventoryLevel>> {
const location = await this.defaultLocation();
const filters: Prisma.ProductVariantWhereInput[] = [];
if (query.q) {
filters.push({
OR: [
{ sku: { contains: query.q, mode: 'insensitive' } },
{ product: { name: { contains: query.q, mode: 'insensitive' } } },
],
});
}
if (query.lowStockOnly) {
// "Low" includes "has no level row at all" — a variant sitting at an
// implicit zero is the most urgent kind of low, not an absent one.
filters.push({
OR: [
{ stockLevels: { none: { locationId: location.id } } },
{
stockLevels: {
some: { locationId: location.id, onHand: { lte: LOW_STOCK_THRESHOLD } },
},
},
],
});
}
const where: Prisma.ProductVariantWhereInput = {
status: 'ACTIVE',
deletedAt: null,
...(filters.length > 0 ? { AND: filters } : {}),
};
const [rows, totalItems] = await Promise.all([
this.prisma.productVariant.findMany({
where,
// By SKU rather than by quantity: ordering on a relation would cost a
// join-and-sort on every page, and `lowStockOnly` is the tool for
// finding the shortages. Stable order matters more while paging.
orderBy: { sku: 'asc' },
skip: (query.page - 1) * query.perPage,
take: query.perPage,
select: {
id: true,
sku: true,
title: true,
updatedAt: true,
product: { select: { name: true } },
stockLevels: {
where: { locationId: location.id },
select: { onHand: true, reserved: true, updatedAt: true },
take: 1,
},
},
}),
this.prisma.productVariant.count({ where }),
]);
const totalPages = Math.max(1, Math.ceil(totalItems / query.perPage));
return {
items: rows.map((row) => {
const level = row.stockLevels[0];
return {
variantId: row.id,
sku: row.sku,
variantTitle: row.title,
productName: row.product.name,
locationId: location.id,
locationName: location.name,
onHand: level?.onHand ?? 0,
reserved: level?.reserved ?? 0,
available: (level?.onHand ?? 0) - (level?.reserved ?? 0),
// Without a level row nothing has moved, so the variant's own
// timestamp is the most recent thing that is true about its stock.
updatedAt: (level?.updatedAt ?? row.updatedAt).toISOString(),
};
}),
pageInfo: {
page: query.page,
perPage: query.perPage,
totalItems,
totalPages,
hasNextPage: query.page < totalPages,
},
};
}
/**
* Applies a stock change and records it in the ledger, atomically.
*
* The ledger entry and the level update are in one transaction because the
* level is a *projection* of the ledger (ADR: inventory is append-only). If
* they could diverge, "why is this number wrong?" becomes unanswerable — and
* that question is the entire reason the ledger exists.
*
* Never lets stock go negative: a correction that would imply selling units
* that were never received is a data-entry error, and silently clamping it
* would hide the mistake.
*/
async adjust(input: AdjustStockInput, actorUserId: string): Promise<InventoryLevel> {
const variant = await this.prisma.productVariant.findFirst({
where: { id: input.variantId, deletedAt: null },
select: {
id: true,
sku: true,
title: true,
productId: true,
product: { select: { name: true } },
},
});
if (!variant) throw AppException.notFound('Variant');
const locationId = input.locationId ?? (await this.defaultLocationId());
const level = await this.prisma.$transaction(async (tx) => {
const current = await tx.stockLevel.findUnique({
where: { variantId_locationId: { variantId: variant.id, locationId } },
select: { onHand: true, reserved: true },
});
const onHand = current?.onHand ?? 0;
// A stock take states the counted total; everything else is a delta.
const delta =
input.reason === 'STOCK_TAKE'
? (input.countedQuantity ?? 0) - onHand
: (input.quantityDelta ?? 0);
const nextOnHand = onHand + delta;
if (nextOnHand < 0) {
throw AppException.badRequest(
`That adjustment would leave ${variant.sku} at ${nextOnHand}. Stock cannot go negative.`,
);
}
const updated = await tx.stockLevel.upsert({
where: { variantId_locationId: { variantId: variant.id, locationId } },
update: { onHand: nextOnHand },
create: { variantId: variant.id, locationId, onHand: nextOnHand, reserved: 0 },
select: {
onHand: true,
reserved: true,
updatedAt: true,
location: { select: { name: true } },
},
});
// Append-only: a stock take that changes nothing still records that a
// count happened, which is exactly what an auditor looks for.
await tx.stockMovement.create({
data: {
variantId: variant.id,
locationId,
quantityDelta: delta,
reason: input.reason,
note: input.note ?? null,
createdByUserId: actorUserId,
},
});
return updated;
});
// `inStock` on the product read model depends on this.
await this.recomputeProductStock(variant.productId);
const dropped = await this.redis.deleteByPrefix(CACHE_KEYS.catalogPrefix());
this.logger.log(`Stock adjusted for ${variant.sku}; dropped ${dropped} catalog cache key(s)`);
this.audit.record({
actorUserId,
action: 'inventory.adjust',
resourceType: 'ProductVariant',
resourceId: variant.id,
changes: { sku: variant.sku, reason: input.reason, onHand: level.onHand },
});
return {
variantId: variant.id,
sku: variant.sku,
variantTitle: variant.title,
productName: variant.product.name,
locationId,
locationName: level.location.name,
onHand: level.onHand,
reserved: level.reserved,
available: level.onHand - level.reserved,
updatedAt: level.updatedAt.toISOString(),
};
}
async movements(variantId: string, limit = 50): Promise<StockMovementEntry[]> {
const rows = await this.prisma.stockMovement.findMany({
where: { variantId },
orderBy: { createdAt: 'desc' },
take: limit,
select: {
id: true,
variantId: true,
quantityDelta: true,
reason: true,
note: true,
createdAt: true,
variant: { select: { sku: true } },
createdByUserId: true,
},
});
const actorIds = [
...new Set(rows.map((row) => row.createdByUserId).filter(Boolean)),
] as string[];
const actors = await this.prisma.user.findMany({
where: { id: { in: actorIds } },
select: { id: true, firstName: true, lastName: true, email: true },
});
const actorById = new Map(actors.map((actor) => [actor.id, actor]));
return rows.map((row) => {
const actor = row.createdByUserId ? actorById.get(row.createdByUserId) : undefined;
const name = actor
? [actor.firstName, actor.lastName].filter(Boolean).join(' ') || actor.email
: null;
return {
id: row.id,
variantId: row.variantId,
sku: row.variant.sku,
quantityDelta: row.quantityDelta,
reason: row.reason,
note: row.note,
createdByName: name,
createdAt: row.createdAt.toISOString(),
};
});
}
/** Creates the default location on first use rather than failing the seed. */
private async defaultLocation(): Promise<{ id: string; name: string }> {
const location = await this.prisma.inventoryLocation.findFirst({
where: { isActive: true },
orderBy: { isDefault: 'desc' },
select: { id: true, name: true },
});
return (
location ??
(await this.prisma.inventoryLocation.create({
data: { code: 'MAIN', name: 'Main Warehouse', isDefault: true },
select: { id: true, name: true },
}))
);
}
private async defaultLocationId(): Promise<string> {
return (await this.defaultLocation()).id;
}
/**
* Keeps `Product.inStock` in step (ADR-0014).
*
* Cheaper than `recomputePricing`: stock changes far more often than price,
* and touching only the one boolean avoids re-reading every variant's pricing
* on each warehouse adjustment.
*/
private async recomputeProductStock(productId: string): Promise<void> {
const variants = await this.prisma.productVariant.findMany({
where: { productId, status: 'ACTIVE', deletedAt: null },
select: { stockLevels: { select: { onHand: true, reserved: true } } },
});
const inStock = variants.some((variant) =>
variant.stockLevels.some((level) => level.onHand - level.reserved > 0),
);
await this.prisma.product.update({ where: { id: productId }, data: { inStock } });
}
}
@@ -1,10 +1,7 @@
/**
* Public surface of InventoryModule.
*
* This barrel is the ONLY thing other modules may import from here. Everything
* else — repository, DTOs, internal services — is private, and the ESLint
* boundary rule in @sport/eslint-config/nest enforces it.
*
* Keep it narrow: each export is a promise to the rest of the codebase.
* CheckoutModule will use this to reserve and release stock; nothing else
* outside this module writes to the ledger.
*/
export {};
export { InventoryService } from '../inventory.service';
@@ -0,0 +1,88 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Post,
Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
PERMISSIONS,
TOKEN_AUDIENCES,
type AuthenticatedActor,
type MediaAssetSummary,
type OffsetPaginated,
type PresignedUploadTarget,
} from '@sport/types';
import {
mediaListQuerySchema,
presignUploadSchema,
registerMediaSchema,
type MediaListQuery,
type PresignUploadInput,
type RegisterMediaInput,
} from '@sport/validation';
import { CurrentActor } from '@/common/decorators/current-actor.decorator';
import {
RequireAudience,
RequirePermissions,
} from '@/common/decorators/require-permissions.decorator';
import { ZodValidationPipe } from '@/common/pipes/zod-validation.pipe';
import { MediaService } from './media.service';
@ApiTags('admin/media')
@ApiBearerAuth()
@RequireAudience(TOKEN_AUDIENCES.ADMIN)
@Controller('admin/media')
export class MediaController {
constructor(private readonly mediaService: MediaService) {}
@Get()
@RequirePermissions(PERMISSIONS.MEDIA_READ)
@ApiOperation({ summary: 'List media assets' })
list(
@Query(new ZodValidationPipe(mediaListQuerySchema)) query: MediaListQuery,
): Promise<OffsetPaginated<MediaAssetSummary>> {
return this.mediaService.list(query);
}
/**
* Step 1 of an upload: get a short-lived URL to PUT the file to.
* The browser then uploads directly to object storage.
*/
@Post('presign')
@HttpCode(HttpStatus.OK)
@RequirePermissions(PERMISSIONS.MEDIA_UPLOAD)
@ApiOperation({ summary: 'Get a presigned upload target' })
presign(
@Body(new ZodValidationPipe(presignUploadSchema)) body: PresignUploadInput,
): Promise<PresignedUploadTarget> {
return this.mediaService.presign(body);
}
/** Step 2: record the asset once the bytes are in storage. */
@Post()
@RequirePermissions(PERMISSIONS.MEDIA_UPLOAD)
@ApiOperation({ summary: 'Register an uploaded asset' })
register(
@Body(new ZodValidationPipe(registerMediaSchema)) body: RegisterMediaInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<MediaAssetSummary> {
return this.mediaService.register(body, actor.userId);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
@RequirePermissions(PERMISSIONS.MEDIA_DELETE)
@ApiOperation({ summary: 'Delete an unused media asset' })
delete(@Param('id') id: string, @CurrentActor() actor: AuthenticatedActor): Promise<void> {
return this.mediaService.delete(id, actor.userId);
}
}
+11 -13
View File
@@ -1,19 +1,17 @@
import { Module } from '@nestjs/common';
import { MediaController } from './media.controller';
import { MediaService } from './media.service';
/**
* MediaModule — boundary declared, implementation pending.
* MediaModule — owns `media_assets`.
*
* Owns (exclusively): `media_assets`
*
* Issues presigned upload URLs and records metadata. Bytes never pass through the API and never enter PostgreSQL.
*
* Anatomy once implemented (see ../README.md):
* media.module.ts wiring only
* media.controller.ts HTTP surface, no logic
* media.service.ts business rules
* media.repository.ts the only file that touches Prisma
* dto/ request/response shapes
* public/ what other modules may import
* Issues presigned upload URLs and records metadata. Bytes never pass through
* the API and never enter PostgreSQL (ADR-0009).
*/
@Module({})
@Module({
controllers: [MediaController],
providers: [MediaService],
exports: [MediaService],
})
export class MediaModule {}
+220
View File
@@ -0,0 +1,220 @@
import { Injectable } from '@nestjs/common';
import {
API_ERROR_CODES,
type MediaAssetSummary,
type MediaKind,
type OffsetPaginated,
type PresignedUploadTarget,
} from '@sport/types';
import type { MediaListQuery, PresignUploadInput, RegisterMediaInput } from '@sport/validation';
import { AuditService } from '@/common/audit/audit.service';
import { AppException } from '@/common/errors/app.exception';
import { MediaUrlService } from '@/common/media/media-url.service';
import { PrismaService } from '@/infrastructure/prisma/prisma.service';
import { StorageService } from '@/infrastructure/storage/storage.service';
/** Enforced again at registration; the presign check alone is bypassable. */
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg',
'image/png',
'image/webp',
'image/avif',
'video/mp4',
'video/webm',
'application/pdf',
]);
const MAX_SIZE_BYTES = 25 * 1024 * 1024;
@Injectable()
export class MediaService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly mediaUrl: MediaUrlService,
private readonly audit: AuditService,
) {}
/**
* Issues a short-lived URL the browser PUTs directly to.
*
* Bytes never pass through the API (ADR-0009): no memory pressure, no request
* timeout on a 20 MB file, and no need to scale the API for bandwidth.
*/
async presign(input: PresignUploadInput): Promise<PresignedUploadTarget> {
this.assertAcceptable(input.mimeType, input.sizeBytes);
return this.storage.presignUpload({
prefix: input.prefix,
filename: input.filename,
mimeType: input.mimeType,
maxSizeBytes: input.sizeBytes,
});
}
/**
* Records an asset after the browser has uploaded it.
*
* The MIME type and size are re-validated here rather than trusted from the
* presign step: a client can call this endpoint directly with any values, so
* treating the earlier check as sufficient would make the allow-list
* decorative.
*
* Idempotent by storage key — a retried upload updates rather than duplicates.
*/
async register(input: RegisterMediaInput, actorUserId: string): Promise<MediaAssetSummary> {
this.assertAcceptable(input.mimeType, input.sizeBytes);
const asset = await this.prisma.mediaAsset.upsert({
where: { storageKey: input.storageKey },
update: {
mimeType: input.mimeType,
sizeBytes: input.sizeBytes,
width: input.width ?? null,
height: input.height ?? null,
altText: input.altText ?? null,
blurDataUrl: input.blurDataUrl ?? null,
},
create: {
kind: kindFor(input.mimeType),
storageKey: input.storageKey,
mimeType: input.mimeType,
sizeBytes: input.sizeBytes,
width: input.width ?? null,
height: input.height ?? null,
altText: input.altText ?? null,
blurDataUrl: input.blurDataUrl ?? null,
uploadedByUserId: actorUserId,
},
});
this.audit.record({
actorUserId,
action: 'media.upload',
resourceType: 'MediaAsset',
resourceId: asset.id,
changes: { storageKey: asset.storageKey, sizeBytes: asset.sizeBytes },
});
return this.toSummary(asset);
}
async list(query: MediaListQuery): Promise<OffsetPaginated<MediaAssetSummary>> {
const where = query.q
? {
OR: [
{ altText: { contains: query.q, mode: 'insensitive' as const } },
{ storageKey: { contains: query.q } },
],
}
: {};
const [items, totalItems] = await Promise.all([
this.prisma.mediaAsset.findMany({
where,
orderBy: { createdAt: 'desc' },
skip: (query.page - 1) * query.perPage,
take: query.perPage,
}),
this.prisma.mediaAsset.count({ where }),
]);
const totalPages = Math.max(1, Math.ceil(totalItems / query.perPage));
return {
items: items.map((item) => this.toSummary(item)),
pageInfo: {
page: query.page,
perPage: query.perPage,
totalItems,
totalPages,
hasNextPage: query.page < totalPages,
},
};
}
/**
* Deletes the row, then the object.
*
* That order matters: if the object delete fails we are left with an orphaned
* file, which a reconciliation job can clean up. The reverse order can leave a
* row pointing at bytes that no longer exist, which renders as a broken image
* on a live product page.
*/
async delete(id: string, actorUserId: string): Promise<void> {
const asset = await this.prisma.mediaAsset.findUnique({
where: { id },
select: { id: true, storageKey: true, _count: { select: { productImages: true } } },
});
if (!asset) throw AppException.notFound('Media asset');
if (asset._count.productImages > 0) {
throw AppException.conflict(
`This image is used by ${asset._count.productImages} product(s). Remove it from them first.`,
);
}
await this.prisma.mediaAsset.delete({ where: { id } });
await this.storage.delete(asset.storageKey).catch(() => undefined);
this.audit.record({
actorUserId,
action: 'media.delete',
resourceType: 'MediaAsset',
resourceId: id,
changes: { storageKey: asset.storageKey },
});
}
private assertAcceptable(mimeType: string, sizeBytes: number): void {
if (!ALLOWED_MIME_TYPES.has(mimeType)) {
throw new AppException({
code: API_ERROR_CODES.UNSUPPORTED_MEDIA_TYPE,
message: `Files of type ${mimeType} are not accepted.`,
status: 415,
});
}
if (sizeBytes > MAX_SIZE_BYTES) {
throw new AppException({
code: API_ERROR_CODES.FILE_TOO_LARGE,
message: `Files must be ${Math.floor(MAX_SIZE_BYTES / 1024 / 1024)} MB or smaller.`,
status: 413,
});
}
}
private toSummary(asset: {
id: string;
kind: string;
storageKey: string;
mimeType: string;
sizeBytes: number;
width: number | null;
height: number | null;
altText: string | null;
createdAt: Date;
}): MediaAssetSummary {
return {
id: asset.id,
kind: asset.kind as MediaKind,
url: this.mediaUrl.url(asset.storageKey),
storageKey: asset.storageKey,
mimeType: asset.mimeType,
sizeBytes: asset.sizeBytes,
width: asset.width,
height: asset.height,
altText: asset.altText,
createdAt: asset.createdAt.toISOString(),
};
}
}
function kindFor(mimeType: string): 'IMAGE' | 'VIDEO' | 'DOCUMENT' {
if (mimeType.startsWith('image/')) return 'IMAGE';
if (mimeType.startsWith('video/')) return 'VIDEO';
return 'DOCUMENT';
}
+3 -6
View File
@@ -1,10 +1,7 @@
/**
* Public surface of MediaModule.
*
* This barrel is the ONLY thing other modules may import from here. Everything
* else — repository, DTOs, internal services — is private, and the ESLint
* boundary rule in @sport/eslint-config/nest enforces it.
*
* Keep it narrow: each export is a promise to the rest of the codebase.
* `ProductsModule` needs to validate that a media id exists before attaching it
* to a product; nothing else outside this module touches media.
*/
export {};
export { MediaService } from '../media.service';
@@ -0,0 +1,120 @@
import { Body, Controller, Get, Param, Patch, Post, Put, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { z } from 'zod';
import {
PERMISSIONS,
TOKEN_AUDIENCES,
type AdminProductDetail,
type AdminProductListItem,
type AuthenticatedActor,
type OffsetPaginated,
} from '@sport/types';
import {
adminProductListQuerySchema,
bulkUpdateVariantsSchema,
createProductSchema,
productImagesSchema,
updateProductSchema,
type AdminProductListQuery,
type BulkUpdateVariantsInput,
type CreateProductInput,
type ProductImagesInput,
type UpdateProductInput,
} from '@sport/validation';
import { CurrentActor } from '@/common/decorators/current-actor.decorator';
import {
RequireAudience,
RequirePermissions,
} from '@/common/decorators/require-permissions.decorator';
import { ZodValidationPipe } from '@/common/pipes/zod-validation.pipe';
import { ProductsAdminService } from './products-admin.service';
const setStatusSchema = z.object({ status: z.enum(['DRAFT', 'ACTIVE', 'ARCHIVED']) });
/**
* The catalog write surface.
*
* Note the permission split: `product.update` covers everyday editing, while
* `product.publish` is separate — making something visible to customers is a
* different level of trust from correcting a description.
*/
@ApiTags('admin/products')
@ApiBearerAuth()
@RequireAudience(TOKEN_AUDIENCES.ADMIN)
@Controller('admin/products')
export class ProductsAdminController {
constructor(private readonly service: ProductsAdminService) {}
@Get()
@RequirePermissions(PERMISSIONS.PRODUCT_READ)
@ApiOperation({ summary: 'List products for the admin table' })
list(
@Query(new ZodValidationPipe(adminProductListQuerySchema)) query: AdminProductListQuery,
): Promise<OffsetPaginated<AdminProductListItem>> {
return this.service.list(query);
}
@Get(':id')
@RequirePermissions(PERMISSIONS.PRODUCT_READ)
@ApiOperation({ summary: 'Full product for the editor, in every locale' })
getById(@Param('id') id: string): Promise<AdminProductDetail> {
return this.service.getById(id);
}
@Post()
@RequirePermissions(PERMISSIONS.PRODUCT_CREATE)
@ApiOperation({ summary: 'Create a product and generate its variant matrix' })
create(
@Body(new ZodValidationPipe(createProductSchema)) body: CreateProductInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<AdminProductDetail> {
return this.service.create(body, actor.userId);
}
@Patch(':id')
@RequirePermissions(PERMISSIONS.PRODUCT_UPDATE)
@ApiOperation({ summary: 'Update a product; re-syncs the matrix if options changed' })
update(
@Param('id') id: string,
@Body(new ZodValidationPipe(updateProductSchema)) body: UpdateProductInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<AdminProductDetail> {
return this.service.update(id, body, actor.userId);
}
@Put(':id/variants')
@RequirePermissions(PERMISSIONS.PRODUCT_UPDATE)
@ApiOperation({ summary: 'Bulk-edit variant SKUs and prices (not stock)' })
updateVariants(
@Param('id') id: string,
@Body(new ZodValidationPipe(bulkUpdateVariantsSchema)) body: BulkUpdateVariantsInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<AdminProductDetail> {
return this.service.updateVariants(id, body, actor.userId);
}
@Put(':id/images')
@RequirePermissions(PERMISSIONS.PRODUCT_UPDATE)
@ApiOperation({ summary: 'Replace the image set and their ordering' })
setImages(
@Param('id') id: string,
@Body(new ZodValidationPipe(productImagesSchema)) body: ProductImagesInput,
@CurrentActor() actor: AuthenticatedActor,
): Promise<AdminProductDetail> {
return this.service.setImages(id, body, actor.userId);
}
@Post(':id/status')
@RequirePermissions(PERMISSIONS.PRODUCT_PUBLISH)
@ApiOperation({ summary: 'Publish, unpublish or archive' })
setStatus(
@Param('id') id: string,
@Body(new ZodValidationPipe(setStatusSchema)) body: { status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED' },
@CurrentActor() actor: AuthenticatedActor,
): Promise<AdminProductDetail> {
return this.service.setStatus(id, body.status, actor.userId);
}
}
@@ -0,0 +1,173 @@
import { Injectable } from '@nestjs/common';
import type {
AdminProductDetail,
AdminProductListItem,
CurrencyCode,
GenderTarget,
Locale,
ProductStatus,
SportType,
TranslationMap,
VariantStatus,
} from '@sport/types';
import { MediaUrlService } from '@/common/media/media-url.service';
import type { AdminProductRow } from './products.repository';
/** Prisma's `Locale` enum → the wire value. */
function toLocale(dbLocale: string): Locale {
return dbLocale === 'VI' ? 'vi' : 'en';
}
/** Collapses `[{locale, ...fields}]` into `{ vi: fields, en: fields }`. */
function byLocale<TRow extends { locale: string }, TOut>(
rows: readonly TRow[],
pick: (row: TRow) => TOut,
): TranslationMap<TOut> {
return Object.fromEntries(rows.map((row) => [toLocale(row.locale), pick(row)]));
}
@Injectable()
export class ProductsAdminMapper {
constructor(private readonly mediaUrl: MediaUrlService) {}
toListItem(row: {
id: string;
name: string;
slug: string;
status: string;
isOnSale: boolean;
publishedAt: Date | null;
updatedAt: Date;
translations: { locale: string; name: string }[];
brand: { name: string } | null;
images: { media: { storageKey: string } }[];
variants: {
currency: string;
priceAmount: number;
salePriceAmount: number | null;
stockLevels: { onHand: number; reserved: number }[];
}[];
}): AdminProductListItem {
const currency = (row.variants[0]?.currency ?? 'VND') as CurrencyCode;
const effective = row.variants.map((variant) => variant.salePriceAmount ?? variant.priceAmount);
// Available, not on-hand: an operator planning a restock cares about what
// can actually be sold, and reserved units cannot be.
const totalStock = row.variants.reduce(
(total, variant) =>
total +
variant.stockLevels.reduce((sum, level) => sum + (level.onHand - level.reserved), 0),
0,
);
const thumbnail = row.images[0]?.media.storageKey;
return {
id: row.id,
// The admin table always shows the default-locale name so rows stay
// comparable; the editor is where other languages are visible.
name: row.translations[0]?.name ?? row.name,
slug: row.slug,
status: row.status as ProductStatus,
brandName: row.brand?.name ?? null,
thumbnailUrl: thumbnail ? this.mediaUrl.url(thumbnail) : null,
variantCount: row.variants.length,
totalStock,
priceRange:
effective.length > 0
? {
min: { amount: Math.min(...effective), currency },
max: { amount: Math.max(...effective), currency },
}
: null,
isOnSale: row.isOnSale,
publishedAt: row.publishedAt?.toISOString() ?? null,
updatedAt: row.updatedAt.toISOString(),
};
}
toDetail(row: AdminProductRow): AdminProductDetail {
return {
id: row.id,
status: row.status as ProductStatus,
publishedAt: row.publishedAt?.toISOString() ?? null,
brandId: row.brandId,
primaryCategoryId: row.primaryCategoryId,
genderTargets: row.genderTargets as GenderTarget[],
sportTypes: row.sportTypes as SportType[],
collectionIds: row.collections.map((link) => link.collectionId),
translations: byLocale(row.translations, (translation) => ({
name: translation.name,
slug: translation.slug,
shortDescription: translation.shortDescription,
description: translation.description,
metaTitle: translation.metaTitle,
metaDescription: translation.metaDescription,
})),
options: row.options.map((option) => ({
id: option.id,
key: option.key,
position: option.position,
names: byLocale(option.translations, (translation) => translation.name),
values: option.values.map((value) => ({
id: value.id,
value: value.value,
position: value.position,
swatchHex: value.swatchHex,
labels: byLocale(value.translations, (translation) => translation.label),
})),
})),
variants: row.variants.map((variant) => {
const onHand = variant.stockLevels.reduce((sum, level) => sum + level.onHand, 0);
const reserved = variant.stockLevels.reduce((sum, level) => sum + level.reserved, 0);
return {
id: variant.id,
sku: variant.sku,
barcode: variant.barcode,
title: variant.title,
optionValueIds: variant.optionValues.map((link) => link.optionValueId),
priceAmount: variant.priceAmount,
salePriceAmount: variant.salePriceAmount,
compareAtAmount: variant.compareAtAmount,
costAmount: variant.costAmount,
weightGrams: variant.weightGrams,
status: variant.status as VariantStatus,
position: variant.position,
onHand,
reserved,
// Always derived, never stored — the two numbers cannot disagree.
available: onHand - reserved,
};
}),
images: row.images.map((image) => ({
id: image.id,
mediaId: image.mediaId,
url: this.mediaUrl.url(image.media.storageKey),
altText: image.media.altText,
position: image.position,
optionValueId: image.optionValueId,
})),
attributes: row.attributes.map((attribute) => ({
id: attribute.id,
key: attribute.key,
position: attribute.position,
translations: byLocale(attribute.translations, (translation) => ({
label: translation.label,
value: translation.value,
})),
})),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
}
@@ -0,0 +1,734 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import {
DEFAULT_LOCALE,
LOCALES,
type AdminProductDetail,
type AdminProductListItem,
type OffsetPaginated,
} from '@sport/types';
import type {
AdminProductListQuery,
BulkUpdateVariantsInput,
CreateProductInput,
ProductImagesInput,
ProductOptionInput,
UpdateProductInput,
} from '@sport/validation';
import { AuditService } from '@/common/audit/audit.service';
import { AppException } from '@/common/errors/app.exception';
import { toDbLocale } from '@/common/i18n';
import { PrismaService } from '@/infrastructure/prisma/prisma.service';
import { CACHE_KEYS } from '@/infrastructure/redis/cache-keys';
import { RedisService } from '@/infrastructure/redis/redis.service';
import { ProductsAdminMapper } from './products-admin.mapper';
import { ProductsRepository } from './products.repository';
import { planVariantMatrix, slugify, type MatrixOption } from './variant-matrix';
@Injectable()
export class ProductsAdminService {
private readonly logger = new Logger(ProductsAdminService.name);
constructor(
private readonly prisma: PrismaService,
private readonly repository: ProductsRepository,
private readonly mapper: ProductsAdminMapper,
private readonly redis: RedisService,
private readonly audit: AuditService,
) {}
// ---- Reads ---------------------------------------------------------------
async list(query: AdminProductListQuery): Promise<OffsetPaginated<AdminProductListItem>> {
const where: Prisma.ProductWhereInput = {
deletedAt: null,
...(query.status ? { status: query.status } : {}),
...(query.brandId ? { brandId: query.brandId } : {}),
...(query.q
? {
OR: [
{ name: { contains: query.q, mode: 'insensitive' } },
{ translations: { some: { name: { contains: query.q, mode: 'insensitive' } } } },
{ variants: { some: { sku: { contains: query.q, mode: 'insensitive' } } } },
],
}
: {}),
};
const [rows, totalItems] = await Promise.all([
this.prisma.product.findMany({
where,
orderBy: { updatedAt: 'desc' },
skip: (query.page - 1) * query.perPage,
take: query.perPage,
select: {
id: true,
name: true,
slug: true,
status: true,
isOnSale: true,
publishedAt: true,
updatedAt: true,
translations: { where: { locale: toDbLocale(DEFAULT_LOCALE) } },
brand: { select: { name: true } },
images: {
orderBy: { position: 'asc' },
take: 1,
select: { media: { select: { storageKey: true } } },
},
variants: {
where: { status: 'ACTIVE', deletedAt: null },
select: {
currency: true,
priceAmount: true,
salePriceAmount: true,
stockLevels: { select: { onHand: true, reserved: true } },
},
},
},
}),
this.prisma.product.count({ where }),
]);
const totalPages = Math.max(1, Math.ceil(totalItems / query.perPage));
return {
items: rows.map((row) => this.mapper.toListItem(row)),
pageInfo: {
page: query.page,
perPage: query.perPage,
totalItems,
totalPages,
hasNextPage: query.page < totalPages,
},
};
}
async getById(id: string): Promise<AdminProductDetail> {
const row = await this.repository.findByIdForAdmin(id);
if (!row) throw AppException.notFound('Product');
return this.mapper.toDetail(row);
}
// ---- Writes --------------------------------------------------------------
/**
* Creates a product and its full variant matrix in one transaction.
*
* All-or-nothing on purpose: a product that exists with half its variants is
* worse than one that failed outright, because the operator cannot tell which
* combinations are missing without inspecting the grid row by row.
*/
async create(input: CreateProductInput, actorUserId: string): Promise<AdminProductDetail> {
const canonical = this.canonicalTranslation(input);
const baseSlug = await this.uniqueSlug(canonical.slug ?? slugify(canonical.name));
const id = await this.prisma.$transaction(async (tx) => {
const product = await tx.product.create({
data: {
name: canonical.name,
slug: baseSlug,
shortDescription: canonical.shortDescription ?? null,
description: canonical.description ?? null,
status: 'DRAFT',
brandId: input.brandId ?? null,
primaryCategoryId: input.primaryCategoryId ?? null,
genderTargets: input.genderTargets,
sportTypes: input.sportTypes,
},
select: { id: true },
});
await this.writeTranslations(tx, product.id, input, baseSlug);
await this.writeCollections(tx, product.id, input.collectionIds ?? []);
await this.writeAttributes(tx, product.id, input.attributes ?? []);
const matrix = await this.writeOptions(tx, product.id, input.options ?? []);
await this.syncVariants(
tx,
product.id,
input.skuPrefix ?? baseSlug,
input.basePriceAmount,
matrix,
);
return product.id;
});
await this.afterWrite(actorUserId, 'product.create', id, { slug: baseSlug });
return this.getById(id);
}
async update(
id: string,
input: UpdateProductInput,
actorUserId: string,
): Promise<AdminProductDetail> {
const existing = await this.prisma.product.findFirst({
where: { id, deletedAt: null },
select: { id: true, slug: true, status: true },
});
if (!existing) throw AppException.notFound('Product');
await this.prisma.$transaction(async (tx) => {
const canonical = input.translations
? this.canonicalTranslation(input as CreateProductInput)
: null;
await tx.product.update({
where: { id },
data: {
...(canonical ? { name: canonical.name } : {}),
...(canonical?.shortDescription === undefined
? {}
: { shortDescription: canonical.shortDescription ?? null }),
...(canonical?.description === undefined
? {}
: { description: canonical.description ?? null }),
...(input.brandId === undefined ? {} : { brandId: input.brandId ?? null }),
...(input.primaryCategoryId === undefined
? {}
: { primaryCategoryId: input.primaryCategoryId ?? null }),
...(input.genderTargets ? { genderTargets: input.genderTargets } : {}),
...(input.sportTypes ? { sportTypes: input.sportTypes } : {}),
...(input.status ? this.statusPatch(input.status) : {}),
},
});
if (input.translations) {
await this.writeTranslations(tx, id, input as CreateProductInput, existing.slug);
}
if (input.collectionIds) {
await this.writeCollections(tx, id, input.collectionIds);
}
if (input.attributes) {
await this.writeAttributes(tx, id, input.attributes);
}
if (input.options) {
const matrix = await this.writeOptions(tx, id, input.options);
await this.syncVariants(
tx,
id,
input.skuPrefix ?? existing.slug,
input.basePriceAmount ?? 0,
matrix,
);
}
});
await this.afterWrite(actorUserId, 'product.update', id, { status: input.status });
return this.getById(id);
}
/**
* Per-variant edits: SKU, prices, weight, status.
*
* Stock is deliberately absent — it moves through the inventory endpoint so
* every change lands in the movement ledger. A price edit and a stock
* correction are different events with different audit requirements.
*/
async updateVariants(
productId: string,
input: BulkUpdateVariantsInput,
actorUserId: string,
): Promise<AdminProductDetail> {
const owned = await this.prisma.productVariant.findMany({
where: { productId, id: { in: input.variants.map((variant) => variant.id) } },
select: { id: true },
});
// Reject ids belonging to another product rather than silently skipping
// them: a partial save that reports success is how pricing work vanishes.
if (owned.length !== input.variants.length) {
throw AppException.badRequest('One or more variants do not belong to this product.');
}
await this.prisma.$transaction(
input.variants.map((variant) =>
this.prisma.productVariant.update({
where: { id: variant.id },
data: {
...(variant.sku === undefined ? {} : { sku: variant.sku }),
...(variant.barcode === undefined ? {} : { barcode: variant.barcode ?? null }),
...(variant.priceAmount === undefined ? {} : { priceAmount: variant.priceAmount }),
...(variant.salePriceAmount === undefined
? {}
: { salePriceAmount: variant.salePriceAmount ?? null }),
...(variant.compareAtAmount === undefined
? {}
: { compareAtAmount: variant.compareAtAmount ?? null }),
...(variant.costAmount === undefined ? {} : { costAmount: variant.costAmount ?? null }),
...(variant.weightGrams === undefined
? {}
: { weightGrams: variant.weightGrams ?? null }),
...(variant.status === undefined ? {} : { status: variant.status }),
},
}),
),
);
await this.afterWrite(actorUserId, 'product.variants.update', productId, {
count: input.variants.length,
});
return this.getById(productId);
}
async setImages(
productId: string,
input: ProductImagesInput,
actorUserId: string,
): Promise<AdminProductDetail> {
await this.prisma.$transaction(async (tx) => {
await tx.productImage.deleteMany({ where: { productId } });
if (input.images.length > 0) {
await tx.productImage.createMany({
data: input.images.map((image) => ({
productId,
mediaId: image.mediaId,
position: image.position,
optionValueId: image.optionValueId ?? null,
})),
skipDuplicates: true,
});
}
});
await this.afterWrite(actorUserId, 'product.images.update', productId, {
count: input.images.length,
});
return this.getById(productId);
}
async setStatus(
id: string,
status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED',
actorUserId: string,
): Promise<AdminProductDetail> {
const existing = await this.prisma.product.findFirst({
where: { id, deletedAt: null },
select: { id: true, _count: { select: { variants: true } } },
});
if (!existing) throw AppException.notFound('Product');
// Publishing something with nothing to buy produces a page with a dead
// "Add to bag" button. Catch it here rather than on the storefront.
if (status === 'ACTIVE' && existing._count.variants === 0) {
throw AppException.badRequest('Add at least one variant before publishing.');
}
await this.prisma.product.update({ where: { id }, data: this.statusPatch(status) });
await this.afterWrite(actorUserId, `product.${status.toLowerCase()}`, id, { status });
return this.getById(id);
}
// ---- internals -----------------------------------------------------------
private statusPatch(status: 'DRAFT' | 'ACTIVE' | 'ARCHIVED') {
return {
status,
// `publishedAt` is set once, on first publish, and never cleared —
// unpublishing and republishing should not reset "new arrivals" ordering.
...(status === 'ACTIVE' ? { publishedAt: new Date() } : {}),
};
}
private canonicalTranslation(input: CreateProductInput) {
const translations = input.translations;
const canonical = translations[DEFAULT_LOCALE] ?? Object.values(translations)[0];
if (!canonical) {
throw AppException.badRequest('Provide content for at least one language.');
}
return canonical;
}
/** Appends `-2`, `-3`… until the base slug is free. */
private async uniqueSlug(base: string, excludeId?: string): Promise<string> {
const candidate = base || 'product';
for (let suffix = 0; suffix < 50; suffix += 1) {
const slug = suffix === 0 ? candidate : `${candidate}-${suffix + 1}`;
const clash = await this.prisma.product.findFirst({
where: { slug, ...(excludeId ? { id: { not: excludeId } } : {}) },
select: { id: true },
});
if (!clash) return slug;
}
throw AppException.conflict('Could not generate a unique slug for this product.');
}
private async writeTranslations(
tx: Prisma.TransactionClient,
productId: string,
input: CreateProductInput,
fallbackSlug: string,
): Promise<void> {
for (const locale of LOCALES) {
const fields = input.translations[locale];
if (!fields) continue;
const slug = fields.slug ?? slugify(fields.name) ?? fallbackSlug;
await tx.productTranslation.upsert({
where: { productId_locale: { productId, locale: toDbLocale(locale) } },
update: {
name: fields.name,
slug,
shortDescription: fields.shortDescription ?? null,
description: fields.description ?? null,
metaTitle: fields.metaTitle ?? null,
metaDescription: fields.metaDescription ?? null,
},
create: {
productId,
locale: toDbLocale(locale),
name: fields.name,
slug,
shortDescription: fields.shortDescription ?? null,
description: fields.description ?? null,
metaTitle: fields.metaTitle ?? null,
metaDescription: fields.metaDescription ?? null,
},
});
}
}
private async writeCollections(
tx: Prisma.TransactionClient,
productId: string,
collectionIds: readonly string[],
): Promise<void> {
await tx.productCollection.deleteMany({ where: { productId } });
if (collectionIds.length > 0) {
await tx.productCollection.createMany({
data: collectionIds.map((collectionId) => ({ productId, collectionId })),
skipDuplicates: true,
});
}
}
private async writeAttributes(
tx: Prisma.TransactionClient,
productId: string,
attributes: CreateProductInput['attributes'],
): Promise<void> {
const keys = attributes.map((attribute) => attribute.key);
await tx.productAttribute.deleteMany({ where: { productId, key: { notIn: keys } } });
for (const attribute of attributes) {
const canonical =
attribute.translations[DEFAULT_LOCALE] ?? Object.values(attribute.translations)[0];
if (!canonical) continue;
const row = await tx.productAttribute.upsert({
where: { productId_key: { productId, key: attribute.key } },
update: { label: canonical.label, value: canonical.value, position: attribute.position },
create: {
productId,
key: attribute.key,
label: canonical.label,
value: canonical.value,
position: attribute.position,
},
select: { id: true },
});
for (const locale of LOCALES) {
const fields = attribute.translations[locale];
if (!fields) continue;
await tx.productAttributeTranslation.upsert({
where: { attributeId_locale: { attributeId: row.id, locale: toDbLocale(locale) } },
update: { label: fields.label, value: fields.value },
create: {
attributeId: row.id,
locale: toDbLocale(locale),
label: fields.label,
value: fields.value,
},
});
}
}
}
/**
* Reconciles options and their values.
*
* Values are matched by `value` (the machine key) rather than by id, so an
* editor that re-sends the whole option set does not orphan every variant
* link — which would archive the entire matrix on a cosmetic edit.
*/
private async writeOptions(
tx: Prisma.TransactionClient,
productId: string,
options: ProductOptionInput[],
): Promise<MatrixOption[]> {
const keys = options.map((option) => option.key);
await this.removeUnreferencedOptions(tx, productId, keys);
const matrix: MatrixOption[] = [];
for (const option of options) {
const canonicalName =
option.names[DEFAULT_LOCALE] ?? Object.values(option.names)[0] ?? option.key;
const optionRow = await tx.productOption.upsert({
where: { productId_key: { productId, key: option.key } },
update: { name: canonicalName, position: option.position },
create: { productId, key: option.key, name: canonicalName, position: option.position },
select: { id: true },
});
for (const locale of LOCALES) {
const name = option.names[locale];
if (!name) continue;
await tx.productOptionTranslation.upsert({
where: { optionId_locale: { optionId: optionRow.id, locale: toDbLocale(locale) } },
update: { name },
create: { optionId: optionRow.id, locale: toDbLocale(locale), name },
});
}
await this.removeUnreferencedValues(
tx,
optionRow.id,
option.values.map((value) => value.value),
);
const matrixValues: MatrixOption['values'] = [];
for (const value of option.values) {
const canonicalLabel =
value.labels[DEFAULT_LOCALE] ?? Object.values(value.labels)[0] ?? value.value;
const valueRow = await tx.productOptionValue.upsert({
where: { optionId_value: { optionId: optionRow.id, value: value.value } },
update: {
label: canonicalLabel,
position: value.position,
swatchHex: value.swatchHex ?? null,
},
create: {
optionId: optionRow.id,
value: value.value,
label: canonicalLabel,
position: value.position,
swatchHex: value.swatchHex ?? null,
},
select: { id: true },
});
for (const locale of LOCALES) {
const label = value.labels[locale];
if (!label) continue;
await tx.productOptionValueTranslation.upsert({
where: {
optionValueId_locale: { optionValueId: valueRow.id, locale: toDbLocale(locale) },
},
update: { label },
create: { optionValueId: valueRow.id, locale: toDbLocale(locale), label },
});
}
matrixValues.push({
id: valueRow.id,
value: value.value,
label: canonicalLabel,
position: value.position,
});
}
matrix.push({
key: option.key,
position: option.position,
values: matrixValues,
});
}
return matrix;
}
/**
* Deletes options the operator removed — but only when nothing references
* them.
*
* `ProductVariantOptionValue.optionValue` is `onDelete: Restrict`, and that is
* deliberate: an archived variant's link is what makes it meaningful ("this
* was Black / M") and order lines depend on it. So a value still referenced by
* any variant is *retained* rather than deleted; it simply stops appearing in
* the generated matrix, and the storefront filters it out because no active
* variant offers it.
*/
private async removeUnreferencedOptions(
tx: Prisma.TransactionClient,
productId: string,
keepKeys: string[],
): Promise<void> {
const doomed = await tx.productOption.findMany({
where: { productId, key: { notIn: keepKeys } },
select: {
id: true,
values: { select: { id: true, _count: { select: { variantLinks: true } } } },
},
});
for (const option of doomed) {
const referenced = option.values.some((value) => value._count.variantLinks > 0);
if (referenced) continue;
await tx.productOption.delete({ where: { id: option.id } });
}
}
private async removeUnreferencedValues(
tx: Prisma.TransactionClient,
optionId: string,
keepValues: string[],
): Promise<void> {
const doomed = await tx.productOptionValue.findMany({
where: { optionId, value: { notIn: keepValues } },
select: { id: true, _count: { select: { variantLinks: true } } },
});
const deletable = doomed.filter((value) => value._count.variantLinks === 0).map((v) => v.id);
if (deletable.length > 0) {
await tx.productOptionValue.deleteMany({ where: { id: { in: deletable } } });
}
}
/**
* Applies the variant matrix plan.
*
* The planning itself is a pure function (`planVariantMatrix`) with its own
* tests; this method only performs the writes it describes.
*/
private async syncVariants(
tx: Prisma.TransactionClient,
productId: string,
skuPrefix: string,
basePriceAmount: number,
options: MatrixOption[],
): Promise<void> {
const existing = await tx.productVariant.findMany({
where: { productId },
select: { id: true, sku: true, optionValues: { select: { optionValueId: true } } },
});
// Built from what the operator submitted, NOT from every row in the
// database — retained-for-history values must not regenerate variants.
const plan = planVariantMatrix({
options,
existing: existing.map((variant) => ({
id: variant.id,
sku: variant.sku,
optionValueIds: variant.optionValues.map((link) => link.optionValueId),
})),
skuPrefix,
});
const optionIdByValueId = new Map<string, string>();
const optionRows = await tx.productOption.findMany({
where: { productId },
select: { id: true, values: { select: { id: true } } },
});
for (const option of optionRows) {
for (const value of option.values) {
optionIdByValueId.set(value.id, option.id);
}
}
for (const row of plan.created) {
const variant = await tx.productVariant.create({
data: {
productId,
sku: await uniqueSku(tx, row.suggestedSku),
title: row.title,
currency: 'VND',
priceAmount: basePriceAmount,
position: row.position,
status: 'ACTIVE',
},
select: { id: true },
});
await tx.productVariantOptionValue.createMany({
data: row.optionValueIds.map((optionValueId) => ({
variantId: variant.id,
optionId: optionIdByValueId.get(optionValueId) ?? '',
optionValueId,
})),
skipDuplicates: true,
});
}
// Keep display order and titles in step with the current option ordering.
for (const row of plan.kept) {
if (!row.existingId) continue;
await tx.productVariant.update({
where: { id: row.existingId },
data: { position: row.position, title: row.title, status: 'ACTIVE' },
});
}
if (plan.archivedIds.length > 0) {
// Archived, never deleted — order lines reference these ids.
await tx.productVariant.updateMany({
where: { id: { in: plan.archivedIds } },
data: { status: 'ARCHIVED' },
});
}
}
/**
* Recomputes the price projection, drops the catalog cache, and records the
* change. Every write path ends here.
*/
private async afterWrite(
actorUserId: string,
action: string,
productId: string,
changes: Record<string, unknown>,
): Promise<void> {
await this.repository.recomputePricing(productId);
const dropped = await this.redis.deleteByPrefix(CACHE_KEYS.catalogPrefix());
this.logger.log(`${action} on ${productId}; dropped ${dropped} catalog cache key(s)`);
this.audit.record({
actorUserId,
action,
resourceType: 'Product',
resourceId: productId,
changes: changes as Prisma.InputJsonValue,
});
}
}
/**
* SKUs are unique across the whole catalog, so a generated one can collide with
* a product that already used that colour/size naming. Suffix until free.
*/
async function uniqueSku(tx: Prisma.TransactionClient, base: string): Promise<string> {
for (let suffix = 0; suffix < 100; suffix += 1) {
const sku = suffix === 0 ? base : `${base}-${suffix + 1}`;
const clash = await tx.productVariant.findUnique({ where: { sku }, select: { id: true } });
if (!clash) return sku;
}
throw AppException.conflict(`Could not generate a unique SKU from "${base}".`);
}
@@ -63,9 +63,24 @@ export class ProductsMapper {
breadcrumbs: readonly Breadcrumb[],
): StorefrontProduct {
const translation = pickTranslation(row.translations, locale);
const options = row.options.map((option) => this.toOption(option, locale));
const variants = row.variants.map((variant) => this.toStorefrontVariant(variant, locale));
/**
* Only option values that at least one *active* variant offers.
*
* Removing a colourway retains its option value when archived variants
* still reference it (order history depends on the link). Without this
* filter the shopper would see a swatch that can never be selected —
* a permanently disabled control with no explanation.
*/
const sellableValueIds = new Set(
variants.flatMap((variant) => variant.optionValues.map((ov) => ov.optionValueId)),
);
const options = row.options
.map((option) => this.toOption(option, locale, sellableValueIds))
.filter((option) => option.values.length > 0);
return {
id: row.id,
name: coalesceRequired(translation?.name, row.name),
@@ -218,21 +233,29 @@ export class ProductsMapper {
};
}
private toOption(option: ProductDetailRow['options'][number], locale: Locale): ProductOption {
private toOption(
option: ProductDetailRow['options'][number],
locale: Locale,
sellableValueIds: ReadonlySet<string>,
): ProductOption {
return {
id: option.id,
name: coalesceRequired(pickTranslation(option.translations, locale)?.name, option.name),
key: option.key,
position: option.position,
values: option.values.map((value) => ({
id: value.id,
optionId: value.optionId,
label: coalesceRequired(pickTranslation(value.translations, locale)?.label, value.label),
value: value.value,
position: value.position,
swatchHex: value.swatchHex,
swatchImageUrl: value.swatchImage ? this.mediaUrl.url(value.swatchImage.storageKey) : null,
})),
values: option.values
.filter((value) => sellableValueIds.has(value.id))
.map((value) => ({
id: value.id,
optionId: value.optionId,
label: coalesceRequired(pickTranslation(value.translations, locale)?.label, value.label),
value: value.value,
position: value.position,
swatchHex: value.swatchHex,
swatchImageUrl: value.swatchImage
? this.mediaUrl.url(value.swatchImage.storageKey)
: null,
})),
};
}
@@ -2,6 +2,9 @@ import { Module } from '@nestjs/common';
import { CategoriesModule } from '@/modules/categories/categories.module';
import { ProductsAdminController } from './products-admin.controller';
import { ProductsAdminMapper } from './products-admin.mapper';
import { ProductsAdminService } from './products-admin.service';
import { ProductsController } from './products.controller';
import { ProductsMapper } from './products.mapper';
import { ProductsRepository } from './products.repository';
@@ -11,13 +14,21 @@ import { ProductsService } from './products.service';
* ProductsModule — owns `products`, `product_translations`, `product_options`,
* `product_option_values`, `product_images` and `product_attributes`.
*
* The catalog aggregate root. Other modules reference a product by id and read
* through this module's public service.
* The catalog aggregate root. Read and write live in the same module but in
* separate services: they have different consumers, different payloads and very
* different caching rules, and merging them would mean the storefront query
* grows admin-only joins it must never expose.
*/
@Module({
imports: [CategoriesModule],
controllers: [ProductsController],
providers: [ProductsService, ProductsRepository, ProductsMapper],
controllers: [ProductsController, ProductsAdminController],
providers: [
ProductsService,
ProductsAdminService,
ProductsRepository,
ProductsMapper,
ProductsAdminMapper,
],
exports: [ProductsService],
})
export class ProductsModule {}
@@ -413,6 +413,81 @@ export class ProductsRepository {
});
}
/**
* Full admin payload: every locale, cost prices, stock, and DRAFT/ARCHIVED
* products included. Deliberately separate from the storefront query, which
* must never see cost price or unpublished rows.
*/
findByIdForAdmin(id: string) {
return this.prisma.product.findFirst({
where: { id, deletedAt: null },
select: {
id: true,
status: true,
publishedAt: true,
brandId: true,
primaryCategoryId: true,
genderTargets: true,
sportTypes: true,
createdAt: true,
updatedAt: true,
translations: true,
collections: { select: { collectionId: true } },
options: {
orderBy: { position: 'asc' },
select: {
id: true,
key: true,
position: true,
translations: true,
values: {
orderBy: { position: 'asc' },
select: {
id: true,
value: true,
position: true,
swatchHex: true,
translations: true,
},
},
},
},
images: {
orderBy: { position: 'asc' },
select: {
id: true,
mediaId: true,
position: true,
optionValueId: true,
media: { select: { storageKey: true, altText: true } },
},
},
attributes: {
orderBy: { position: 'asc' },
select: { id: true, key: true, position: true, translations: true },
},
variants: {
orderBy: { position: 'asc' },
select: {
id: true,
sku: true,
barcode: true,
title: true,
priceAmount: true,
salePriceAmount: true,
compareAtAmount: true,
costAmount: true,
weightGrams: true,
status: true,
position: true,
optionValues: { select: { optionValueId: true } },
stockLevels: { select: { onHand: true, reserved: true } },
},
},
},
});
}
/** All translated slugs for a locale — feeds `generateStaticParams`/sitemaps. */
findAllSlugs(locale: Locale) {
return this.prisma.productTranslation.findMany({
@@ -534,3 +609,6 @@ export class ProductsRepository {
export type ProductListRow = Awaited<ReturnType<ProductsRepository['findList']>>[number];
export type ProductDetailRow = NonNullable<Awaited<ReturnType<ProductsRepository['findBySlug']>>>;
export type AdminProductRow = NonNullable<
Awaited<ReturnType<ProductsRepository['findByIdForAdmin']>>
>;
@@ -0,0 +1,153 @@
import {
buildSku,
combinationSignature,
planVariantMatrix,
slugify,
type MatrixOption,
} from './variant-matrix';
/**
* The variant matrix decides what is purchasable. A bug here either deletes a
* merchandiser's pricing work or resurrects products that should be gone, so
* the behaviour is pinned rather than left to inspection.
*/
const colour: MatrixOption = {
key: 'colour',
position: 0,
values: [
{ id: 'c-black', value: 'black', label: 'Black', position: 0 },
{ id: 'c-white', value: 'white', label: 'White', position: 1 },
],
};
const size: MatrixOption = {
key: 'size',
position: 1,
values: [
{ id: 's-s', value: 's', label: 'S', position: 0 },
{ id: 's-m', value: 'm', label: 'M', position: 1 },
],
};
describe('planVariantMatrix', () => {
it('generates every combination for a fresh product', () => {
const plan = planVariantMatrix({ options: [colour, size], existing: [], skuPrefix: 'TEE' });
expect(plan.created).toHaveLength(4);
expect(plan.kept).toHaveLength(0);
expect(plan.archivedIds).toHaveLength(0);
expect(plan.created.map((row) => row.title)).toEqual([
'Black / S',
'Black / M',
'White / S',
'White / M',
]);
});
it('orders combinations with the first option varying slowest', () => {
// "all sizes of black, then all sizes of white" — not interleaved, which is
// what makes the generated grid readable.
const plan = planVariantMatrix({ options: [colour, size], existing: [], skuPrefix: 'TEE' });
expect(plan.created.map((row) => row.suggestedSku)).toEqual([
'TEE-BLACK-S',
'TEE-BLACK-M',
'TEE-WHITE-S',
'TEE-WHITE-M',
]);
});
it('keeps existing variants so their price and stock survive an edit', () => {
const existing = [
{ id: 'v1', sku: 'TEE-BLACK-S', optionValueIds: ['c-black', 's-s'] },
{ id: 'v2', sku: 'TEE-BLACK-M', optionValueIds: ['c-black', 's-m'] },
];
const plan = planVariantMatrix({ options: [colour, size], existing, skuPrefix: 'TEE' });
expect(plan.kept.map((row) => row.existingId)).toEqual(['v1', 'v2']);
expect(plan.created).toHaveLength(2);
expect(plan.archivedIds).toHaveLength(0);
});
it('matches combinations regardless of option-value order', () => {
// A reordered option list must not read as a brand-new set of variants —
// that would wipe every price and stock level on the product.
const existing = [{ id: 'v1', sku: 'X', optionValueIds: ['s-s', 'c-black'] }];
const plan = planVariantMatrix({ options: [colour, size], existing, skuPrefix: 'TEE' });
expect(plan.kept).toHaveLength(1);
expect(plan.kept[0]?.existingId).toBe('v1');
});
it('archives combinations that no longer exist rather than deleting them', () => {
// Order lines reference variant ids; deleting one breaks history.
const existing = [
{ id: 'v1', sku: 'TEE-BLACK-S', optionValueIds: ['c-black', 's-s'] },
{ id: 'gone', sku: 'TEE-RED-S', optionValueIds: ['c-red', 's-s'] },
];
const plan = planVariantMatrix({ options: [colour, size], existing, skuPrefix: 'TEE' });
expect(plan.archivedIds).toEqual(['gone']);
});
it('refuses to plan when an option has no values, instead of archiving everything', () => {
const existing = [{ id: 'v1', sku: 'X', optionValueIds: ['c-black', 's-s'] }];
const empty: MatrixOption = { key: 'size', position: 1, values: [] };
const plan = planVariantMatrix({ options: [colour, empty], existing, skuPrefix: 'TEE' });
// An empty option is a half-finished edit, not an instruction to unpublish
// every variant on the product.
expect(plan.archivedIds).toHaveLength(0);
expect(plan.created).toHaveLength(0);
});
it('scales to a third option without special-casing', () => {
const width: MatrixOption = {
key: 'width',
position: 2,
values: [
{ id: 'w-r', value: 'regular', label: 'Regular', position: 0 },
{ id: 'w-w', value: 'wide', label: 'Wide', position: 1 },
],
};
const plan = planVariantMatrix({
options: [colour, size, width],
existing: [],
skuPrefix: 'TEE',
});
expect(plan.created).toHaveLength(8);
expect(plan.created[0]?.title).toBe('Black / S / Regular');
});
});
describe('combinationSignature', () => {
it('is order-independent', () => {
expect(combinationSignature(['b', 'a'])).toBe(combinationSignature(['a', 'b']));
});
});
describe('buildSku', () => {
it('uppercases and hyphenates', () => {
expect(buildSku('vel art', ['black', 'xl'])).toBe('VEL-ART-BLACK-XL');
});
it('strips diacritics and punctuation', () => {
expect(buildSku('Áo', ['xanh neon'])).toBe('AO-XANH-NEON');
});
});
describe('slugify', () => {
it('handles Vietnamese diacritics including đ', () => {
expect(slugify('Áo Chạy Bộ Aero')).toBe('ao-chay-bo-aero');
expect(slugify('Giày Đá Bóng')).toBe('giay-da-bong');
});
it('collapses punctuation and trims separators', () => {
expect(slugify(' Tempo — Split/Short! ')).toBe('tempo-split-short');
});
});
@@ -0,0 +1,170 @@
/**
* Variant matrix generation.
*
* A pure function on purpose: this is the single most consequential piece of
* logic in the catalog, and it needs to be testable without a database, a Nest
* container or a fixture. Everything it touches is plain data.
*
* The rule it enforces (ADR-0003): a product's purchasable units are exactly
* the cartesian product of its option values. Adding a colour must not silently
* destroy the price and stock of every existing size.
*/
export interface MatrixOption {
key: string;
position: number;
values: { id: string; value: string; label: string; position: number }[];
}
export interface ExistingVariant {
id: string;
sku: string;
/** The option-value ids this variant resolves to. Order-independent. */
optionValueIds: string[];
}
export interface MatrixRow {
/** Present when this combination already exists. */
existingId: string | null;
optionValueIds: string[];
/** Stable identity for the combination, independent of option order. */
signature: string;
/** "Black / M" — from the option values, in option order. */
title: string;
suggestedSku: string;
position: number;
}
export interface MatrixPlan {
/** Combinations that already exist and should be kept as-is. */
kept: MatrixRow[];
/** Combinations that do not exist yet and must be created. */
created: MatrixRow[];
/**
* Variants whose combination no longer exists.
*
* ARCHIVED, never deleted: order lines reference variant ids, and deleting
* one would either break a historical order or cascade into it. An archived
* variant stops being sellable and stops appearing anywhere except history.
*/
archivedIds: string[];
}
/**
* Order-independent identity for a combination.
*
* Sorting the ids means `[black, M]` and `[M, black]` produce the same
* signature — without it, a reordered option list would look like an entirely
* new set of variants and wipe every price and stock level on the product.
*/
export function combinationSignature(optionValueIds: readonly string[]): string {
return [...optionValueIds].sort().join('|');
}
/**
* Builds the full matrix and diffs it against what exists.
*
* Returns a *plan* rather than performing writes, so the caller can apply it in
* one transaction and so the decision is inspectable in a test.
*/
export function planVariantMatrix(params: {
options: MatrixOption[];
existing: ExistingVariant[];
skuPrefix: string;
}): MatrixPlan {
const options = [...params.options].sort((a, b) => a.position - b.position);
// A product with no options has no combinations, so every existing variant
// would be archived. That is almost certainly a mistake in the caller rather
// than an intent to unpublish everything, so refuse instead.
if (options.length === 0 || options.some((option) => option.values.length === 0)) {
return { kept: [], created: [], archivedIds: [] };
}
const existingBySignature = new Map(
params.existing.map((variant) => [combinationSignature(variant.optionValueIds), variant]),
);
const combinations = cartesian(options.map((option) => option.values));
const kept: MatrixRow[] = [];
const created: MatrixRow[] = [];
const seen = new Set<string>();
combinations.forEach((combination, index) => {
const optionValueIds = combination.map((value) => value.id);
const signature = combinationSignature(optionValueIds);
seen.add(signature);
const row: MatrixRow = {
existingId: existingBySignature.get(signature)?.id ?? null,
optionValueIds,
signature,
title: combination.map((value) => value.label).join(' / '),
suggestedSku: buildSku(
params.skuPrefix,
combination.map((value) => value.value),
),
position: index,
};
if (row.existingId) {
kept.push(row);
} else {
created.push(row);
}
});
const archivedIds = params.existing
.filter((variant) => !seen.has(combinationSignature(variant.optionValueIds)))
.map((variant) => variant.id);
return { kept, created, archivedIds };
}
/**
* Cartesian product, preserving option order so the first option varies
* slowest — which is what makes the generated grid read as "all sizes of black,
* then all sizes of white" rather than an interleaved jumble.
*/
function cartesian<T>(groups: T[][]): T[][] {
return groups.reduce<T[][]>(
(accumulator, group) =>
accumulator.flatMap((combination) => group.map((item) => [...combination, item])),
[[]],
);
}
/**
* `VEL-ART` + `black` + `m` → `VEL-ART-BLACK-M`.
*
* A suggestion only. SKUs frequently have to match an existing ERP or
* warehouse scheme, so the editor always lets an operator override it — and the
* database, not this function, is what guarantees uniqueness.
*/
export function buildSku(prefix: string, values: readonly string[]): string {
const clean = (input: string) =>
input
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^A-Za-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.toUpperCase();
return [clean(prefix), ...values.map(clean)].filter(Boolean).join('-');
}
/** `Áo Chạy Bộ Aero` → `ao-chay-bo-aero`. Vietnamese diacritics included. */
export function slugify(input: string): string {
return (
input
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
// đ/Đ has no combining form, so NFD leaves it intact.
.replace(/[đĐ]/g, 'd')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 180)
);
}
+4
View File
@@ -17,10 +17,14 @@
"@sport/ui": "workspace:*",
"@sport/validation": "workspace:*",
"@tanstack/react-query": "^5.101.4",
"embla-carousel-react": "8.6.0",
"lucide-react": "1.31.0",
"motion": "13.1.0",
"next": "catalog:",
"next-intl": "^4.13.6",
"react": "catalog:",
"react-dom": "catalog:",
"tw-animate-css": "1.4.0",
"zod": "catalog:",
"zustand": "^5.0.14"
},
@@ -2,10 +2,10 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { SiteHeader } from '@/components/commerce/site-header';
import { SiteFooter } from '@/components/layout/site-footer';
import { SiteHeader } from '@/components/layout/site-header';
import { fetchNavigation } from '@/features/product/services/catalog';
import { Link } from '@/i18n/navigation';
import { fetchNavigation } from '@/lib/catalog';
import { routes } from '@/lib/routes';
/**
@@ -4,7 +4,7 @@ import { setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { ProductListing } from '@/features/product/components/product-listing';
import { ProductListing } from '@/components/commerce/product-listing';
import { CATALOG_CACHE, getServerApi } from '@/lib/api';
import { parseListingParams, type RawSearchParams } from '@/lib/search-params';
@@ -2,9 +2,9 @@ import { setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { SiteHeader } from '@/components/commerce/site-header';
import { SiteFooter } from '@/components/layout/site-footer';
import { SiteHeader } from '@/components/layout/site-header';
import { fetchNavigation } from '@/features/product/services/catalog';
import { fetchNavigation } from '@/lib/catalog';
/**
* Chrome shared by every browsing route.
@@ -3,7 +3,7 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { ProductListing } from '@/features/product/components/product-listing';
import { ProductListing } from '@/components/commerce/product-listing';
import { parseListingParams, type RawSearchParams } from '@/lib/search-params';
type PageProps = {
@@ -1,11 +1,11 @@
import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { Button } from '@sport/ui';
import { ProductGrid } from '@/features/product/components/product-grid';
import { fetchProducts } from '@/features/product/services/catalog';
import { Hero } from '@/components/commerce/hero';
import { ProductGrid } from '@/components/commerce/product-grid';
import { Link } from '@/i18n/navigation';
import { fetchProducts } from '@/lib/catalog';
import { SPORT_NAV, routes } from '@/lib/routes';
type PageProps = { params: Promise<{ locale: string }> };
@@ -26,34 +26,15 @@ export default async function HomePage({ params }: PageProps) {
return (
<>
<section className="border-ink-200 bg-ink-950 border-b text-white">
<div className="max-w-page px-gutter mx-auto py-24 sm:py-32">
<p className="text-volt-500 text-xs font-semibold uppercase tracking-widest">
{t('heroEyebrow')}
</p>
<h1 className="mt-4 max-w-3xl text-5xl font-black uppercase leading-[0.95] sm:text-7xl">
{t('heroTitle')}
</h1>
<p className="text-ink-300 mt-6 max-w-xl text-base">{t('heroBody')}</p>
<div className="mt-10 flex flex-wrap gap-3">
<Link href={routes.collection('new-arrivals')}>
<Button variant="accent" size="lg">
{t('heroCta')}
</Button>
</Link>
<Link href={routes.men()}>
<Button
variant="outline"
size="lg"
className="hover:text-ink-950 border-white text-white hover:bg-white"
>
{t('heroSecondary')}
</Button>
</Link>
</div>
</div>
</section>
<Hero
eyebrow={t('heroEyebrow')}
title={t('heroTitle')}
body={t('heroBody')}
primaryCta={t('heroCta')}
primaryHref={routes.collection('new-arrivals')}
secondaryCta={t('heroSecondary')}
secondaryHref={routes.men()}
/>
<section className="max-w-page px-gutter mx-auto py-16">
<h2 className="text-ink-400 text-xs font-semibold uppercase tracking-widest">
@@ -4,10 +4,10 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import { LOCALES, type Locale } from '@sport/types';
import { ProductDetail } from '@/features/product/components/product-detail';
import { fetchProduct } from '@/features/product/services/catalog';
import { ProductDetail } from '@/components/commerce/product-detail';
import { Link, redirect } from '@/i18n/navigation';
import { getServerApi } from '@/lib/api';
import { fetchProduct } from '@/lib/catalog';
import { routes } from '@/lib/routes';
type PageProps = { params: Promise<{ locale: string; slug: string }> };
@@ -3,7 +3,7 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { ProductListing } from '@/features/product/components/product-listing';
import { ProductListing } from '@/components/commerce/product-listing';
import { parseListingParams, type RawSearchParams } from '@/lib/search-params';
type PageProps = {
@@ -4,7 +4,7 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { ProductListing } from '@/features/product/components/product-listing';
import { ProductListing } from '@/components/commerce/product-listing';
import { routing } from '@/i18n/routing';
import { SPORT_NAV, isSportSlug } from '@/lib/routes';
import { parseListingParams, type RawSearchParams } from '@/lib/search-params';
@@ -3,7 +3,7 @@ import { getTranslations, setRequestLocale } from 'next-intl/server';
import type { Locale } from '@sport/types';
import { ProductListing } from '@/features/product/components/product-listing';
import { ProductListing } from '@/components/commerce/product-listing';
import { parseListingParams, type RawSearchParams } from '@/lib/search-params';
type PageProps = {
@@ -13,9 +13,9 @@ export default function NotFound() {
<p className="text-ink-400 text-xs font-semibold uppercase tracking-widest">{t('code')}</p>
<h1 className="mt-4 text-5xl font-black uppercase">{t('title')}</h1>
<p className="text-ink-500 mt-4 max-w-md">{t('body')}</p>
<Link href={routes.home()} className="mt-8">
<Button>{t('cta')}</Button>
</Link>
<Button className="mt-8" asChild>
<Link href={routes.home()}>{t('cta')}</Link>
</Button>
</div>
);
}
@@ -0,0 +1,55 @@
'use client';
import { SlidersHorizontal } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { ReactNode } from 'react';
import { Button, Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@sport/ui';
/**
* Puts the filter rail behind a button on small screens.
*
* Without this the rail stacks above the grid, so on a phone every product sits
* below a full screen of filter controls — the listing appears empty until you
* scroll past the thing that is meant to help you narrow it.
*
* The rail itself is passed in as `children` and stays a Server Component: this
* wrapper only owns the open/closed state, so no filter rendering moves to the
* client. The links inside are ordinary navigations, which close the sheet by
* unmounting it.
*/
export function FilterSheet({
children,
activeCount,
}: {
children: ReactNode;
activeCount: number;
}) {
const t = useTranslations('listing');
return (
<Sheet>
<SheetTrigger asChild>
<Button variant="outline" size="sm" className="w-full lg:hidden">
<SlidersHorizontal />
{t('filters')}
{activeCount > 0 ? (
<span className="bg-ink-950 grid size-5 place-items-center rounded-full text-[0.625rem] text-white">
{activeCount}
</span>
) : null}
</Button>
</SheetTrigger>
<SheetContent side="left" className="w-[85vw] overflow-y-auto sm:max-w-sm">
<SheetHeader className="border-ink-200 border-b">
<SheetTitle className="text-sm font-semibold uppercase tracking-widest">
{t('filters')}
</SheetTitle>
</SheetHeader>
<div className="px-gutter py-6">{children}</div>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,117 @@
'use client';
import { ArrowRight } from 'lucide-react';
import { motion, useReducedMotion } from 'motion/react';
import { Button } from '@sport/ui';
import { Link } from '@/i18n/navigation';
/**
* The homepage hero.
*
* Hand-built rather than assembled from primitives: this is the first thing a
* shopper sees and it is almost entirely brand — the oversized condensed
* headline, the volt eyebrow, the stagger on entry. There is no registry
* component that would make this better, only one that would make it generic.
*
* The animation is a single staggered rise. It runs once, on mount, and it is
* short — a hero that keeps moving is a hero that delays the first click.
*/
export function Hero({
eyebrow,
title,
body,
primaryCta,
primaryHref,
secondaryCta,
secondaryHref,
}: {
eyebrow: string;
title: string;
body: string;
primaryCta: string;
primaryHref: string;
secondaryCta: string;
secondaryHref: string;
}) {
// Honour the OS setting rather than animating regardless: vestibular
// sensitivity is exactly the case a large moving headline aggravates.
const reduceMotion = useReducedMotion();
const rise = reduceMotion
? {}
: {
initial: { opacity: 0, y: 16 },
animate: { opacity: 1, y: 0 },
};
return (
<section className="bg-ink-950 relative overflow-hidden border-b border-white/10 text-white">
{/*
A single volt bloom, well off-centre, painted as a radial gradient.
The first version was a blurred div — `size-[32rem]` with `blur(64px)`.
It promoted a half-megapixel element to its own composited layer, and in
that state the browser dropped the paint of everything beneath it: the
headline, the copy and both CTAs rendered as empty black. A gradient
produces the same image with no filter and no extra layer.
*/}
<div
aria-hidden
className="pointer-events-none absolute inset-0"
style={{
background:
'radial-gradient(38rem 38rem at 88% -10%, color-mix(in oklab, var(--color-volt-500) 18%, transparent), transparent 70%)',
}}
/>
<div className="max-w-page px-gutter relative mx-auto py-24 sm:py-32">
<motion.p
{...rise}
transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
className="text-volt-500 text-xs font-semibold uppercase tracking-widest"
>
{eyebrow}
</motion.p>
<motion.h1
{...rise}
transition={{ duration: 0.5, delay: 0.06, ease: [0.22, 1, 0.36, 1] }}
className="mt-4 max-w-3xl text-5xl font-black uppercase leading-[0.95] sm:text-7xl"
>
{title}
</motion.h1>
<motion.p
{...rise}
transition={{ duration: 0.5, delay: 0.12, ease: [0.22, 1, 0.36, 1] }}
className="text-ink-300 mt-6 max-w-xl text-base"
>
{body}
</motion.p>
<motion.div
{...rise}
transition={{ duration: 0.5, delay: 0.18, ease: [0.22, 1, 0.36, 1] }}
className="mt-10 flex flex-wrap gap-3"
>
<Button variant="accent" size="lg" asChild>
<Link href={primaryHref}>
{primaryCta}
<ArrowRight />
</Link>
</Button>
<Button
variant="outline"
size="lg"
className="hover:text-ink-950 border-white text-white hover:bg-white"
asChild
>
<Link href={secondaryHref}>{secondaryCta}</Link>
</Button>
</motion.div>
</div>
</section>
);
}
@@ -0,0 +1,117 @@
'use client';
import { Loader2 } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { isApiClientError, type ProductListQuery } from '@sport/api-client';
import type { Locale, ProductListItem } from '@sport/types';
import { Button } from '@sport/ui';
import { Link } from '@/i18n/navigation';
import { browserApi } from '@/lib/api';
import { buildListingHref } from '@/lib/listing-href';
import { ProductCard } from './product-card';
/**
* Appends the next page of products in place.
*
* The button is a real `<a href="?cursor=…">`, and that is the whole design.
* With JavaScript the click is intercepted and the next page is appended, which
* is what a shopper browsing a category actually wants. Without it — and for a
* crawler — the link is followed and the server renders the next page normally.
* So the catalog stays reachable beyond the first 24 products without a sitemap
* and without an infinite scroll that search engines cannot walk.
*
* Only the *appended* products are client-rendered. The first page is server
* rendered by `ProductGrid` above this component, so the initial paint and its
* markup are unchanged.
*/
export function LoadMore({
locale,
query,
basePath,
initialCursor,
initialCount,
totalCount,
}: {
locale: Locale;
query: ProductListQuery;
basePath: string;
initialCursor: string;
initialCount: number;
totalCount: number;
}) {
const t = useTranslations('listing');
const [extra, setExtra] = useState<ProductListItem[]>([]);
const [cursor, setCursor] = useState<string | null>(initialCursor);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const shown = initialCount + extra.length;
async function loadNext() {
if (!cursor || loading) return;
setLoading(true);
setError(null);
try {
const result = await browserApi.catalog.listProducts(locale, { ...query, cursor });
setExtra((current) => [...current, ...result.items]);
setCursor(result.pageInfo.nextCursor);
} catch (caught) {
// Leaves the href intact, so the fallback is still a working navigation
// rather than a dead end.
setError(isApiClientError(caught) ? caught.message : t('loadFailed'));
} finally {
setLoading(false);
}
}
return (
<>
{extra.length > 0 ? (
<div className="mt-10 grid grid-cols-2 gap-x-4 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{extra.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
) : null}
<div className="mt-12 flex flex-col items-center gap-3">
<p className="text-ink-400 text-xs uppercase tracking-widest">
{t('showing', { shown, total: totalCount })}
</p>
{error ? (
<p role="alert" className="text-danger text-sm">
{error}
</p>
) : null}
{cursor ? (
<Button variant="outline" size="lg" asChild>
<Link
href={buildListingHref(basePath, query, { cursor })}
onClick={(event) => {
// Let modified clicks (new tab, download, middle click) behave
// like the ordinary link this genuinely is.
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
void loadNext();
}}
aria-busy={loading}
>
{loading ? <Loader2 className="animate-spin" /> : null}
{t('loadMore')}
</Link>
</Button>
) : null}
</div>
</>
);
}
@@ -0,0 +1,132 @@
'use client';
import { ChevronDown } from 'lucide-react';
import { useEffect, useState } from 'react';
import { cn } from '@sport/ui';
import { Link } from '@/i18n/navigation';
export interface MegaMenuColumn {
readonly heading: string;
readonly links: readonly { readonly label: string; readonly href: string }[];
}
export interface MegaMenuEntry {
readonly id: string;
readonly label: string;
readonly href: string;
readonly columns: readonly MegaMenuColumn[];
}
/**
* Desktop navigation with a full-width drop panel.
*
* Hand-built rather than Radix NavigationMenu. The panel here is a plain hover
* region with no roving focus and no collision logic to get wrong, and it is
* the most brand-visible element in the chrome — the animation, the full-bleed
* black panel, the column rhythm. Radix would supply behaviour this does not
* need and constrain the markup that carries the identity.
*
* What it still has to get right, and does:
* - Opens on hover *and* on keyboard focus, so it is reachable without a mouse.
* - Closes on Escape and on focus leaving the group.
* - The top-level item stays a real link, so a sport is one click away rather
* than requiring the panel.
*/
export function MegaMenu({
entries,
className,
}: {
entries: readonly MegaMenuEntry[];
className?: string;
}) {
const [openId, setOpenId] = useState<string | null>(null);
// Escape is bound to the document rather than to a wrapper's `onKeyDown`:
// the panel is dismissible from anywhere while it is open, and hanging key
// handlers off a non-interactive container would be lying about what that
// container is.
useEffect(() => {
if (!openId) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') setOpenId(null);
};
document.addEventListener('keydown', onKeyDown);
return () => document.removeEventListener('keydown', onKeyDown);
}, [openId]);
return (
<div className={cn('flex items-center gap-5', className)} onMouseLeave={() => setOpenId(null)}>
{entries.map((entry) => {
const open = openId === entry.id;
const hasPanel = entry.columns.length > 0;
return (
<div
key={entry.id}
className="static"
onMouseEnter={() => setOpenId(entry.id)}
onFocus={() => setOpenId(entry.id)}
onBlur={(event) => {
// Only close when focus leaves the whole group, otherwise tabbing
// from the trigger into the panel would shut it immediately.
if (!event.currentTarget.contains(event.relatedTarget)) setOpenId(null);
}}
>
<Link
href={entry.href}
aria-expanded={hasPanel ? open : undefined}
className={cn(
'hover:text-volt-600 focus-visible:ring-ring/50 flex items-center gap-1 py-5 text-xs font-semibold uppercase tracking-widest outline-none transition-colors focus-visible:ring-[3px]',
open && 'text-volt-600',
)}
>
{entry.label}
{hasPanel ? (
<ChevronDown
className={cn('size-3 transition-transform duration-200', open && 'rotate-180')}
/>
) : null}
</Link>
{/*
`border-y`, not `border-t`. On the homepage the panel is black
over a black hero, and without a bottom edge the two surfaces
merge — the menu reads as text floating on the hero rather than as
a panel in front of it.
*/}
{hasPanel && open ? (
<div className="bg-ink-950 absolute inset-x-0 top-full z-40 border-y border-white/15 text-white shadow-2xl">
<div className="max-w-page px-gutter mx-auto grid grid-cols-2 gap-10 py-10 md:grid-cols-4">
{entry.columns.map((column) => (
<div key={column.heading}>
<p className="text-volt-500 text-[0.625rem] font-semibold uppercase tracking-widest">
{column.heading}
</p>
<ul className="mt-4 space-y-2.5">
{column.links.map((link) => (
<li key={link.href}>
<Link
href={link.href}
onClick={() => setOpenId(null)}
className="text-ink-300 hover:text-volt-500 text-sm transition-colors"
>
{link.label}
</Link>
</li>
))}
</ul>
</div>
))}
</div>
</div>
) : null}
</div>
);
})}
</div>
);
}
@@ -0,0 +1,77 @@
'use client';
import { Menu } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@sport/ui';
import { Link } from '@/i18n/navigation';
import type { MegaMenuEntry } from './mega-menu';
/**
* The small-screen counterpart to the mega menu.
*
* A Sheet rather than a bespoke drawer: focus trapping, scroll locking, the
* Escape handler and the `aria-modal` wiring are exactly the infrastructure
* worth taking from the registry. What is inside it is ours.
*
* Sections are flattened rather than nested behind accordions — with four
* groups the extra tap costs more than the scroll it saves.
*/
export function MobileNav({ entries }: { entries: readonly MegaMenuEntry[] }) {
const t = useTranslations('nav');
const [open, setOpen] = useState(false);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger
aria-label={t('openMenu')}
className="focus-visible:ring-ring/50 -ml-2 grid size-10 place-items-center outline-none focus-visible:ring-[3px] lg:hidden"
>
<Menu className="size-5" />
</SheetTrigger>
<SheetContent side="left" className="w-[85vw] gap-0 overflow-y-auto sm:max-w-sm">
<SheetHeader className="border-ink-200 border-b">
<SheetTitle className="text-lg font-black uppercase tracking-tighter">
Sport<span className="text-volt-600">.</span>
</SheetTitle>
</SheetHeader>
<nav aria-label={t('ariaMain')} className="px-gutter space-y-8 py-6">
{entries.map((entry) => (
<div key={entry.id}>
<Link
href={entry.href}
onClick={() => setOpen(false)}
className="text-sm font-black uppercase tracking-widest"
>
{entry.label}
</Link>
{entry.columns.length > 0 ? (
<ul className="mt-3 space-y-2">
{entry.columns
.flatMap((column) => column.links)
.map((link) => (
<li key={link.href}>
<Link
href={link.href}
onClick={() => setOpen(false)}
className="text-ink-500 hover:text-ink-950 text-sm"
>
{link.label}
</Link>
</li>
))}
</ul>
) : null}
</div>
))}
</nav>
</SheetContent>
</Sheet>
);
}
@@ -0,0 +1,134 @@
import Image from 'next/image';
import { useFormatter, useTranslations } from 'next-intl';
import type { ProductListItem } from '@sport/types';
import { Badge, cn } from '@sport/ui';
import { Link } from '@/i18n/navigation';
import { discountPercent, formatMoney } from '@/lib/format';
import { routes } from '@/lib/routes';
/**
* The grid card.
*
* Commerce, not UI: it knows about sale badges, price ranges and colourways,
* none of which mean anything in the admin dashboard. Built by hand because the
* card *is* the catalog — its proportions, the hover crossfade and the
* typographic hierarchy are the brand, and a generic card component would erase
* all three. See docs/architecture.md §4.
*
* Stays a Server Component. The hover swap is pure CSS, so this ships no
* JavaScript at all, and a listing renders 24 of them.
*/
export function ProductCard({
product,
priority = false,
}: {
product: ProductListItem;
priority?: boolean;
}) {
const t = useTranslations('product');
const format = useFormatter();
const { priceRange, primaryImage, hoverImage } = product;
const hasRange = priceRange.min.amount !== priceRange.max.amount;
const discount =
priceRange.compareAtMax && product.isOnSale
? discountPercent(priceRange.min, priceRange.compareAtMax)
: 0;
return (
<article className="group relative">
<div className="bg-ink-100 relative aspect-[4/5] overflow-hidden">
{primaryImage ? (
<>
<Image
src={primaryImage.url}
alt={primaryImage.altText ?? product.name}
fill
// Matches the grid below so the browser never downloads a larger
// file than it renders.
sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
className={cn(
'object-cover transition-[opacity,transform] duration-500 ease-[var(--ease-out-quint)]',
'group-hover:scale-[1.03]',
hoverImage && 'group-hover:opacity-0',
)}
placeholder={primaryImage.blurDataUrl ? 'blur' : 'empty'}
blurDataURL={primaryImage.blurDataUrl ?? undefined}
// Only the first row is priority; marking everything priority is
// the same as marking nothing.
priority={priority}
/>
{hoverImage ? (
<Image
src={hoverImage.url}
alt=""
aria-hidden
fill
sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
className="scale-[1.03] object-cover opacity-0 transition-opacity duration-500 group-hover:opacity-100"
/>
) : null}
</>
) : (
<div className="bg-ink-200 size-full" />
)}
{discount > 0 ? (
<Badge variant="sale" className="absolute left-3 top-3">
{t('save', { percent: discount })}
</Badge>
) : null}
</div>
<div className="mt-3 space-y-1">
{product.brandName ? (
<p className="text-ink-400 text-[0.625rem] font-semibold uppercase tracking-widest">
{product.brandName}
</p>
) : null}
<h3 className="text-ink-950 text-sm font-medium">
{/*
The link covers the whole card via ::after rather than wrapping it.
Wrapping put the colourway list inside the anchor, which made the
swatches part of the link's accessible name — a screen reader read
the product name followed by every colour.
*/}
<Link href={routes.product(product.slug)} className="after:absolute after:inset-0">
{product.name}
</Link>
</h3>
<p className="flex items-baseline gap-2 text-sm">
<span className={cn('font-semibold', product.isOnSale && 'text-sale')}>
{hasRange ? `${t('from')} ` : ''}
{formatMoney(priceRange.min, format)}
</span>
{priceRange.compareAtMax && product.isOnSale ? (
<span className="text-ink-400 text-xs line-through">
{formatMoney(priceRange.compareAtMax, format)}
</span>
) : null}
</p>
</div>
{product.colorSwatches.length > 1 ? (
<ul className="mt-2 flex items-center gap-1.5">
{product.colorSwatches.slice(0, 5).map((swatch) => (
<li
key={swatch.optionValueId}
className="border-ink-200 size-3 rounded-full border"
style={{ backgroundColor: swatch.swatchHex ?? undefined }}
title={swatch.label}
/>
))}
{product.colorSwatches.length > 5 ? (
<li className="text-ink-400 text-[0.625rem]">+{product.colorSwatches.length - 5}</li>
) : null}
</ul>
) : null}
</article>
);
}
@@ -1,14 +1,16 @@
'use client';
import Image from 'next/image';
import { ShoppingBag } from 'lucide-react';
import { useFormatter, useTranslations } from 'next-intl';
import { useMemo, useState } from 'react';
import { VARIANT_AVAILABILITY, type StorefrontProduct, type StorefrontVariant } from '@sport/types';
import { Badge, Button, cn } from '@sport/ui';
import { Button, cn } from '@sport/ui';
import { discountPercent, formatMoney } from '@/lib/format';
import { ProductGallery } from './product-gallery';
/**
* The PDP interaction surface: gallery and variant selector, sharing one piece
* of state.
@@ -50,16 +52,26 @@ export function ProductDetail({ product }: { product: StorefrontProduct }) {
return forColour.length > 0 ? forColour : product.images;
}, [product.images, selectedColourId]);
const [activeImage, setActiveImage] = useState(0);
const currentImage = gallery[Math.min(activeImage, gallery.length - 1)] ?? null;
const price = selectedVariant?.effectivePrice ?? product.priceRange.min;
const compareAt = selectedVariant?.compareAtPrice ?? product.priceRange.compareAtMax;
/**
* What to strike through, in priority order.
*
* A variant can be discounted two ways and both must show a reference price:
* `compareAtPrice` is the "was" price, and `salePrice` is a markdown off the
* variant's own `price`. Reading only `compareAtPrice` — as this did — left
* every sale set from the admin's variant grid rendering as a lone red number
* with nothing to compare it against.
*/
const compareAt =
selectedVariant?.compareAtPrice ??
(selectedVariant?.isOnSale ? selectedVariant.price : null) ??
product.priceRange.compareAtMax;
const discount = compareAt ? discountPercent(price, compareAt) : 0;
function select(optionKey: string, optionValueId: string) {
setSelection((current) => ({ ...current, [optionKey]: optionValueId }));
if (optionKey === 'colour') setActiveImage(0);
}
/** Values on this axis still reachable given the other choices. */
@@ -92,62 +104,16 @@ export function ProductDetail({ product }: { product: StorefrontProduct }) {
return (
<div className="grid gap-10 lg:grid-cols-2 lg:gap-16">
{/* ---- Gallery ---- */}
<div className="space-y-3">
<div className="bg-ink-100 relative aspect-[4/5] overflow-hidden">
{currentImage ? (
<Image
src={currentImage.url}
alt={currentImage.altText ?? product.name}
fill
sizes="(min-width: 1024px) 50vw, 100vw"
className="object-cover"
placeholder={currentImage.blurDataUrl ? 'blur' : 'empty'}
blurDataURL={currentImage.blurDataUrl ?? undefined}
priority
/>
) : (
<div className="bg-ink-200 size-full" />
)}
<ProductGallery
// Remounts on colourway change so Embla starts at the first photo of
// the new set rather than holding an index into the old one.
key={selectedColourId ?? 'all'}
images={gallery}
productName={product.name}
discount={discount}
saveLabel={t('save', { percent: discount })}
/>
{discount > 0 ? (
<Badge variant="sale" className="absolute left-4 top-4">
{t('save', { percent: discount })}
</Badge>
) : null}
</div>
{gallery.length > 1 ? (
<ul className="grid grid-cols-4 gap-3">
{gallery.map((image, index) => (
<li key={image.id}>
<button
type="button"
onClick={() => setActiveImage(index)}
aria-current={index === activeImage}
className={cn(
'bg-ink-100 relative block aspect-[4/5] w-full overflow-hidden border transition-colors',
index === activeImage
? 'border-ink-950'
: 'hover:border-ink-300 border-transparent',
)}
>
<Image
src={image.url}
alt=""
aria-hidden
fill
sizes="12vw"
className="object-cover"
/>
</button>
</li>
))}
</ul>
) : null}
</div>
{/* ---- Selector ---- */}
<div className="space-y-8 lg:pt-4">
<div>
{product.brand ? (
@@ -162,13 +128,18 @@ export function ProductDetail({ product }: { product: StorefrontProduct }) {
</div>
<div className="flex flex-wrap items-baseline gap-3">
<span className={cn('text-2xl font-semibold', selectedVariant?.isOnSale && 'text-sale')}>
<span className={cn('text-2xl font-semibold', discount > 0 && 'text-sale')}>
{formatMoney(price, format)}
</span>
{compareAt && discount > 0 ? (
<span className="text-ink-400 text-base line-through">
{formatMoney(compareAt, format)}
</span>
<>
<span className="text-ink-400 text-base line-through">
{formatMoney(compareAt, format)}
</span>
<span className="text-sale text-xs font-semibold uppercase tracking-widest">
{t('save', { percent: discount })}
</span>
</>
) : null}
</div>
@@ -201,7 +172,7 @@ export function ProductDetail({ product }: { product: StorefrontProduct }) {
onClick={() => select(option.key, value.id)}
title={value.label}
className={cn(
'relative flex items-center justify-center border text-xs font-medium transition-colors',
'focus-visible:ring-ring/50 relative flex items-center justify-center border text-xs font-medium outline-none transition-colors focus-visible:ring-[3px]',
isColour ? 'size-10 rounded-full' : 'h-11 min-w-14 px-3 uppercase',
selected
? 'border-ink-950 ring-ink-950 ring-1'
@@ -237,6 +208,10 @@ export function ProductDetail({ product }: { product: StorefrontProduct }) {
!selectedVariant || selectedVariant.availability === VARIANT_AVAILABILITY.OUT_OF_STOCK
}
>
{selectedVariant &&
selectedVariant.availability !== VARIANT_AVAILABILITY.OUT_OF_STOCK ? (
<ShoppingBag />
) : null}
{!selectedVariant
? t('selectSizePrompt')
: selectedVariant.availability === VARIANT_AVAILABILITY.OUT_OF_STOCK
@@ -5,6 +5,7 @@ import type { ProductFacets } from '@sport/types';
import { cn } from '@sport/ui';
import { Link } from '@/i18n/navigation';
import { buildListingHref } from '@/lib/listing-href';
/**
* Filter rail, rendered on the server as plain links.
@@ -18,10 +19,16 @@ export async function ProductFilters({
facets,
basePath,
query,
showHeading = true,
}: {
facets: ProductFacets;
basePath: string;
query: ProductListQuery;
/**
* Off inside the mobile sheet, which supplies its own title — otherwise the
* word "Filters" appears twice, once in the sheet header and once here.
*/
showHeading?: boolean;
}) {
const t = await getTranslations('listing');
@@ -37,19 +44,26 @@ export async function ProductFilters({
} else {
current.add(value);
}
return buildHref(basePath, { ...query, [key]: [...current] });
return buildListingHref(basePath, { ...query, [key]: [...current] });
}
return (
<aside className="space-y-8">
<div className="flex items-baseline justify-between">
<h2 className="text-xs font-semibold uppercase tracking-widest">{t('filters')}</h2>
{hasActiveFilters ? (
<Link href={basePath} className="text-ink-500 text-xs underline underline-offset-4">
{t('clearAll')}
</Link>
) : null}
</div>
{showHeading || hasActiveFilters ? (
<div className="flex items-baseline justify-between">
{showHeading ? (
<h2 className="text-xs font-semibold uppercase tracking-widest">{t('filters')}</h2>
) : null}
{hasActiveFilters ? (
<Link
href={basePath}
className="text-ink-500 ml-auto text-xs underline underline-offset-4"
>
{t('clearAll')}
</Link>
) : null}
</div>
) : null}
{facets.colors.length > 0 ? (
<section>
@@ -63,7 +77,7 @@ export async function ProductFilters({
<li key={colour.value}>
<Link
href={toggleHref('colors', colour.value)}
aria-pressed={active}
aria-current={active ? true : undefined}
title={`${colour.label} (${colour.count})`}
className={cn(
'flex size-8 items-center justify-center rounded-full border transition-colors',
@@ -94,7 +108,7 @@ export async function ProductFilters({
<li key={size.value}>
<Link
href={toggleHref('sizes', size.value)}
aria-pressed={active}
aria-current={active ? true : undefined}
className={cn(
'flex h-9 min-w-11 items-center justify-center border px-2 text-xs font-medium uppercase transition-colors',
active
@@ -123,7 +137,7 @@ export async function ProductFilters({
<li key={brand.value}>
<Link
href={toggleHref('brandSlugs', brand.value)}
aria-pressed={active}
aria-current={active ? true : undefined}
className={cn(
'flex items-baseline justify-between text-sm transition-colors',
active ? 'text-ink-950 font-semibold' : 'text-ink-600 hover:text-ink-950',
@@ -141,8 +155,8 @@ export async function ProductFilters({
<section>
<Link
href={buildHref(basePath, { ...query, onSale: query.onSale ? undefined : true })}
aria-pressed={Boolean(query.onSale)}
href={buildListingHref(basePath, { ...query, onSale: query.onSale ? undefined : true })}
aria-current={query.onSale ? true : undefined}
className={cn(
'inline-flex items-center gap-2 text-sm transition-colors',
query.onSale ? 'text-sale font-semibold' : 'text-ink-600 hover:text-ink-950',
@@ -157,25 +171,3 @@ export async function ProductFilters({
</aside>
);
}
/**
* Serialises a query back into a URL.
*
* Only presentation-level filters are emitted — `gender`, `sport`,
* `categorySlug` and `collectionSlug` are implied by the route itself, so
* repeating them in the query string would produce ugly, duplicate-content URLs
* like `/men?gender=MEN`.
*/
function buildHref(basePath: string, query: ProductListQuery): string {
const params = new URLSearchParams();
if (query.q) params.set('q', query.q);
if (query.colors?.length) params.set('colors', query.colors.join(','));
if (query.sizes?.length) params.set('sizes', query.sizes.join(','));
if (query.brandSlugs?.length) params.set('brandSlugs', query.brandSlugs.join(','));
if (query.onSale) params.set('onSale', 'true');
if (query.sort && query.sort !== 'newest') params.set('sort', query.sort);
const search = params.toString();
return search ? `${basePath}?${search}` : basePath;
}
@@ -0,0 +1,175 @@
'use client';
import useEmblaCarousel from 'embla-carousel-react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import Image from 'next/image';
import { useTranslations } from 'next-intl';
import { useCallback, useEffect, useState } from 'react';
import type { ProductImage } from '@sport/types';
import { Badge, cn } from '@sport/ui';
/**
* The PDP gallery.
*
* Embla rather than a plain image swap, because the mobile behaviour a shopper
* expects here is a swipe, and reimplementing momentum, drag thresholds and
* snap points on top of a `useState` index is exactly the kind of work worth
* taking off the shelf.
*
* Thumbnails stay a plain grid rather than a second carousel — with four to
* eight images there is nothing to scroll, and a nested Embla would add two
* more event handlers for no gain.
*/
export function ProductGallery({
images,
productName,
discount,
saveLabel,
}: {
images: readonly ProductImage[];
productName: string;
discount: number;
saveLabel: string;
}) {
const t = useTranslations('product');
const [emblaRef, embla] = useEmblaCarousel({ loop: false, align: 'start', duration: 22 });
const [selected, setSelected] = useState(0);
const scrollTo = useCallback((index: number) => embla?.scrollTo(index), [embla]);
useEffect(() => {
if (!embla) return;
const sync = () => setSelected(embla.selectedScrollSnap());
sync();
embla.on('select', sync);
// `reInit` is what makes the colourway swap work: swapping to a colour with
// a different number of photos changes the slide count, and without this
// Embla keeps measuring the old set and refuses to scroll to the new ones.
embla.reInit();
return () => {
embla.off('select', sync);
};
}, [embla, images.length]);
if (images.length === 0) {
return <div className="bg-ink-200 aspect-[4/5] w-full" />;
}
const canPrev = selected > 0;
const canNext = selected < images.length - 1;
return (
<div className="space-y-3">
<div className="group relative">
<div className="overflow-hidden" ref={emblaRef}>
<div className="flex touch-pan-y">
{images.map((image, index) => (
<div key={image.id} className="min-w-0 flex-[0_0_100%]">
<div className="bg-ink-100 relative aspect-[4/5] overflow-hidden">
<Image
src={image.url}
alt={image.altText ?? productName}
fill
sizes="(min-width: 1024px) 50vw, 100vw"
className="object-cover"
placeholder={image.blurDataUrl ? 'blur' : 'empty'}
blurDataURL={image.blurDataUrl ?? undefined}
priority={index === 0}
/>
</div>
</div>
))}
</div>
</div>
{discount > 0 ? (
<Badge variant="sale" className="absolute left-4 top-4">
{saveLabel}
</Badge>
) : null}
{images.length > 1 ? (
<>
<GalleryArrow
side="left"
disabled={!canPrev}
label={t('previousImage')}
onClick={() => scrollTo(selected - 1)}
/>
<GalleryArrow
side="right"
disabled={!canNext}
label={t('nextImage')}
onClick={() => scrollTo(selected + 1)}
/>
</>
) : null}
</div>
{images.length > 1 ? (
<ul className="grid grid-cols-4 gap-3">
{images.map((image, index) => (
<li key={image.id}>
<button
type="button"
onClick={() => scrollTo(index)}
aria-label={t('goToImage', { index: index + 1 })}
aria-current={index === selected}
className={cn(
'bg-ink-100 focus-visible:ring-ring/50 relative block aspect-[4/5] w-full overflow-hidden border outline-none transition-colors focus-visible:ring-[3px]',
index === selected ? 'border-ink-950' : 'hover:border-ink-300 border-transparent',
)}
>
<Image
src={image.url}
alt=""
aria-hidden
fill
sizes="12vw"
className="object-cover"
/>
</button>
</li>
))}
</ul>
) : null}
</div>
);
}
function GalleryArrow({
side,
disabled,
label,
onClick,
}: {
side: 'left' | 'right';
disabled: boolean;
label: string;
onClick: () => void;
}) {
const Icon = side === 'left' ? ChevronLeft : ChevronRight;
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
className={cn(
'text-ink-950 focus-visible:ring-ring/50 absolute top-1/2 z-10 grid size-10 -translate-y-1/2 place-items-center bg-white/90 shadow-sm outline-none transition-opacity focus-visible:opacity-100 focus-visible:ring-[3px]',
// Hidden until hover on pointer devices — on touch the swipe is the
// affordance and a pair of floating arrows just covers the photograph.
'opacity-0 group-hover:opacity-100 max-lg:hidden',
'disabled:pointer-events-none disabled:opacity-0',
side === 'left' ? 'left-3' : 'right-3',
)}
>
<Icon className="size-5" />
</button>
);
}
@@ -0,0 +1,118 @@
import { getTranslations } from 'next-intl/server';
import type { ProductListQuery } from '@sport/api-client';
import type { Locale } from '@sport/types';
import { fetchProducts } from '@/lib/catalog';
import { buildListingHref } from '@/lib/listing-href';
import { FilterSheet } from './filter-sheet';
import { LoadMore } from './load-more';
import { ProductFilters } from './product-filters';
import { ProductGrid } from './product-grid';
import { SortMenu } from './sort-menu';
/**
* One listing component behind /men, /women, /sports/*, /collections/* and
* /search.
*
* They are the same query with different presets, so they are the same
* component. Five near-identical page implementations is how filter behaviour
* starts drifting between routes.
*/
export async function ProductListing({
locale,
title,
eyebrow,
description,
query,
basePath,
}: {
locale: Locale;
title: string;
eyebrow?: string;
description?: string | null;
query: ProductListQuery;
basePath: string;
}) {
const t = await getTranslations('listing');
const result = await fetchProducts(locale, query);
// Drives the count badge on the mobile trigger, so the shopper can see a
// filter is active without opening the sheet to look for it.
const activeFilterCount =
(query.colors?.length ?? 0) +
(query.sizes?.length ?? 0) +
(query.brandSlugs?.length ?? 0) +
(query.onSale ? 1 : 0);
return (
<div className="max-w-page px-gutter mx-auto py-12">
<header className="mb-10">
{eyebrow ? (
<p className="text-ink-400 text-xs font-semibold uppercase tracking-widest">{eyebrow}</p>
) : null}
<h1 className="mt-2 text-4xl font-black uppercase sm:text-5xl">{title}</h1>
{description ? <p className="text-ink-500 mt-4 max-w-2xl text-sm">{description}</p> : null}
</header>
{/*
The count and the sort control share a row above the grid rather than
sitting in the header, so on mobile they land next to the filter trigger
instead of pushing the products another screen down.
*/}
<div className="border-ink-200 mb-6 flex items-center justify-between gap-4 border-b pb-4">
<p className="text-ink-400 text-xs uppercase tracking-widest">
{t('resultsCount', { count: result.totalCount })}
</p>
<SortMenu basePath={basePath} query={query} />
</div>
<div className="grid gap-6 lg:grid-cols-[16rem_1fr] lg:gap-10">
{/*
The same rail, mounted twice and shown at one breakpoint each. It is a
Server Component either way — `FilterSheet` only owns open/closed
state, so nothing about filtering moves to the browser.
*/}
<FilterSheet activeCount={activeFilterCount}>
<ProductFilters
facets={result.facets}
basePath={basePath}
query={query}
showHeading={false}
/>
</FilterSheet>
<div className="hidden lg:block">
<ProductFilters facets={result.facets} basePath={basePath} query={query} />
</div>
<div>
<ProductGrid products={result.items} />
{result.pageInfo.hasNextPage && result.pageInfo.nextCursor ? (
<LoadMore
/*
* Keyed on the listing identity so a sort or filter change
* remounts it.
*
* Changing the sort is a soft navigation: the server re-renders
* page 1 in the new order, but this component keeps its position
* in the React tree and therefore keeps the products it appended
* under the *old* query. The result was duplicates — the same
* product visible twice, once in each ordering.
*/
key={buildListingHref(basePath, query)}
locale={locale}
query={query}
basePath={basePath}
initialCursor={result.pageInfo.nextCursor}
initialCount={result.items.length}
totalCount={result.totalCount}
/>
) : null}
</div>
</div>
</div>
);
}
@@ -0,0 +1,119 @@
import { Search, ShoppingBag, User } from 'lucide-react';
import { getTranslations } from 'next-intl/server';
import type { NavigationMenu } from '@sport/types';
import { LanguageSwitcher } from '@/components/language-switcher';
import { Link } from '@/i18n/navigation';
import { SPORT_NAV, routes } from '@/lib/routes';
import { MegaMenu, type MegaMenuEntry } from './mega-menu';
import { MobileNav } from './mobile-nav';
/**
* Site chrome. Stays a Server Component: only the mega menu, the mobile drawer
* and the language switcher are interactive, and each is mounted as its own
* small Client Component rather than turning the whole header into one.
*
* `navigation` comes from the API (categories and collections are database
* content, translated in the database). Sports come from the local message
* catalog, because they are a fixed enum in code. That split is deliberate and
* is documented in CategoriesService.getNavigation.
*/
export async function SiteHeader({ navigation }: { navigation: NavigationMenu | null }) {
const t = await getTranslations('nav');
const tSports = await getTranslations('sports');
const sportLinks = SPORT_NAV.map((sport) => ({
label: tSports(sport.slug),
href: routes.sport(sport.slug),
}));
/**
* Each top-level entry from the API gets its children as panel columns.
* Sports are appended as one entry of their own because they are a facet, not
* a category tree.
*/
const entries: MegaMenuEntry[] = [
...(navigation?.primary ?? []).map((item) => ({
id: item.id,
label: item.label,
href: item.href,
columns:
item.children && item.children.length > 0
? [
{
heading: item.label,
links: item.children.map((child) => ({ label: child.label, href: child.href })),
},
]
: [],
})),
{
id: 'sports',
label: t('sports'),
href: routes.sport(SPORT_NAV[0].slug),
columns: [{ heading: t('sports'), links: sportLinks }],
},
];
return (
<header className="border-ink-200 sticky top-0 z-50 border-b bg-white/95 backdrop-blur">
<div className="max-w-page px-gutter mx-auto flex h-16 items-center gap-4">
<MobileNav entries={entries} />
<Link
href={routes.home()}
className="focus-visible:ring-ring/50 text-lg font-black uppercase tracking-tighter outline-none focus-visible:ring-[3px]"
>
Sport<span className="text-volt-600">.</span>
</Link>
<nav aria-label={t('ariaMain')} className="hidden lg:flex">
<MegaMenu entries={entries} />
</nav>
<div className="ml-auto flex items-center gap-1">
<LanguageSwitcher />
<HeaderAction href={routes.search()} label={t('search')}>
<Search className="size-5" />
</HeaderAction>
<HeaderAction href={routes.account()} label={t('account')} className="hidden sm:grid">
<User className="size-5" />
</HeaderAction>
<HeaderAction href={routes.cart()} label={t('cart')}>
<ShoppingBag className="size-5" />
</HeaderAction>
</div>
</div>
</header>
);
}
/**
* Icon-only, so the label moves to `aria-label` and a tooltip — the row has to
* survive a 360px viewport alongside the logo and the language switcher.
*/
function HeaderAction({
href,
label,
className,
children,
}: {
href: string;
label: string;
className?: string;
children: React.ReactNode;
}) {
return (
<Link
href={href}
aria-label={label}
title={label}
className={`hover:text-volt-600 focus-visible:ring-ring/50 grid size-10 place-items-center outline-none transition-colors focus-visible:ring-[3px] ${className ?? ''}`}
>
{children}
</Link>
);
}
@@ -0,0 +1,63 @@
'use client';
import { Check, ChevronDown } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { ProductListQuery } from '@sport/api-client';
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@sport/ui';
import { Link } from '@/i18n/navigation';
import { PRODUCT_SORTS, buildListingHref } from '@/lib/listing-href';
/**
* Sort order, as a menu of links.
*
* Every item is a real `<a href>` to the same listing with `?sort=` set, which
* keeps sorting shareable, bookmarkable and back-button-correct — the same
* contract the filter rail already honours. The menu is a Client Component only
* because a dropdown needs open/closed state; the navigation itself is ordinary
* and works without the menu ever opening.
*
* Selecting a sort drops the cursor, because a position in one ordering means
* nothing in another.
*/
export function SortMenu({ basePath, query }: { basePath: string; query: ProductListQuery }) {
const t = useTranslations('listing');
const active = query.sort ?? 'newest';
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<span className="text-ink-400 hidden font-normal normal-case sm:inline">
{t('sortBy')}
</span>
{t(`sort.${active}`)}
<ChevronDown />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-52">
{PRODUCT_SORTS.map((sort) => (
<DropdownMenuItem key={sort} asChild>
<Link
href={buildListingHref(basePath, { ...query, sort })}
className="flex items-center justify-between gap-4"
>
{t(`sort.${sort}`)}
{/* Rendered but transparent when inactive, so the label position
does not shift as the selection moves down the list. */}
<Check className={sort === active ? 'opacity-100' : 'opacity-0'} />
</Link>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -1,68 +0,0 @@
import { getTranslations } from 'next-intl/server';
import type { NavigationMenu } from '@sport/types';
import { LanguageSwitcher } from '@/components/language-switcher';
import { Link } from '@/i18n/navigation';
import { SPORT_NAV, routes } from '@/lib/routes';
/**
* Server Component. It renders no interactive state beyond the language
* switcher, so almost nothing ships to the browser — the mobile menu and cart
* badge will be small Client Components mounted inside it rather than turning
* the whole header into one.
*
* `navigation` comes from the API (categories and collections are database
* content, translated in the database). Sports come from the local message
* catalog, because they are a fixed enum in code. That split is deliberate and
* is documented in CategoriesService.getNavigation.
*/
export async function SiteHeader({ navigation }: { navigation: NavigationMenu | null }) {
const t = await getTranslations('nav');
const tSports = await getTranslations('sports');
return (
<header className="border-ink-200 sticky top-0 z-50 border-b bg-white/95 backdrop-blur">
<div className="max-w-page px-gutter mx-auto flex h-16 items-center gap-6">
<Link href={routes.home()} className="text-lg font-black uppercase tracking-tighter">
Sport<span className="text-volt-600">.</span>
</Link>
<nav aria-label={t('ariaMain')} className="hidden items-center gap-5 lg:flex">
{navigation?.primary.map((item) => (
<Link
key={item.id}
href={item.href}
className="hover:text-volt-600 text-xs font-semibold uppercase tracking-widest"
>
{item.label}
</Link>
))}
{SPORT_NAV.map((sport) => (
<Link
key={sport.slug}
href={routes.sport(sport.slug)}
className="hover:text-volt-600 text-xs font-semibold uppercase tracking-widest"
>
{tSports(sport.slug)}
</Link>
))}
</nav>
<div className="ml-auto flex items-center gap-4 text-xs font-semibold uppercase tracking-widest">
<LanguageSwitcher />
<Link href={routes.search()} className="hover:text-volt-600">
{t('search')}
</Link>
<Link href={routes.account()} className="hover:text-volt-600 hidden sm:inline">
{t('account')}
</Link>
<Link href={routes.cart()} className="hover:text-volt-600">
{t('cart')}
</Link>
</div>
</div>
</header>
);
}
@@ -1,24 +0,0 @@
# feature: account
Profile, addresses and account settings.
## Structure
```
account/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: auth
Sign in, register, password reset, and the session store the rest of the app reads.
## Structure
```
auth/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: cart
Bag drawer and page, line-item mutations, optimistic quantity updates.
## Structure
```
cart/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: category
Category landing pages, breadcrumbs and the facet sidebar.
## Structure
```
category/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: checkout
Multi-step checkout: address, delivery, payment, review.
## Structure
```
checkout/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: collection
Campaign and editorial collection pages.
## Structure
```
collection/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: order
Order confirmation and order history views.
## Structure
```
order/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: product
PDP: gallery, variant selector, price display, add-to-bag. Owns `<ProductCard>`.
## Structure
```
product/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,121 +0,0 @@
import Image from 'next/image';
import { useFormatter, useTranslations } from 'next-intl';
import type { ProductListItem } from '@sport/types';
import { Badge, cn } from '@sport/ui';
import { Link } from '@/i18n/navigation';
import { formatMoney, discountPercent } from '@/lib/format';
import { routes } from '@/lib/routes';
/**
* The grid card.
*
* Lives in `features/product/` rather than `@sport/ui` on purpose: it knows
* about sale badges, price ranges and colourways, none of which mean anything
* in the admin dashboard. See docs/architecture.md §4.
*/
export function ProductCard({
product,
priority = false,
}: {
product: ProductListItem;
priority?: boolean;
}) {
const t = useTranslations('product');
const format = useFormatter();
const { priceRange, primaryImage, hoverImage } = product;
const hasRange = priceRange.min.amount !== priceRange.max.amount;
const discount =
priceRange.compareAtMax && product.isOnSale
? discountPercent(priceRange.min, priceRange.compareAtMax)
: 0;
return (
<article className="group">
<Link href={routes.product(product.slug)} className="block">
<div className="bg-ink-100 relative aspect-[4/5] overflow-hidden">
{primaryImage ? (
<>
<Image
src={primaryImage.url}
alt={primaryImage.altText ?? product.name}
fill
// Three columns on desktop, two on tablet, one on mobile —
// matching the grid below so the browser never downloads a
// larger file than it renders.
sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
className={cn(
'object-cover transition-opacity duration-500',
hoverImage && 'group-hover:opacity-0',
)}
placeholder={primaryImage.blurDataUrl ? 'blur' : 'empty'}
blurDataURL={primaryImage.blurDataUrl ?? undefined}
// Only the first row is priority; marking everything priority
// is the same as marking nothing.
priority={priority}
/>
{hoverImage ? (
<Image
src={hoverImage.url}
alt=""
aria-hidden
fill
sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
className="object-cover opacity-0 transition-opacity duration-500 group-hover:opacity-100"
/>
) : null}
</>
) : (
<div className="bg-ink-200 size-full" />
)}
{discount > 0 ? (
<Badge variant="sale" className="absolute left-3 top-3">
{t('save', { percent: discount })}
</Badge>
) : null}
</div>
<div className="mt-3 space-y-1">
{product.brandName ? (
<p className="text-ink-400 text-[0.625rem] font-semibold uppercase tracking-widest">
{product.brandName}
</p>
) : null}
<h3 className="text-ink-950 text-sm font-medium">{product.name}</h3>
<p className="flex items-baseline gap-2 text-sm">
<span className={cn('font-semibold', product.isOnSale && 'text-sale')}>
{hasRange ? `${t('from')} ` : ''}
{formatMoney(priceRange.min, format)}
</span>
{priceRange.compareAtMax && product.isOnSale ? (
<span className="text-ink-400 text-xs line-through">
{formatMoney(priceRange.compareAtMax, format)}
</span>
) : null}
</p>
</div>
</Link>
{product.colorSwatches.length > 1 ? (
<ul className="mt-2 flex items-center gap-1.5" aria-label={t('selectColour')}>
{product.colorSwatches.slice(0, 5).map((swatch) => (
<li
key={swatch.optionValueId}
className="border-ink-200 size-3 rounded-full border"
style={{ backgroundColor: swatch.swatchHex ?? undefined }}
title={swatch.label}
/>
))}
{product.colorSwatches.length > 5 ? (
<li className="text-ink-400 text-[0.625rem]">+{product.colorSwatches.length - 5}</li>
) : null}
</ul>
) : null}
</article>
);
}
@@ -1,56 +0,0 @@
import { getTranslations } from 'next-intl/server';
import type { ProductListQuery } from '@sport/api-client';
import type { Locale } from '@sport/types';
import { fetchProducts } from '@/features/product/services/catalog';
import { ProductFilters } from './product-filters';
import { ProductGrid } from './product-grid';
/**
* One listing component behind /men, /women, /sports/*, /collections/* and
* /search.
*
* They are the same query with different presets, so they are the same
* component. Five near-identical page implementations is how filter behaviour
* starts drifting between routes.
*/
export async function ProductListing({
locale,
title,
eyebrow,
description,
query,
basePath,
}: {
locale: Locale;
title: string;
eyebrow?: string;
description?: string | null;
query: ProductListQuery;
basePath: string;
}) {
const t = await getTranslations('listing');
const result = await fetchProducts(locale, query);
return (
<div className="max-w-page px-gutter mx-auto py-12">
<header className="mb-10">
{eyebrow ? (
<p className="text-ink-400 text-xs font-semibold uppercase tracking-widest">{eyebrow}</p>
) : null}
<h1 className="mt-2 text-4xl font-black uppercase sm:text-5xl">{title}</h1>
{description ? <p className="text-ink-500 mt-4 max-w-2xl text-sm">{description}</p> : null}
<p className="text-ink-400 mt-4 text-xs uppercase tracking-widest">
{t('resultsCount', { count: result.totalCount })}
</p>
</header>
<div className="grid gap-10 lg:grid-cols-[16rem_1fr]">
<ProductFilters facets={result.facets} basePath={basePath} query={query} />
<ProductGrid products={result.items} />
</div>
</div>
);
}
@@ -1,24 +0,0 @@
# feature: search
Search input, suggestions, results and the shared filter state.
## Structure
```
search/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
@@ -1,24 +0,0 @@
# feature: wishlist
Save-for-later toggles and the wishlist page.
## Structure
```
wishlist/
├── components/ # UI specific to this feature
├── hooks/ # React hooks (client-side only)
├── services/ # Calls into @sport/api-client, plus query keys
├── stores/ # Zustand slices, only if this feature owns client state
└── types.ts # View-model types. Domain types come from @sport/types.
```
## Rules
- A feature may import from `@/components`, `@/lib`, `@/hooks` and any
`@sport/*` package.
- A feature must **not** import from another feature's internals. If two
features need the same thing, it moves up to `@/components` or `@/lib`.
Cross-feature imports are what turn a feature folder into a second, worse
module system.
- Data fetching goes through `@sport/api-client`. No raw `fetch` to the API.
+47
View File
@@ -0,0 +1,47 @@
import type { ProductListQuery } from '@sport/api-client';
/**
* Serialises a listing query back into a URL.
*
* Shared by the filter rail, the sort menu and the "load more" link so the
* three cannot disagree about what a listing URL looks like. They used to build
* hrefs independently, which is how sorting silently drops the filters you had
* applied.
*
* Only presentation-level filters are emitted — `gender`, `sport`,
* `categorySlug` and `collectionSlug` are implied by the route itself, so
* repeating them in the query string would produce ugly, duplicate-content URLs
* like `/men?gender=MEN`.
*
* `cursor` is deliberately opt-in. Changing a filter or the sort order
* invalidates any position in the result set, so those callers omit it and the
* listing restarts from the first page.
*/
export function buildListingHref(
basePath: string,
query: ProductListQuery,
extra?: { cursor?: string | null },
): string {
const params = new URLSearchParams();
if (query.q) params.set('q', query.q);
if (query.colors?.length) params.set('colors', query.colors.join(','));
if (query.sizes?.length) params.set('sizes', query.sizes.join(','));
if (query.brandSlugs?.length) params.set('brandSlugs', query.brandSlugs.join(','));
if (query.onSale) params.set('onSale', 'true');
if (query.sort && query.sort !== 'newest') params.set('sort', query.sort);
if (extra?.cursor) params.set('cursor', extra.cursor);
const search = params.toString();
return search ? `${basePath}?${search}` : basePath;
}
export const PRODUCT_SORTS = [
'newest',
'price_asc',
'price_desc',
'best_selling',
'relevance',
] as const;
export type ProductSort = (typeof PRODUCT_SORTS)[number];
+4
View File
@@ -21,6 +21,10 @@ export function parseListingParams(params: RawSearchParams): ProductListQuery {
categorySlug: single(params['category']),
onSale: single(params['onSale']) === 'true' ? true : undefined,
sort: parseSort(single(params['sort'])),
// Present only when someone followed the "load more" link without
// JavaScript, or a crawler did. The client path appends in place and never
// puts a cursor in the address bar.
cursor: single(params['cursor']),
};
}
+7 -2
View File
@@ -58,7 +58,9 @@
"price": "Price",
"onSale": "On sale only",
"inStock": "In stock only"
}
},
"showing": "Showing {shown} of {total}",
"loadFailed": "Could not load more products."
},
"product": {
"selectColour": "Colour",
@@ -77,7 +79,10 @@
"new": "New",
"from": "From",
"notAvailable": "This combination is not available",
"comingSoon": "Add to bag arrives with the cart milestone."
"comingSoon": "Add to bag arrives with the cart milestone.",
"previousImage": "Previous image",
"nextImage": "Next image",
"goToImage": "Go to image {index}"
},
"search": {
"title": "Search",
+7 -2
View File
@@ -58,7 +58,9 @@
"price": "Giá",
"onSale": "Chỉ hàng giảm giá",
"inStock": "Chỉ hàng còn sẵn"
}
},
"showing": "Đang xem {shown} trên {total}",
"loadFailed": "Không tải thêm được sản phẩm."
},
"product": {
"selectColour": "Màu sắc",
@@ -77,7 +79,10 @@
"new": "Mới",
"from": "Từ",
"notAvailable": "Phiên bản này không có sẵn",
"comingSoon": "Chức năng thêm vào giỏ sẽ có ở giai đoạn giỏ hàng."
"comingSoon": "Chức năng thêm vào giỏ sẽ có ở giai đoạn giỏ hàng.",
"previousImage": "Ảnh trước",
"nextImage": "Ảnh sau",
"goToImage": "Xem ảnh {index}"
},
"search": {
"title": "Tìm kiếm",
+4
View File
@@ -1,5 +1,9 @@
@import 'tailwindcss';
@import '@sport/config/tailwind/theme.css';
/* Supplies the enter/exit utilities Radix-driven overlays animate with
(`animate-in`, `fade-in-0`, `slide-in-from-right`). Registry components
assume these exist; without it Dialog and Sheet appear instantly. */
@import 'tw-animate-css';
/* Tailwind v4 scans the importing app by default; workspace packages must be
registered explicitly or their utility classes get purged. */