Skip to content

Commit 1bc7aa7

Browse files
committed
Add admin portal for sets, photos and themes; product photo gallery
- /admin area (lazy-loaded) for staff and admins: set list with search, theme and low-stock filters; add/edit/delete sets; theme management - Photo manager: upload multiple images to the lego-images bucket, reorder, choose the main photo, delete - Product page shows a thumbnail gallery when a set has several photos - Header shows an Admin link to staff/admins - Migration hardening decrement_stock and rls_auto_enable (applied) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WL7zH8QfKYa4QvuVnnWmVs
1 parent dd7b529 commit 1bc7aa7

10 files changed

Lines changed: 1064 additions & 5 deletions

File tree

‎src/App.jsx‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import "./App.css";
22
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
3-
import { useEffect, useState } from "react";
3+
import { lazy, Suspense, useEffect, useState } from "react";
44
import { supabase } from "./supabase/supabaseClient"; // adjust path if needed
55
import MainLayout from "./layout/mainlayout.jsx";
66
import Signup from "./pages/signup.jsx";
@@ -16,16 +16,24 @@ import Terms from "./pages/terms.jsx";
1616
import Privacy from "./pages/privacy.jsx";
1717
import OrderSuccess from "./pages/orderSuccess.jsx";
1818
import OrderCancelled from "./pages/orderCancelled.jsx";
19+
import Spinner from "./components/Spinner.jsx";
1920
import Aos from "aos";
2021
import "aos/dist/aos.css";
2122

23+
// The admin area is loaded only when someone opens /admin, so regular
24+
// customers never download its code.
25+
const AdminApp = lazy(() => import("./admin/AdminApp.jsx"));
26+
2227
// App is the root component. It owns the logged-in `user` state and decides
2328
// which page component to render based on the current URL (routing).
2429
function App() {
2530
// `user` is shared across the whole site: the header uses it to show
2631
// Login/Logout, and the cart page uses it to know whose cart to load.
2732
// It starts as null (not logged in) until we check for a session below.
2833
const [user, setUser] = useState(null);
34+
// False until we've checked for a saved session - the admin area waits
35+
// for this so it doesn't bounce a logged-in admin to /login on refresh.
36+
const [authReady, setAuthReady] = useState(false);
2937

3038
// Total number of items (summed quantity, not distinct lines) in the
3139
// logged-in user's cart. Lives up here so the header badge can show it
@@ -67,6 +75,7 @@ function App() {
6775
const { data } = await supabase.auth.getSession();
6876
const sessionUser = data.session?.user ?? null;
6977
setUser(sessionUser);
78+
setAuthReady(true);
7079
refreshCartCount(sessionUser);
7180
}
7281
loadSession();
@@ -118,6 +127,20 @@ function App() {
118127
<Route path="/privacy" element={<Privacy />} />
119128
<Route path="/order-success" element={<OrderSuccess />} />
120129
<Route path="/order-cancelled" element={<OrderCancelled />} />
130+
<Route
131+
path="/admin/*"
132+
element={
133+
<Suspense
134+
fallback={
135+
<div className="min-h-[60vh] flex items-center justify-center">
136+
<Spinner />
137+
</div>
138+
}
139+
>
140+
<AdminApp user={user} authReady={authReady} />
141+
</Suspense>
142+
}
143+
/>
121144
</Routes>
122145
</MainLayout>
123146
</Router>

‎src/admin/AdminApp.jsx‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { NavLink, Route, Routes, Navigate } from "react-router-dom";
2+
import useRole from "./useRole";
3+
import Spinner from "../components/Spinner";
4+
import BrickButton from "../components/BrickButton";
5+
import SetsList from "./pages/SetsList";
6+
import SetEdit from "./pages/SetEdit";
7+
import Themes from "./pages/Themes";
8+
9+
// Entry point for everything under /admin. App.jsx lazy-loads this file,
10+
// so customers never download the admin code.
11+
//
12+
// `user` comes from App.jsx. `authReady` is false until App.jsx has
13+
// checked for a saved session - without it we'd briefly think nobody is
14+
// logged in and bounce the admin to the login page on every refresh.
15+
export default function AdminApp({ user, authReady }) {
16+
const { isStaff, isAdmin, loading } = useRole(user);
17+
18+
if (!authReady || loading) {
19+
return (
20+
<div className="min-h-[60vh] flex items-center justify-center">
21+
<Spinner />
22+
</div>
23+
);
24+
}
25+
26+
if (!user) return <Navigate to="/login" replace />;
27+
28+
if (!isStaff) {
29+
return (
30+
<div className="min-h-[60vh] flex flex-col items-center justify-center gap-4 px-4 text-center">
31+
<h1 className="text-2xl font-bold text-gray-800">No access</h1>
32+
<p className="text-gray-600">
33+
This area is only for TC PlayBricks staff.
34+
</p>
35+
<BrickButton to="/">Back to the shop</BrickButton>
36+
</div>
37+
);
38+
}
39+
40+
const tab = ({ isActive }) =>
41+
`px-4 py-2 rounded-md font-semibold text-sm transition ${
42+
isActive ? "bg-red-600 text-white" : "bg-white text-gray-800 hover:bg-gray-100"
43+
}`;
44+
45+
return (
46+
<div className="container mx-auto px-4 py-6">
47+
<div className="flex flex-wrap items-center justify-between gap-3 mb-6">
48+
<h1 className="text-2xl font-bold text-gray-800">
49+
Admin{" "}
50+
<span className="text-sm font-normal text-gray-500">
51+
({isAdmin ? "admin" : "staff"})
52+
</span>
53+
</h1>
54+
<nav className="flex flex-wrap gap-2">
55+
<NavLink to="/admin/sets" className={tab}>
56+
Sets
57+
</NavLink>
58+
<NavLink to="/admin/themes" className={tab}>
59+
Themes
60+
</NavLink>
61+
</nav>
62+
</div>
63+
64+
<Routes>
65+
<Route index element={<Navigate to="sets" replace />} />
66+
<Route path="sets" element={<SetsList />} />
67+
<Route path="sets/new" element={<SetEdit />} />
68+
<Route path="sets/:setId" element={<SetEdit />} />
69+
<Route path="themes" element={<Themes />} />
70+
<Route path="*" element={<Navigate to="sets" replace />} />
71+
</Routes>
72+
</div>
73+
);
74+
}
Lines changed: 260 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,260 @@
1+
import { useCallback, useEffect, useState } from "react";
2+
import {
3+
ArrowLeftIcon,
4+
ArrowRightIcon,
5+
StarIcon,
6+
TrashIcon,
7+
} from "@heroicons/react/24/outline";
8+
import { StarIcon as StarSolid } from "@heroicons/react/24/solid";
9+
import { supabase } from "../../supabase/supabaseClient";
10+
import Spinner from "../../components/Spinner";
11+
12+
const BUCKET = "lego-images";
13+
const MAX_BYTES = 5 * 1024 * 1024; // must match the bucket's 5 MB limit
14+
const ALLOWED = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp" };
15+
16+
// Upload, reorder, delete and choose the main photo for one set.
17+
// The main photo is automatically copied to lego_sets.image_url by a
18+
// database trigger, so shop listings and the cart always show it.
19+
export default function ImageManager({ setId }) {
20+
const [images, setImages] = useState(null);
21+
const [busy, setBusy] = useState(false);
22+
const [error, setError] = useState(null);
23+
24+
// Fetches this set's photos in their saved order.
25+
const fetchImages = useCallback(
26+
() =>
27+
supabase
28+
.from("set_images")
29+
.select("*")
30+
.eq("set_id", setId)
31+
.order("sort_order")
32+
.order("image_id"),
33+
[setId],
34+
);
35+
36+
async function load() {
37+
const { data, error } = await fetchImages();
38+
if (error) setError(error.message);
39+
else setImages(data);
40+
}
41+
42+
useEffect(() => {
43+
let cancelled = false;
44+
fetchImages().then(({ data, error }) => {
45+
if (cancelled) return;
46+
if (error) setError(error.message);
47+
else setImages(data);
48+
});
49+
return () => {
50+
cancelled = true;
51+
};
52+
}, [fetchImages]);
53+
54+
// Wraps each action: shows a spinner, reports errors, reloads afterwards.
55+
async function run(action) {
56+
setBusy(true);
57+
setError(null);
58+
try {
59+
await action();
60+
} catch (err) {
61+
setError(err.message ?? String(err));
62+
}
63+
await load();
64+
setBusy(false);
65+
}
66+
67+
function handleUpload(e) {
68+
const files = Array.from(e.target.files ?? []);
69+
e.target.value = ""; // allow picking the same file again later
70+
if (files.length === 0) return;
71+
72+
const bad = files.find((f) => !ALLOWED[f.type] || f.size > MAX_BYTES);
73+
if (bad) {
74+
setError(`"${bad.name}" must be a JPG, PNG or WebP image under 5 MB.`);
75+
return;
76+
}
77+
78+
run(async () => {
79+
let nextOrder = images.reduce((m, i) => Math.max(m, i.sort_order), -1) + 1;
80+
let needsPrimary = !images.some((i) => i.is_primary);
81+
82+
for (const file of files) {
83+
const path = `sets/${setId}/${crypto.randomUUID()}.${ALLOWED[file.type]}`;
84+
const { error: upErr } = await supabase.storage
85+
.from(BUCKET)
86+
.upload(path, file, { contentType: file.type, cacheControl: "31536000" });
87+
if (upErr) throw upErr;
88+
89+
const { data: pub } = supabase.storage.from(BUCKET).getPublicUrl(path);
90+
const { error: dbErr } = await supabase.from("set_images").insert({
91+
set_id: setId,
92+
url: pub.publicUrl,
93+
storage_path: path,
94+
sort_order: nextOrder++,
95+
is_primary: needsPrimary,
96+
});
97+
if (dbErr) {
98+
// Don't leave an orphaned file behind.
99+
await supabase.storage.from(BUCKET).remove([path]);
100+
throw dbErr;
101+
}
102+
needsPrimary = false;
103+
}
104+
});
105+
}
106+
107+
function makeMain(image) {
108+
run(async () => {
109+
// Only one main photo per set is allowed, so clear the old one first.
110+
const { error: clearErr } = await supabase
111+
.from("set_images")
112+
.update({ is_primary: false })
113+
.eq("set_id", setId)
114+
.eq("is_primary", true);
115+
if (clearErr) throw clearErr;
116+
const { error } = await supabase
117+
.from("set_images")
118+
.update({ is_primary: true })
119+
.eq("image_id", image.image_id);
120+
if (error) throw error;
121+
});
122+
}
123+
124+
// Swap a photo with its neighbour (-1 = left, +1 = right).
125+
function move(index, direction) {
126+
const other = images[index + direction];
127+
const image = images[index];
128+
if (!other) return;
129+
run(async () => {
130+
// Renumber everything in the new order so ties can't happen.
131+
const order = [...images];
132+
order[index] = other;
133+
order[index + direction] = image;
134+
for (let i = 0; i < order.length; i++) {
135+
if (order[i].sort_order !== i) {
136+
const { error } = await supabase
137+
.from("set_images")
138+
.update({ sort_order: i })
139+
.eq("image_id", order[i].image_id);
140+
if (error) throw error;
141+
}
142+
}
143+
});
144+
}
145+
146+
function remove(image) {
147+
if (!window.confirm("Delete this photo?")) return;
148+
run(async () => {
149+
const { error } = await supabase
150+
.from("set_images")
151+
.delete()
152+
.eq("image_id", image.image_id);
153+
if (error) throw error;
154+
155+
// Older photos can be shared between sets (e.g. one theme picture),
156+
// so only delete the file if nothing else still uses it.
157+
if (image.storage_path) {
158+
const { count } = await supabase
159+
.from("set_images")
160+
.select("image_id", { count: "exact", head: true })
161+
.eq("storage_path", image.storage_path);
162+
if (count === 0) {
163+
await supabase.storage.from(BUCKET).remove([image.storage_path]);
164+
}
165+
}
166+
167+
// If the main photo was deleted, promote the next one.
168+
if (image.is_primary) {
169+
const next = images.find((i) => i.image_id !== image.image_id);
170+
if (next) {
171+
await supabase.from("set_images").update({ is_primary: true }).eq("image_id", next.image_id);
172+
}
173+
}
174+
});
175+
}
176+
177+
if (!images) {
178+
return error ? <p className="text-red-600">{error}</p> : <Spinner />;
179+
}
180+
181+
return (
182+
<div>
183+
<p className="text-sm text-gray-500 mb-4">
184+
JPG, PNG or WebP, up to 5 MB each. The ★ photo is the main one shown in the shop.
185+
</p>
186+
187+
{error && <p className="mb-4 rounded-md bg-red-50 text-red-700 px-4 py-2">{error}</p>}
188+
189+
<ul className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4 mb-4">
190+
{images.map((img, index) => (
191+
<li
192+
key={img.image_id}
193+
className={`relative rounded-lg border-2 p-2 bg-gray-50 ${
194+
img.is_primary ? "border-red-500" : "border-transparent"
195+
}`}
196+
>
197+
<img src={img.url} alt="" className="w-full aspect-square object-contain" />
198+
<div className="flex justify-between items-center mt-2">
199+
<button
200+
type="button"
201+
title="Move left"
202+
disabled={busy || index === 0}
203+
onClick={() => move(index, -1)}
204+
className="p-1 rounded hover:bg-gray-200 disabled:opacity-30"
205+
>
206+
<ArrowLeftIcon className="h-5 w-5" />
207+
</button>
208+
<button
209+
type="button"
210+
title={img.is_primary ? "Main photo" : "Make main photo"}
211+
disabled={busy || img.is_primary}
212+
onClick={() => makeMain(img)}
213+
className="p-1 rounded hover:bg-gray-200"
214+
>
215+
{img.is_primary ? (
216+
<StarSolid className="h-5 w-5 text-red-500" />
217+
) : (
218+
<StarIcon className="h-5 w-5" />
219+
)}
220+
</button>
221+
<button
222+
type="button"
223+
title="Delete photo"
224+
disabled={busy}
225+
onClick={() => remove(img)}
226+
className="p-1 rounded hover:bg-red-100 text-red-600"
227+
>
228+
<TrashIcon className="h-5 w-5" />
229+
</button>
230+
<button
231+
type="button"
232+
title="Move right"
233+
disabled={busy || index === images.length - 1}
234+
onClick={() => move(index, 1)}
235+
className="p-1 rounded hover:bg-gray-200 disabled:opacity-30"
236+
>
237+
<ArrowRightIcon className="h-5 w-5" />
238+
</button>
239+
</div>
240+
</li>
241+
))}
242+
</ul>
243+
244+
<label
245+
className={`inline-flex items-center gap-2 rounded-xl px-4 py-2 font-semibold text-white bg-red-600 hover:bg-red-700 cursor-pointer ${
246+
busy ? "opacity-50 pointer-events-none" : ""
247+
}`}
248+
>
249+
{busy ? <Spinner size="h-4 w-4" /> : "+"} Add photos
250+
<input
251+
type="file"
252+
accept="image/jpeg,image/png,image/webp"
253+
multiple
254+
onChange={handleUpload}
255+
className="sr-only"
256+
/>
257+
</label>
258+
</div>
259+
);
260+
}

0 commit comments

Comments
 (0)