This commit is contained in:
CFOU
2026-09-14 20:50:19 +02:00
commit 3091fb4020
135 changed files with 10262 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+32
View File
@@ -0,0 +1,32 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1359
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.3"
},
"devDependencies": {
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"oxlint": "^1.81.0",
"typescript": "~6.0.2",
"vite": "^8.3.0"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+50
View File
@@ -0,0 +1,50 @@
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { AuthProvider } from "./features/auth/AuthContext";
import LoginPage from "./features/auth/LoginPage";
import ProtectedRoute from "./router/ProtectedRoute";
import AdminLayout from "./features/admin/AdminLayout";
import DashboardPage from "./features/admin/DashboardPage";
import SiteSettingsPage from "./features/admin/SiteSettingsPage";
import UsersPage from "./features/admin/UsersPage";
import CategoriesPage from "./features/admin/CategoriesPage";
import UnitsPage from "./features/admin/UnitsPage";
import ProductsPage from "./features/admin/ProductsPage";
import ProductEditPage from "./features/admin/ProductEditPage";
import MediaPage from "./features/admin/MediaPage";
import OrdersPage from "./features/admin/OrdersPage";
import OrderDetailPage from "./features/admin/OrderDetailPage";
import TelegramSettingsPage from "./features/admin/TelegramSettingsPage";
export default function App() {
return (
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/admin"
element={
<ProtectedRoute>
<AdminLayout />
</ProtectedRoute>
}
>
<Route index element={<DashboardPage />} />
<Route path="site-settings" element={<SiteSettingsPage />} />
<Route path="users" element={<UsersPage />} />
<Route path="categories" element={<CategoriesPage />} />
<Route path="units" element={<UnitsPage />} />
<Route path="products" element={<ProductsPage />} />
<Route path="products/:id" element={<ProductEditPage />} />
<Route path="media" element={<MediaPage />} />
<Route path="orders" element={<OrdersPage />} />
<Route path="orders/:id" element={<OrderDetailPage />} />
<Route path="notifications/telegram" element={<TelegramSettingsPage />} />
</Route>
<Route path="/" element={<Navigate to="/admin" replace />} />
<Route path="*" element={<Navigate to="/admin" replace />} />
</Routes>
</AuthProvider>
</BrowserRouter>
);
}
+86
View File
@@ -0,0 +1,86 @@
// Central fetch wrapper: the access token is kept in memory only (never
// localStorage/sessionStorage, per the auth design), and a 401 triggers a
// single silent refresh-and-retry via the httpOnly refresh cookie.
let accessToken: string | null = null;
export function setAccessToken(token: string | null): void {
accessToken = token;
}
export function getAccessToken(): string | null {
return accessToken;
}
export class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
const NO_RETRY_PATHS = ["/api/auth/admin/refresh", "/api/auth/admin/login"];
async function rawFetch(path: string, init: RequestInit): Promise<Response> {
const headers = new Headers(init.headers);
if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
return fetch(path, { ...init, headers, credentials: "include" });
}
let refreshInFlight: Promise<boolean> | null = null;
async function refreshAccessToken(): Promise<boolean> {
if (!refreshInFlight) {
refreshInFlight = (async () => {
try {
const res = await fetch("/api/auth/admin/refresh", {
method: "POST",
credentials: "include",
});
if (!res.ok) return false;
const data = (await res.json()) as { access_token: string };
setAccessToken(data.access_token);
return true;
} catch {
return false;
} finally {
refreshInFlight = null;
}
})();
}
return refreshInFlight;
}
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
let res = await rawFetch(path, init);
if (res.status === 401 && !NO_RETRY_PATHS.includes(path)) {
const refreshed = await refreshAccessToken();
if (refreshed) {
res = await rawFetch(path, init);
}
}
if (!res.ok) {
let message = `Request failed with status ${res.status}`;
try {
const body = (await res.json()) as { error?: string };
if (body?.error) message = body.error;
} catch {
// response had no JSON body
}
throw new ApiError(message, res.status);
}
if (res.status === 204) {
return undefined as T;
}
return (await res.json()) as T;
}
export function apiUpload<T>(path: string, formData: FormData): Promise<T> {
return apiFetch<T>(path, { method: "POST", body: formData });
}
+20
View File
@@ -0,0 +1,20 @@
// Shared helper for admin lists that support manual reordering (categories,
// products, ...): swap the position of the item at `index` with its
// neighbor, then persist both via the given per-item PATCH call.
export async function swapPosition<T extends { id: string; position: number }>(
items: T[],
index: number,
direction: "up" | "down",
patchPosition: (id: string, position: number) => Promise<unknown>,
): Promise<void> {
const swapIndex = direction === "up" ? index - 1 : index + 1;
if (swapIndex < 0 || swapIndex >= items.length) return;
const current = items[index];
const neighbor = items[swapIndex];
await Promise.all([
patchPosition(current.id, neighbor.position),
patchPosition(neighbor.id, current.position),
]);
}
+100
View File
@@ -0,0 +1,100 @@
export interface User {
id: string;
email: string;
role: string;
is_active?: boolean;
}
export interface SiteSettings {
name: string;
description: string;
slug: string;
}
export interface Category {
id: string;
name: string;
slug: string;
description: string;
position: number;
is_active: boolean;
}
export interface Unit {
id: string;
name: string;
symbol: string;
}
export interface Media {
id: string;
filename: string;
url: string;
mime_type: string;
size_bytes: number;
alt_text: string;
}
export interface Product {
id: string;
category_id?: string | null;
name: string;
slug: string;
short_description: string;
description: string;
is_active: boolean;
is_featured: boolean;
primary_media_id?: string | null;
position: number;
}
export interface PriceTier {
id: string;
product_id: string;
unit_id: string;
quantity: number;
price_cents: number;
position: number;
}
export interface TelegramSettings {
enabled: boolean;
bot_token_configured: boolean;
chat_id: string;
notify_new_order: boolean;
notify_status_change: boolean;
}
export interface OrderItem {
product_id?: string;
product_name: string;
unit_symbol: string;
tier_quantity: number;
multiplier: number;
unit_price_cents: number;
total_cents: number;
}
export interface Order {
id: string;
customer_name: string;
customer_email: string;
customer_phone: string;
status: string;
total_cents: number;
notes: string;
items?: OrderItem[];
}
export const ORDER_STATUSES = [
"pending",
"confirmed",
"preparing",
"shipped",
"completed",
"cancelled",
] as const;
export function formatCents(cents: number): string {
return (cents / 100).toFixed(2);
}
@@ -0,0 +1,81 @@
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";
const NAV_SECTIONS: { title: string; items: { to: string; label: string }[] }[] = [
{
title: "Site",
items: [
{ to: "/admin", label: "Dashboard" },
{ to: "/admin/site-settings", label: "General" },
],
},
{
title: "Catalog",
items: [
{ to: "/admin/categories", label: "Categories" },
{ to: "/admin/units", label: "Units" },
{ to: "/admin/products", label: "Products" },
{ to: "/admin/media", label: "Media" },
],
},
{
title: "Sales",
items: [{ to: "/admin/orders", label: "Orders" }],
},
{
title: "Communication",
items: [{ to: "/admin/notifications/telegram", label: "Telegram" }],
},
{
title: "System",
items: [{ to: "/admin/users", label: "Users" }],
},
];
export default function AdminLayout() {
const { user, logout } = useAuth();
const navigate = useNavigate();
async function handleLogout() {
await logout();
navigate("/login", { replace: true });
}
return (
<div className="admin-shell">
<aside className="admin-sidebar">
<h2>Admin Panel</h2>
<nav>
{NAV_SECTIONS.map((section) => (
<div key={section.title} style={{ marginBottom: "0.75rem" }}>
<div style={{ fontSize: "0.7rem", opacity: 0.6, padding: "0 0.6rem", marginBottom: "0.2rem" }}>
{section.title.toUpperCase()}
</div>
{section.items.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.to === "/admin"}
className={({ isActive }) => (isActive ? "active" : "")}
>
{item.label}
</NavLink>
))}
</div>
))}
</nav>
</aside>
<div className="admin-main">
<header className="admin-topbar">
<span>{user?.email}</span>
<button className="btn" onClick={handleLogout}>
Log out
</button>
</header>
<main className="admin-content">
<Outlet />
</main>
</div>
</div>
);
}
@@ -0,0 +1,204 @@
import { useEffect, useState, type FormEvent } from "react";
import { apiFetch } from "../../api/client";
import { swapPosition } from "../../api/reorder";
import type { Category } from "../../api/types";
const emptyForm = { name: "", slug: "", description: "", position: 0, is_active: true };
export default function CategoriesPage() {
const [categories, setCategories] = useState<Category[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
const [form, setForm] = useState(emptyForm);
const [saving, setSaving] = useState(false);
function load() {
setLoading(true);
apiFetch<{ categories: Category[] }>("/api/admin/categories")
.then((data) => setCategories(data.categories))
.catch(() => setError("Failed to load categories."))
.finally(() => setLoading(false));
}
useEffect(load, []);
function startEdit(cat: Category) {
setEditingId(cat.id);
setForm({
name: cat.name,
slug: cat.slug,
description: cat.description,
position: cat.position,
is_active: cat.is_active,
});
}
function cancelEdit() {
setEditingId(null);
setForm(emptyForm);
}
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setSaving(true);
setError(null);
try {
if (editingId) {
await apiFetch(`/api/admin/categories/${editingId}`, { method: "PUT", body: JSON.stringify(form) });
} else {
await apiFetch("/api/admin/categories", { method: "POST", body: JSON.stringify(form) });
}
cancelEdit();
load();
} catch {
setError("Failed to save category (slug may already be in use).");
} finally {
setSaving(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Delete this category?")) return;
try {
await apiFetch(`/api/admin/categories/${id}`, { method: "DELETE" });
load();
} catch {
setError("Failed to delete category (it may still have products attached).");
}
}
async function handleMove(index: number, direction: "up" | "down") {
try {
await swapPosition(categories, index, direction, (id, position) =>
apiFetch(`/api/admin/categories/${id}/position`, {
method: "PATCH",
body: JSON.stringify({ position }),
}),
);
load();
} catch {
setError("Failed to reorder categories.");
}
}
return (
<div>
<h1>Categories</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>{editingId ? "Edit category" : "New category"}</h2>
<form onSubmit={handleSubmit}>
<div className="form-row">
<div className="field">
<label htmlFor="cat-name">Name</label>
<input id="cat-name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</div>
<div className="field">
<label htmlFor="cat-slug">Slug</label>
<input id="cat-slug" value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} required />
</div>
<div className="field">
<label htmlFor="cat-position">Position</label>
<input
id="cat-position"
type="number"
value={form.position}
onChange={(e) => setForm({ ...form, position: Number(e.target.value) })}
/>
</div>
</div>
<div className="field">
<label htmlFor="cat-description">Description</label>
<textarea
id="cat-description"
rows={2}
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
/>
</div>
<div className="field field-inline">
<input
id="cat-active"
type="checkbox"
checked={form.is_active}
onChange={(e) => setForm({ ...form, is_active: e.target.checked })}
/>
<label htmlFor="cat-active">Active</label>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? "Saving…" : editingId ? "Save changes" : "Create category"}
</button>
{editingId && (
<button type="button" className="btn" onClick={cancelEdit}>
Cancel
</button>
)}
</div>
</form>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<table>
<thead>
<tr>
<th>Name</th>
<th>Slug</th>
<th>Position</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{categories.map((cat, index) => (
<tr key={cat.id}>
<td>{cat.name}</td>
<td>{cat.slug}</td>
<td>
<div style={{ display: "flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
className="btn"
title="Move up"
disabled={index === 0}
onClick={() => handleMove(index, "up")}
>
</button>
<button
type="button"
className="btn"
title="Move down"
disabled={index === categories.length - 1}
onClick={() => handleMove(index, "down")}
>
</button>
<span>{cat.position}</span>
</div>
</td>
<td>
<span className={`badge ${cat.is_active ? "badge-active" : "badge-inactive"}`}>
{cat.is_active ? "active" : "inactive"}
</span>
</td>
<td>
<button className="btn" onClick={() => startEdit(cat)}>
Edit
</button>{" "}
<button className="btn btn-danger" onClick={() => handleDelete(cat.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
@@ -0,0 +1,16 @@
import { useAuth } from "../auth/AuthContext";
export default function DashboardPage() {
const { user } = useAuth();
return (
<div>
<h1>Dashboard</h1>
<div className="panel">
<p>
Signed in as <strong>{user?.email}</strong> ({user?.role}).
</p>
<p>Use the sidebar to configure the site: identity, catalog, orders and notifications.</p>
</div>
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useRef, useState, type FormEvent } from "react";
import { apiFetch, apiUpload } from "../../api/client";
import type { Media } from "../../api/types";
export default function MediaPage() {
const [media, setMedia] = useState<Media[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [altText, setAltText] = useState("");
const fileInputRef = useRef<HTMLInputElement>(null);
function load() {
setLoading(true);
apiFetch<{ media: Media[] }>("/api/admin/media")
.then((data) => setMedia(data.media))
.catch(() => setError("Failed to load media."))
.finally(() => setLoading(false));
}
useEffect(load, []);
async function handleUpload(e: FormEvent) {
e.preventDefault();
const file = fileInputRef.current?.files?.[0];
if (!file) return;
setUploading(true);
setError(null);
try {
const formData = new FormData();
formData.append("file", file);
formData.append("alt_text", altText);
await apiUpload("/api/admin/media", formData);
setAltText("");
if (fileInputRef.current) fileInputRef.current.value = "";
load();
} catch {
setError("Upload failed (check file type/size).");
} finally {
setUploading(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Delete this media file?")) return;
try {
await apiFetch(`/api/admin/media/${id}`, { method: "DELETE" });
load();
} catch {
setError("Failed to delete media.");
}
}
return (
<div>
<h1>Media</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>Upload</h2>
<form onSubmit={handleUpload}>
<div className="field">
<label htmlFor="file">File (image or video)</label>
<input id="file" type="file" ref={fileInputRef} accept="image/*,video/mp4,video/webm" required />
</div>
<div className="field">
<label htmlFor="alt-text">Alt text</label>
<input id="alt-text" value={altText} onChange={(e) => setAltText(e.target.value)} />
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={uploading}>
{uploading ? "Uploading…" : "Upload"}
</button>
</div>
</form>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: "1rem" }}>
{media.map((m) => (
<div key={m.id} className="panel" style={{ padding: "0.75rem", marginBottom: 0 }}>
{m.mime_type.startsWith("image/") ? (
<img src={m.url} alt={m.alt_text} style={{ width: "100%", height: 100, objectFit: "cover", borderRadius: 4 }} />
) : (
<div style={{ height: 100, display: "flex", alignItems: "center", justifyContent: "center", background: "#f3f4f6" }}>
{m.mime_type}
</div>
)}
<p style={{ fontSize: "0.75rem", margin: "0.4rem 0", wordBreak: "break-all" }}>{m.filename}</p>
<button className="btn btn-danger" style={{ width: "100%" }} onClick={() => handleDelete(m.id)}>
Delete
</button>
</div>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,102 @@
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { formatCents, ORDER_STATUSES, type Order } from "../../api/types";
export default function OrderDetailPage() {
const { id } = useParams<{ id: string }>();
const [order, setOrder] = useState<Order | null>(null);
const [loading, setLoading] = useState(true);
const [updating, setUpdating] = useState(false);
const [error, setError] = useState<string | null>(null);
function load() {
setLoading(true);
apiFetch<Order>(`/api/admin/orders/${id}`)
.then(setOrder)
.catch(() => setError("Failed to load order."))
.finally(() => setLoading(false));
}
useEffect(load, [id]);
async function handleStatusChange(newStatus: string) {
setUpdating(true);
setError(null);
try {
const updated = await apiFetch<Order>(`/api/admin/orders/${id}/status`, {
method: "PATCH",
body: JSON.stringify({ status: newStatus }),
});
setOrder((prev) => (prev ? { ...prev, status: updated.status } : updated));
} catch {
setError("Failed to update order status.");
} finally {
setUpdating(false);
}
}
if (loading) return <div className="page-loading">Loading</div>;
if (!order) return <div className="alert alert-error">Order not found.</div>;
return (
<div>
<p>
<Link to="/admin/orders">&larr; Back to orders</Link>
</p>
<h1>Order {order.id.slice(0, 8)}</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>Customer</h2>
<p>
{order.customer_name} &mdash; {order.customer_email}
{order.customer_phone && `${order.customer_phone}`}
</p>
{order.notes && <p style={{ color: "var(--color-text-muted)" }}>Notes: {order.notes}</p>}
<div className="field" style={{ maxWidth: 240 }}>
<label htmlFor="status">Status</label>
<select id="status" value={order.status} onChange={(e) => handleStatusChange(e.target.value)} disabled={updating}>
{ORDER_STATUSES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
</div>
<div className="panel">
<h2>Items</h2>
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Multiplier</th>
<th>Unit price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{order.items?.map((item, idx) => (
<tr key={idx}>
<td>{item.product_name}</td>
<td>
{item.tier_quantity} {item.unit_symbol}
</td>
<td>{item.multiplier}</td>
<td>{formatCents(item.unit_price_cents)}</td>
<td>{formatCents(item.total_cents)}</td>
</tr>
))}
</tbody>
</table>
<p style={{ textAlign: "right", fontWeight: 600, marginTop: "0.75rem" }}>
Total: {formatCents(order.total_cents)}
</p>
</div>
</div>
);
}
@@ -0,0 +1,71 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { formatCents, ORDER_STATUSES, type Order } from "../../api/types";
export default function OrdersPage() {
const [orders, setOrders] = useState<Order[]>([]);
const [status, setStatus] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setLoading(true);
const query = status ? `?status=${status}` : "";
apiFetch<{ orders: Order[] }>(`/api/admin/orders${query}`)
.then((data) => setOrders(data.orders))
.catch(() => setError("Failed to load orders."))
.finally(() => setLoading(false));
}, [status]);
return (
<div>
<h1>Orders</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="toolbar">
<select value={status} onChange={(e) => setStatus(e.target.value)} style={{ maxWidth: 200 }}>
<option value="">All statuses</option>
{ORDER_STATUSES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<table>
<thead>
<tr>
<th>Customer</th>
<th>Email</th>
<th>Status</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
{orders.map((o) => (
<tr key={o.id}>
<td>{o.customer_name}</td>
<td>{o.customer_email}</td>
<td>
<span className="badge">{o.status}</span>
</td>
<td>{formatCents(o.total_cents)}</td>
<td>
<Link className="btn" to={`/admin/orders/${o.id}`}>
View
</Link>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
@@ -0,0 +1,280 @@
import { useEffect, useState, type FormEvent } from "react";
import { Link, useParams } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { formatCents, type Category, type Media, type PriceTier, type Product, type Unit } from "../../api/types";
export default function ProductEditPage() {
const { id } = useParams<{ id: string }>();
const [product, setProduct] = useState<Product | null>(null);
const [categories, setCategories] = useState<Category[]>([]);
const [units, setUnits] = useState<Unit[]>([]);
const [tiers, setTiers] = useState<PriceTier[]>([]);
const [mediaLibrary, setMediaLibrary] = useState<Media[]>([]);
const [gallery, setGallery] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<{ type: "error" | "success"; text: string } | null>(null);
function load() {
if (!id) return;
setLoading(true);
Promise.all([
apiFetch<Product>(`/api/admin/products/${id}`),
apiFetch<{ categories: Category[] }>("/api/admin/categories"),
apiFetch<{ units: Unit[] }>("/api/admin/units"),
apiFetch<{ price_tiers: PriceTier[] }>(`/api/admin/products/${id}/price-tiers`),
apiFetch<{ media: Media[] }>("/api/admin/media"),
apiFetch<{ gallery: { media_id: string }[] }>(`/api/admin/products/${id}/gallery`),
])
.then(([p, c, u, t, m, g]) => {
setProduct(p);
setCategories(c.categories);
setUnits(u.units);
setTiers(t.price_tiers);
setMediaLibrary(m.media);
setGallery(g.gallery.map((item) => item.media_id));
})
.catch(() => setMessage({ type: "error", text: "Failed to load product." }))
.finally(() => setLoading(false));
}
useEffect(load, [id]);
async function handleSave(e: FormEvent) {
e.preventDefault();
if (!product) return;
setSaving(true);
setMessage(null);
try {
const updated = await apiFetch<Product>(`/api/admin/products/${id}`, {
method: "PUT",
body: JSON.stringify(product),
});
setProduct(updated);
setMessage({ type: "success", text: "Product saved." });
} catch {
setMessage({ type: "error", text: "Failed to save product (slug may already be in use)." });
} finally {
setSaving(false);
}
}
async function handleAddTier(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = new FormData(e.currentTarget);
try {
await apiFetch(`/api/admin/products/${id}/price-tiers`, {
method: "POST",
body: JSON.stringify({
unit_id: form.get("unit_id"),
quantity: Number(form.get("quantity")),
price_cents: Math.round(Number(form.get("price")) * 100),
position: tiers.length,
}),
});
e.currentTarget.reset();
load();
} catch {
setMessage({ type: "error", text: "Failed to add price tier." });
}
}
async function handleDeleteTier(tierId: string) {
if (!confirm("Delete this price tier?")) return;
try {
await apiFetch(`/api/admin/products/${id}/price-tiers/${tierId}`, { method: "DELETE" });
load();
} catch {
setMessage({ type: "error", text: "Failed to delete price tier." });
}
}
async function toggleGalleryItem(mediaId: string) {
try {
if (gallery.includes(mediaId)) {
await apiFetch(`/api/admin/products/${id}/gallery/${mediaId}`, { method: "DELETE" });
} else {
await apiFetch(`/api/admin/products/${id}/gallery`, {
method: "POST",
body: JSON.stringify({ media_id: mediaId, position: gallery.length }),
});
}
load();
} catch {
setMessage({ type: "error", text: "Failed to update gallery." });
}
}
function unitSymbol(unitId: string) {
return units.find((u) => u.id === unitId)?.symbol ?? unitId;
}
if (loading || !product) return <div className="page-loading">Loading</div>;
return (
<div>
<p>
<Link to="/admin/products">&larr; Back to products</Link>
</p>
<h1>{product.name}</h1>
{message && <div className={`alert alert-${message.type}`}>{message.text}</div>}
<div className="panel">
<h2>Details</h2>
<form onSubmit={handleSave}>
<div className="form-row">
<div className="field">
<label htmlFor="name">Name</label>
<input id="name" value={product.name} onChange={(e) => setProduct({ ...product, name: e.target.value })} required />
</div>
<div className="field">
<label htmlFor="slug">Slug</label>
<input id="slug" value={product.slug} onChange={(e) => setProduct({ ...product, slug: e.target.value })} required />
</div>
<div className="field">
<label htmlFor="category">Category</label>
<select
id="category"
value={product.category_id ?? ""}
onChange={(e) => setProduct({ ...product, category_id: e.target.value || null })}
>
<option value="">None</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
</div>
<div className="field">
<label htmlFor="short">Short description</label>
<input
id="short"
value={product.short_description}
onChange={(e) => setProduct({ ...product, short_description: e.target.value })}
/>
</div>
<div className="field">
<label htmlFor="description">Description</label>
<textarea
id="description"
rows={4}
value={product.description}
onChange={(e) => setProduct({ ...product, description: e.target.value })}
/>
</div>
<div className="field field-inline">
<input
id="active"
type="checkbox"
checked={product.is_active}
onChange={(e) => setProduct({ ...product, is_active: e.target.checked })}
/>
<label htmlFor="active">Active</label>
</div>
<div className="field field-inline">
<input
id="featured"
type="checkbox"
checked={product.is_featured}
onChange={(e) => setProduct({ ...product, is_featured: e.target.checked })}
/>
<label htmlFor="featured">Featured</label>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? "Saving…" : "Save"}
</button>
</div>
</form>
</div>
<div className="panel">
<h2>Quantity-based pricing</h2>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Unit</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
{tiers.map((t) => (
<tr key={t.id}>
<td>{t.quantity}</td>
<td>{unitSymbol(t.unit_id)}</td>
<td>{formatCents(t.price_cents)}</td>
<td>
<button className="btn btn-danger" onClick={() => handleDeleteTier(t.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
<form onSubmit={handleAddTier} style={{ marginTop: "1rem" }}>
<div className="form-row">
<div className="field">
<label htmlFor="quantity">Quantity</label>
<input id="quantity" name="quantity" type="number" step="any" min="0.001" required />
</div>
<div className="field">
<label htmlFor="unit_id">Unit</label>
<select id="unit_id" name="unit_id" required>
{units.map((u) => (
<option key={u.id} value={u.id}>
{u.name} ({u.symbol})
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="price">Price</label>
<input id="price" name="price" type="number" step="0.01" min="0" required />
</div>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary">
Add price tier
</button>
</div>
</form>
</div>
<div className="panel">
<h2>Gallery</h2>
<p style={{ color: "var(--color-text-muted)" }}>Click a media item to attach/detach it from this product's gallery.</p>
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))", gap: "0.75rem" }}>
{mediaLibrary.map((m) => {
const attached = gallery.includes(m.id);
return (
<div
key={m.id}
onClick={() => toggleGalleryItem(m.id)}
style={{
cursor: "pointer",
border: attached ? "2px solid var(--color-primary)" : "1px solid var(--color-border)",
borderRadius: 6,
padding: 4,
}}
>
{m.mime_type.startsWith("image/") ? (
<img src={m.url} alt={m.alt_text} style={{ width: "100%", height: 80, objectFit: "cover", borderRadius: 4 }} />
) : (
<div style={{ height: 80, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "0.7rem" }}>
{m.mime_type}
</div>
)}
</div>
);
})}
</div>
</div>
</div>
);
}
@@ -0,0 +1,187 @@
import { useEffect, useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { apiFetch } from "../../api/client";
import { swapPosition } from "../../api/reorder";
import type { Category, Product } from "../../api/types";
export default function ProductsPage() {
const [products, setProducts] = useState<Product[]>([]);
const [categories, setCategories] = useState<Category[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [name, setName] = useState("");
const [slug, setSlug] = useState("");
const [categoryId, setCategoryId] = useState("");
const [creating, setCreating] = useState(false);
const navigate = useNavigate();
function load() {
setLoading(true);
Promise.all([
apiFetch<{ products: Product[] }>("/api/admin/products"),
apiFetch<{ categories: Category[] }>("/api/admin/categories"),
])
.then(([p, c]) => {
setProducts(p.products);
setCategories(c.categories);
})
.catch(() => setError("Failed to load products."))
.finally(() => setLoading(false));
}
useEffect(load, []);
async function handleCreate(e: FormEvent) {
e.preventDefault();
setCreating(true);
setError(null);
try {
const created = await apiFetch<Product>("/api/admin/products", {
method: "POST",
body: JSON.stringify({
name,
slug,
category_id: categoryId || null,
is_active: true,
position: products.length,
}),
});
navigate(`/admin/products/${created.id}`);
} catch {
setError("Failed to create product (slug may already be in use).");
} finally {
setCreating(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Delete this product?")) return;
try {
await apiFetch(`/api/admin/products/${id}`, { method: "DELETE" });
load();
} catch {
setError("Failed to delete product.");
}
}
function categoryName(id?: string | null) {
if (!id) return "—";
return categories.find((c) => c.id === id)?.name ?? "—";
}
async function handleMove(index: number, direction: "up" | "down") {
try {
await swapPosition(products, index, direction, (id, position) =>
apiFetch(`/api/admin/products/${id}/position`, {
method: "PATCH",
body: JSON.stringify({ position }),
}),
);
load();
} catch {
setError("Failed to reorder products.");
}
}
return (
<div>
<h1>Products</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>New product</h2>
<form onSubmit={handleCreate}>
<div className="form-row">
<div className="field">
<label htmlFor="p-name">Name</label>
<input id="p-name" value={name} onChange={(e) => setName(e.target.value)} required />
</div>
<div className="field">
<label htmlFor="p-slug">Slug</label>
<input id="p-slug" value={slug} onChange={(e) => setSlug(e.target.value)} required />
</div>
<div className="field">
<label htmlFor="p-category">Category</label>
<select id="p-category" value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
<option value="">None</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={creating}>
{creating ? "Creating…" : "Create product"}
</button>
</div>
</form>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<table>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Order</th>
<th>Status</th>
<th>Featured</th>
<th></th>
</tr>
</thead>
<tbody>
{products.map((p, index) => (
<tr key={p.id}>
<td>{p.name}</td>
<td>{categoryName(p.category_id)}</td>
<td>
<div style={{ display: "flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
className="btn"
title="Move up"
disabled={index === 0}
onClick={() => handleMove(index, "up")}
>
</button>
<button
type="button"
className="btn"
title="Move down"
disabled={index === products.length - 1}
onClick={() => handleMove(index, "down")}
>
</button>
<span>{p.position}</span>
</div>
</td>
<td>
<span className={`badge ${p.is_active ? "badge-active" : "badge-inactive"}`}>
{p.is_active ? "active" : "inactive"}
</span>
</td>
<td>{p.is_featured ? "★" : ""}</td>
<td>
<Link className="btn" to={`/admin/products/${p.id}`}>
Edit
</Link>{" "}
<button className="btn btn-danger" onClick={() => handleDelete(p.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
@@ -0,0 +1,82 @@
import { useEffect, useState, type FormEvent } from "react";
import { apiFetch } from "../../api/client";
import type { SiteSettings } from "../../api/types";
export default function SiteSettingsPage() {
const [settings, setSettings] = useState<SiteSettings>({ name: "", description: "", slug: "" });
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState<{ type: "error" | "success"; text: string } | null>(null);
useEffect(() => {
apiFetch<SiteSettings>("/api/admin/site-settings")
.then(setSettings)
.catch(() => setMessage({ type: "error", text: "Failed to load site settings." }))
.finally(() => setLoading(false));
}, []);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setSaving(true);
setMessage(null);
try {
const updated = await apiFetch<SiteSettings>("/api/admin/site-settings", {
method: "PUT",
body: JSON.stringify(settings),
});
setSettings(updated);
setMessage({ type: "success", text: "Site settings saved." });
} catch {
setMessage({ type: "error", text: "Failed to save site settings." });
} finally {
setSaving(false);
}
}
if (loading) return <div className="page-loading">Loading</div>;
return (
<div>
<h1>General</h1>
<div className="panel">
{message && <div className={`alert alert-${message.type}`}>{message.text}</div>}
<form onSubmit={handleSubmit}>
<div className="field">
<label htmlFor="name">Site name</label>
<input
id="name"
value={settings.name}
onChange={(e) => setSettings({ ...settings, name: e.target.value })}
required
/>
</div>
<div className="field">
<label htmlFor="slug">Slug</label>
<input
id="slug"
value={settings.slug}
onChange={(e) => setSettings({ ...settings, slug: e.target.value })}
pattern="^[a-z0-9]+(-[a-z0-9]+)*$"
title="lowercase letters, digits and hyphens only"
required
/>
</div>
<div className="field">
<label htmlFor="description">Description</label>
<textarea
id="description"
rows={3}
value={settings.description}
onChange={(e) => setSettings({ ...settings, description: e.target.value })}
/>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? "Saving…" : "Save"}
</button>
</div>
</form>
</div>
</div>
);
}
@@ -0,0 +1,134 @@
import { useEffect, useState, type FormEvent } from "react";
import { apiFetch } from "../../api/client";
import type { TelegramSettings } from "../../api/types";
export default function TelegramSettingsPage() {
const [settings, setSettings] = useState<TelegramSettings | null>(null);
const [botToken, setBotToken] = useState("");
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [message, setMessage] = useState<{ type: "error" | "success"; text: string } | null>(null);
function load() {
setLoading(true);
apiFetch<TelegramSettings>("/api/admin/notifications/telegram")
.then(setSettings)
.catch(() => setMessage({ type: "error", text: "Failed to load Telegram settings." }))
.finally(() => setLoading(false));
}
useEffect(load, []);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!settings) return;
setSaving(true);
setMessage(null);
try {
const updated = await apiFetch<TelegramSettings>("/api/admin/notifications/telegram", {
method: "PUT",
body: JSON.stringify({
enabled: settings.enabled,
bot_token: botToken,
chat_id: settings.chat_id,
notify_new_order: settings.notify_new_order,
notify_status_change: settings.notify_status_change,
}),
});
setSettings(updated);
setBotToken("");
setMessage({ type: "success", text: "Telegram settings saved." });
} catch {
setMessage({ type: "error", text: "Failed to save Telegram settings." });
} finally {
setSaving(false);
}
}
async function handleTest() {
setTesting(true);
setMessage(null);
try {
await apiFetch("/api/admin/notifications/telegram/test", { method: "POST" });
setMessage({ type: "success", text: "Test message sent." });
} catch {
setMessage({ type: "error", text: "Failed to send test message. Check bot token/chat id." });
} finally {
setTesting(false);
}
}
if (loading || !settings) return <div className="page-loading">Loading</div>;
return (
<div>
<h1>Telegram notifications</h1>
{message && <div className={`alert alert-${message.type}`}>{message.text}</div>}
<div className="panel">
<form onSubmit={handleSubmit}>
<div className="field field-inline">
<input
id="tg-enabled"
type="checkbox"
checked={settings.enabled}
onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
/>
<label htmlFor="tg-enabled">Enabled</label>
</div>
<div className="field">
<label htmlFor="tg-token">
Bot token {settings.bot_token_configured && <span style={{ color: "var(--color-text-muted)" }}>(configured leave blank to keep it)</span>}
</label>
<input
id="tg-token"
type="password"
value={botToken}
onChange={(e) => setBotToken(e.target.value)}
placeholder={settings.bot_token_configured ? "••••••••" : ""}
/>
</div>
<div className="field">
<label htmlFor="tg-chat">Chat ID</label>
<input
id="tg-chat"
value={settings.chat_id}
onChange={(e) => setSettings({ ...settings, chat_id: e.target.value })}
/>
</div>
<div className="field field-inline">
<input
id="tg-new-order"
type="checkbox"
checked={settings.notify_new_order}
onChange={(e) => setSettings({ ...settings, notify_new_order: e.target.checked })}
/>
<label htmlFor="tg-new-order">Notify on new order</label>
</div>
<div className="field field-inline">
<input
id="tg-status-change"
type="checkbox"
checked={settings.notify_status_change}
onChange={(e) => setSettings({ ...settings, notify_status_change: e.target.checked })}
/>
<label htmlFor="tg-status-change">Notify on order status change</label>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" onClick={handleTest} disabled={testing}>
{testing ? "Sending…" : "Send test message"}
</button>
</div>
</form>
</div>
</div>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { useEffect, useState, type FormEvent } from "react";
import { apiFetch } from "../../api/client";
import type { Unit } from "../../api/types";
export default function UnitsPage() {
const [units, setUnits] = useState<Unit[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
const [name, setName] = useState("");
const [symbol, setSymbol] = useState("");
const [saving, setSaving] = useState(false);
function load() {
setLoading(true);
apiFetch<{ units: Unit[] }>("/api/admin/units")
.then((data) => setUnits(data.units))
.catch(() => setError("Failed to load units."))
.finally(() => setLoading(false));
}
useEffect(load, []);
function startEdit(unit: Unit) {
setEditingId(unit.id);
setName(unit.name);
setSymbol(unit.symbol);
}
function resetForm() {
setEditingId(null);
setName("");
setSymbol("");
}
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setSaving(true);
setError(null);
try {
if (editingId) {
await apiFetch(`/api/admin/units/${editingId}`, { method: "PUT", body: JSON.stringify({ name, symbol }) });
} else {
await apiFetch("/api/admin/units", { method: "POST", body: JSON.stringify({ name, symbol }) });
}
resetForm();
load();
} catch {
setError("Failed to save unit (symbol may already be in use).");
} finally {
setSaving(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Delete this unit?")) return;
try {
await apiFetch(`/api/admin/units/${id}`, { method: "DELETE" });
load();
} catch {
setError("Failed to delete unit (it may still be used by price tiers).");
}
}
return (
<div>
<h1>Units</h1>
<p style={{ color: "var(--color-text-muted)", marginTop: "-0.5rem" }}>
Define your own measurement units (kg, piece, box, ...) &mdash; not limited to a fixed list.
</p>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>{editingId ? "Edit unit" : "New unit"}</h2>
<form onSubmit={handleSubmit}>
<div className="form-row">
<div className="field">
<label htmlFor="unit-name">Name</label>
<input id="unit-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Kilogram" required />
</div>
<div className="field">
<label htmlFor="unit-symbol">Symbol</label>
<input id="unit-symbol" value={symbol} onChange={(e) => setSymbol(e.target.value)} placeholder="kg" required />
</div>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={saving}>
{saving ? "Saving…" : editingId ? "Save changes" : "Create unit"}
</button>
{editingId && (
<button type="button" className="btn" onClick={resetForm}>
Cancel
</button>
)}
</div>
</form>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<table>
<thead>
<tr>
<th>Name</th>
<th>Symbol</th>
<th></th>
</tr>
</thead>
<tbody>
{units.map((u) => (
<tr key={u.id}>
<td>{u.name}</td>
<td>{u.symbol}</td>
<td>
<button className="btn" onClick={() => startEdit(u)}>
Edit
</button>{" "}
<button className="btn btn-danger" onClick={() => handleDelete(u.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
+128
View File
@@ -0,0 +1,128 @@
import { useEffect, useState, type FormEvent } from "react";
import { apiFetch } from "../../api/client";
import type { User } from "../../api/types";
export default function UsersPage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [role, setRole] = useState("admin");
const [creating, setCreating] = useState(false);
function load() {
setLoading(true);
apiFetch<{ users: User[] }>("/api/admin/users")
.then((data) => setUsers(data.users))
.catch(() => setError("Failed to load users."))
.finally(() => setLoading(false));
}
useEffect(load, []);
async function handleCreate(e: FormEvent) {
e.preventDefault();
setCreating(true);
setError(null);
try {
await apiFetch("/api/admin/users", {
method: "POST",
body: JSON.stringify({ email, password, role }),
});
setEmail("");
setPassword("");
load();
} catch {
setError("Failed to create user. Password must be at least 12 characters.");
} finally {
setCreating(false);
}
}
async function handleDelete(id: string) {
if (!confirm("Delete this user?")) return;
try {
await apiFetch(`/api/admin/users/${id}`, { method: "DELETE" });
load();
} catch {
setError("Failed to delete user.");
}
}
return (
<div>
<h1>Users</h1>
{error && <div className="alert alert-error">{error}</div>}
<div className="panel">
<h2>Create user</h2>
<form onSubmit={handleCreate}>
<div className="form-row">
<div className="field">
<label htmlFor="new-email">Email</label>
<input id="new-email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
</div>
<div className="field">
<label htmlFor="new-password">Password</label>
<input
id="new-password"
type="password"
minLength={12}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="field">
<label htmlFor="new-role">Role</label>
<select id="new-role" value={role} onChange={(e) => setRole(e.target.value)}>
<option value="admin">Admin</option>
<option value="customer">Customer</option>
</select>
</div>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={creating}>
{creating ? "Creating…" : "Create user"}
</button>
</div>
</form>
</div>
{loading ? (
<div className="page-loading">Loading</div>
) : (
<table>
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>{u.email}</td>
<td>{u.role}</td>
<td>
<span className={`badge ${u.is_active ? "badge-active" : "badge-inactive"}`}>
{u.is_active ? "active" : "inactive"}
</span>
</td>
<td>
<button className="btn btn-danger" onClick={() => handleDelete(u.id)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
@@ -0,0 +1,63 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { apiFetch, setAccessToken } from "../../api/client";
import type { User } from "../../api/types";
interface LoginResponse {
access_token: string;
user: User;
}
interface AuthContextValue {
user: User | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// No access token yet on a fresh page load: this first call is
// expected to 401, which triggers the client's automatic
// refresh-via-cookie-and-retry. If that succeeds we're still logged
// in; if not, the user lands on the login page.
apiFetch<User>("/api/auth/admin/me")
.then(setUser)
.catch(() => setUser(null))
.finally(() => setLoading(false));
}, []);
async function login(email: string, password: string) {
const data = await apiFetch<LoginResponse>("/api/auth/admin/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
setAccessToken(data.access_token);
setUser(data.user);
}
async function logout() {
try {
await apiFetch("/api/auth/admin/logout", { method: "POST" });
} finally {
setAccessToken(null);
setUser(null);
}
}
return (
<AuthContext.Provider value={{ user, loading, login, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
return ctx;
}
+71
View File
@@ -0,0 +1,71 @@
import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "./AuthContext";
import { ApiError } from "../../api/client";
export default function LoginPage() {
const { login } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setError(null);
setSubmitting(true);
try {
await login(email, password);
navigate("/admin", { replace: true });
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
setError("Invalid email or password.");
} else if (err instanceof ApiError && err.status === 429) {
setError("Too many attempts. Please wait a moment and try again.");
} else {
setError("Something went wrong. Please try again.");
}
} finally {
setSubmitting(false);
}
}
return (
<div className="auth-screen">
<div className="auth-card">
<h1>Admin sign in</h1>
{error && <div className="alert alert-error">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="field">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="field">
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="form-actions">
<button type="submit" className="btn btn-primary" disabled={submitting}>
{submitting ? "Signing in…" : "Sign in"}
</button>
</div>
</form>
</div>
</div>
);
}
+290
View File
@@ -0,0 +1,290 @@
:root {
--color-bg: #f4f5f7;
--color-surface: #ffffff;
--color-border: #e0e2e7;
--color-text: #1f2430;
--color-text-muted: #6b7280;
--color-primary: #2563eb;
--color-primary-hover: #1d4ed8;
--color-danger: #dc2626;
--color-success: #16a34a;
--radius: 8px;
--sidebar-width: 220px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
color-scheme: light;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--color-bg);
color: var(--color-text);
}
a {
color: var(--color-primary);
}
button {
font-family: inherit;
cursor: pointer;
}
.btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 0.9rem;
border-radius: var(--radius);
border: 1px solid var(--color-border);
background: var(--color-surface);
color: var(--color-text);
font-size: 0.9rem;
}
.btn:hover {
border-color: var(--color-primary);
}
.btn-primary {
background: var(--color-primary);
border-color: var(--color-primary);
color: white;
}
.btn-primary:hover {
background: var(--color-primary-hover);
}
.btn-danger {
color: var(--color-danger);
border-color: var(--color-danger);
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.page-loading {
padding: 2rem;
text-align: center;
color: var(--color-text-muted);
}
/* --- Auth / login --- */
.auth-screen {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.auth-card {
width: 100%;
max-width: 360px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: 2rem;
}
.auth-card h1 {
font-size: 1.25rem;
margin: 0 0 1.5rem;
}
/* --- Forms --- */
.field {
margin-bottom: 1rem;
}
.field label {
display: block;
font-size: 0.85rem;
font-weight: 600;
margin-bottom: 0.3rem;
}
.field input,
.field textarea,
.field select {
width: 100%;
padding: 0.55rem 0.7rem;
border: 1px solid var(--color-border);
border-radius: var(--radius);
font-size: 0.9rem;
}
.field-inline {
display: flex;
align-items: center;
gap: 0.5rem;
}
.form-row {
display: flex;
gap: 1rem;
}
.form-row > .field {
flex: 1;
}
.form-actions {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
}
.alert {
padding: 0.6rem 0.8rem;
border-radius: var(--radius);
font-size: 0.85rem;
margin-bottom: 1rem;
}
.alert-error {
background: #fee2e2;
color: #991b1b;
}
.alert-success {
background: #dcfce7;
color: #166534;
}
/* --- Admin shell --- */
.admin-shell {
display: flex;
min-height: 100vh;
}
.admin-sidebar {
width: var(--sidebar-width);
flex-shrink: 0;
background: #111827;
color: #e5e7eb;
padding: 1.25rem 0.75rem;
}
.admin-sidebar h2 {
font-size: 1rem;
margin: 0 0 1.25rem;
padding: 0 0.5rem;
color: white;
}
.admin-sidebar nav {
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.admin-sidebar a {
color: #d1d5db;
text-decoration: none;
padding: 0.5rem 0.6rem;
border-radius: var(--radius);
font-size: 0.88rem;
}
.admin-sidebar a:hover,
.admin-sidebar a.active {
background: #1f2937;
color: white;
}
.admin-main {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
.admin-topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1.5rem;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
}
.admin-content {
padding: 1.5rem;
flex: 1;
}
.admin-content h1 {
font-size: 1.4rem;
margin: 0 0 1rem;
}
/* --- Tables --- */
table {
width: 100%;
border-collapse: collapse;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
overflow: hidden;
}
th, td {
text-align: left;
padding: 0.6rem 0.8rem;
border-bottom: 1px solid var(--color-border);
font-size: 0.88rem;
}
th {
background: #f9fafb;
font-weight: 600;
}
tr:last-child td {
border-bottom: none;
}
.panel {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: 1.25rem;
margin-bottom: 1.5rem;
}
.panel h2 {
font-size: 1.05rem;
margin: 0 0 1rem;
}
.badge {
display: inline-block;
padding: 0.15rem 0.5rem;
border-radius: 999px;
font-size: 0.75rem;
background: #e5e7eb;
}
.badge-active {
background: #dcfce7;
color: #166534;
}
.badge-inactive {
background: #fee2e2;
color: #991b1b;
}
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+15
View File
@@ -0,0 +1,15 @@
import type { ReactNode } from "react";
import { Navigate } from "react-router-dom";
import { useAuth } from "../features/auth/AuthContext";
export default function ProtectedRoute({ children }: { children: ReactNode }) {
const { user, loading } = useAuth();
if (loading) {
return <div className="page-loading">Loading</div>;
}
if (!user) {
return <Navigate to="/login" replace />;
}
return <>{children}</>;
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+17
View File
@@ -0,0 +1,17 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
// Proxied so the browser sees /api and the backend as the same
// origin (localhost:5173) in dev -- the refresh-token cookie then
// "just works" as same-site without touching CORS/SameSite at all.
'/api': 'http://localhost:8080',
'/uploads': 'http://localhost:8080',
},
},
})