mirror of
https://git.meshkee.com/novintrades/website.git
synced 2026-08-11 20:50:58 +04:30
Initial commit: NovinTrades website monorepo.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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 }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<!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" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>NovinTrades Admin</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@novintrades/admin",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tiptap/extension-image": "^3.28.0",
|
||||
"@tiptap/extension-link": "^3.28.0",
|
||||
"@tiptap/extension-placeholder": "^3.28.0",
|
||||
"@tiptap/react": "^3.28.0",
|
||||
"@tiptap/starter-kit": "^3.28.0",
|
||||
"lucide-react": "^1.26.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-easy-crop": "^6.2.2",
|
||||
"react-router-dom": "^7.18.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"oxlint": "^1.71.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
|
||||
<rect width="32" height="32" rx="4" fill="#0B1F3A"/>
|
||||
<rect x="6" y="6" width="20" height="20" rx="2" fill="#1A6CF0"/>
|
||||
<text x="16" y="21" text-anchor="middle" fill="#FFFFFF" font-family="Arial, sans-serif" font-size="11" font-weight="700">NT</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,37 @@
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import { Layout } from "./components/Layout";
|
||||
import { RequireAuth } from "./components/RequireAuth";
|
||||
import { BlogNewPage } from "./pages/BlogNewPage";
|
||||
import { BlogPage } from "./pages/BlogPage";
|
||||
import { BrandNewPage } from "./pages/BrandNewPage";
|
||||
import { BrandsPage } from "./pages/BrandsPage";
|
||||
import { HomePage } from "./pages/HomePage";
|
||||
import { LoginPage } from "./pages/LoginPage";
|
||||
import { ReportageNewPage } from "./pages/ReportageNewPage";
|
||||
import { ReportagePage } from "./pages/ReportagePage";
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
|
||||
<Route element={<RequireAuth />}>
|
||||
<Route element={<Layout />}>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="blog" element={<BlogPage />} />
|
||||
<Route path="blog/new" element={<BlogNewPage />} />
|
||||
<Route path="blog/:id/edit" element={<BlogNewPage />} />
|
||||
<Route path="reportage" element={<ReportagePage />} />
|
||||
<Route path="reportage/new" element={<ReportageNewPage />} />
|
||||
<Route path="reportage/:id/edit" element={<ReportageNewPage />} />
|
||||
<Route path="brands" element={<BrandsPage />} />
|
||||
<Route path="brands/new" element={<BrandNewPage />} />
|
||||
<Route path="brands/:id/edit" element={<BrandNewPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,38 @@
|
||||
.contacts__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.contacts__list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.contacts__row {
|
||||
display: grid;
|
||||
grid-template-columns: 150px 1fr auto;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.contacts__empty {
|
||||
padding: 0.9rem 1rem;
|
||||
border: 1px dashed var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
color: var(--gray-600);
|
||||
font-size: 0.85rem;
|
||||
background: var(--gray-50);
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.contacts__row {
|
||||
grid-template-columns: 1fr auto;
|
||||
}
|
||||
|
||||
.contacts__row .field-select {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import { IconButton } from "./IconButton";
|
||||
import "./ContactFields.css";
|
||||
|
||||
export type ContactType =
|
||||
| "phone"
|
||||
| "landline"
|
||||
| "email"
|
||||
| "instagram"
|
||||
| "website"
|
||||
| "whatsapp"
|
||||
| "other";
|
||||
|
||||
export interface ContactItem {
|
||||
id: string;
|
||||
type: ContactType;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const CONTACT_TYPES: { value: ContactType; label: string }[] = [
|
||||
{ value: "phone", label: "Phone" },
|
||||
{ value: "landline", label: "Land line" },
|
||||
{ value: "email", label: "Email" },
|
||||
{ value: "instagram", label: "Instagram" },
|
||||
{ value: "website", label: "Website" },
|
||||
{ value: "whatsapp", label: "WhatsApp" },
|
||||
{ value: "other", label: "Other" },
|
||||
];
|
||||
|
||||
interface ContactFieldsProps {
|
||||
value: ContactItem[];
|
||||
onChange: (value: ContactItem[]) => void;
|
||||
}
|
||||
|
||||
export function createContact(type: ContactType = "phone"): ContactItem {
|
||||
return {
|
||||
id: `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
type,
|
||||
value: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function ContactFields({ value, onChange }: ContactFieldsProps) {
|
||||
function update(id: string, patch: Partial<ContactItem>) {
|
||||
onChange(value.map((item) => (item.id === id ? { ...item, ...patch } : item)));
|
||||
}
|
||||
|
||||
function remove(id: string) {
|
||||
onChange(value.filter((item) => item.id !== id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="field">
|
||||
<div className="contacts__header">
|
||||
<span className="field__label">Contact info</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost btn--sm"
|
||||
onClick={() => onChange([...value, createContact()])}
|
||||
>
|
||||
<Plus size={14} />
|
||||
Add contact
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="contacts__list">
|
||||
{value.length === 0 ? (
|
||||
<p className="contacts__empty">No contacts yet. Add phone, email, Instagram, etc.</p>
|
||||
) : (
|
||||
value.map((item) => (
|
||||
<div key={item.id} className="contacts__row">
|
||||
<select
|
||||
className="field-select"
|
||||
value={item.type}
|
||||
onChange={(e) => update(item.id, { type: e.target.value as ContactType })}
|
||||
aria-label="Contact type"
|
||||
>
|
||||
{CONTACT_TYPES.map((type) => (
|
||||
<option key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
className="field-input"
|
||||
value={item.value}
|
||||
onChange={(e) => update(item.id, { value: e.target.value })}
|
||||
placeholder={
|
||||
item.type === "email"
|
||||
? "name@company.com"
|
||||
: item.type === "instagram"
|
||||
? "@brand"
|
||||
: "Value"
|
||||
}
|
||||
/>
|
||||
<IconButton label="Remove contact" variant="danger" onClick={() => remove(item.id)}>
|
||||
<Trash2 size={15} />
|
||||
</IconButton>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
.table-wrap {
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.data-table {
|
||||
min-width: 640px;
|
||||
}
|
||||
|
||||
.data-table th,
|
||||
.data-table td {
|
||||
text-align: left;
|
||||
padding: 0.85rem 1rem;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
background: var(--gray-50);
|
||||
color: var(--gray-600);
|
||||
font-weight: 600;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table tbody tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover td {
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
|
||||
.data-table td {
|
||||
color: var(--gray-800);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.cell-title {
|
||||
font-weight: 600;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.cell-muted {
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
border: none;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.badge--clickable {
|
||||
cursor: pointer;
|
||||
transition: filter 0.15s ease, transform 0.15s ease;
|
||||
}
|
||||
|
||||
.badge--clickable:hover {
|
||||
filter: brightness(0.96);
|
||||
}
|
||||
|
||||
.badge--clickable:focus-visible {
|
||||
outline: 2px solid var(--blue);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.badge--approved {
|
||||
background: var(--success-soft);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.badge--pending {
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
}
|
||||
|
||||
.badge--rejected {
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
max-width: 320px;
|
||||
padding: 0.55rem 0.85rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
color: var(--gray-800);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.search-input::placeholder {
|
||||
color: var(--gray-400);
|
||||
}
|
||||
|
||||
.filter-select {
|
||||
padding: 0.55rem 0.85rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
color: var(--gray-800);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.filter-select:focus {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 3rem 1.5rem;
|
||||
text-align: center;
|
||||
color: var(--gray-600);
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { ReactNode } from "react";
|
||||
import "./DataTable.css";
|
||||
|
||||
interface Column<T> {
|
||||
key: string;
|
||||
header: string;
|
||||
render: (row: T) => ReactNode;
|
||||
width?: string;
|
||||
}
|
||||
|
||||
interface DataTableProps<T> {
|
||||
columns: Column<T>[];
|
||||
rows: T[];
|
||||
rowKey: (row: T) => string;
|
||||
}
|
||||
|
||||
export function DataTable<T>({ columns, rows, rowKey }: DataTableProps<T>) {
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th key={col.key} style={col.width ? { width: col.width } : undefined}>
|
||||
{col.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={rowKey(row)}>
|
||||
{columns.map((col) => (
|
||||
<td key={col.key}>{col.render(row)}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
.icon-btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--radius);
|
||||
color: var(--gray-600);
|
||||
border: 1px solid var(--gray-200);
|
||||
background: var(--white);
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.icon-btn:hover {
|
||||
background: var(--gray-100);
|
||||
color: var(--dark-blue);
|
||||
border-color: var(--gray-200);
|
||||
}
|
||||
|
||||
.icon-btn--primary {
|
||||
background: var(--blue);
|
||||
border-color: var(--blue);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.icon-btn--primary:hover {
|
||||
background: var(--blue-hover);
|
||||
border-color: var(--blue-hover);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.icon-btn--danger {
|
||||
border-color: transparent;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.icon-btn--danger:hover {
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.icon-btn::after {
|
||||
content: attr(data-tooltip);
|
||||
position: absolute;
|
||||
bottom: calc(100% + 6px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(2px);
|
||||
padding: 0.3rem 0.5rem;
|
||||
background: var(--dark-blue);
|
||||
color: var(--white);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
border-radius: 4px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.12s ease, transform 0.12s ease;
|
||||
z-index: 20;
|
||||
}
|
||||
|
||||
.icon-btn:hover::after,
|
||||
.icon-btn:focus-visible::after {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(0);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { ReactNode } from "react";
|
||||
import "./IconButton.css";
|
||||
|
||||
interface IconButtonProps {
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
variant?: "default" | "danger" | "primary";
|
||||
children: ReactNode;
|
||||
type?: "button" | "submit";
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function IconButton({
|
||||
label,
|
||||
onClick,
|
||||
variant = "default",
|
||||
children,
|
||||
type = "button",
|
||||
disabled = false,
|
||||
}: IconButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
className={`icon-btn icon-btn--${variant}`}
|
||||
aria-label={label}
|
||||
data-tooltip={label}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
.image-cropper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.image-cropper__upload {
|
||||
width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
border: 1px dashed var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--gray-50);
|
||||
color: var(--gray-600);
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.image-cropper__upload:hover {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.image-cropper__upload span {
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.image-cropper__upload small {
|
||||
font-size: 0.75rem;
|
||||
color: var(--gray-400);
|
||||
}
|
||||
|
||||
.image-cropper__preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
background: var(--gray-100);
|
||||
}
|
||||
|
||||
.image-cropper__preview img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.image-cropper__preview-actions {
|
||||
position: absolute;
|
||||
top: 0.65rem;
|
||||
right: 0.65rem;
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.crop-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 100;
|
||||
background: rgba(11, 31, 58, 0.55);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.crop-modal__panel {
|
||||
width: min(720px, 100%);
|
||||
background: var(--white);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.crop-modal__stage {
|
||||
position: relative;
|
||||
height: 420px;
|
||||
background: var(--dark-blue);
|
||||
}
|
||||
|
||||
.crop-modal__controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.crop-modal__zoom {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--gray-600);
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.crop-modal__zoom input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.crop-modal__actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import Cropper, { type Area } from "react-easy-crop";
|
||||
import { ImagePlus, Trash2 } from "lucide-react";
|
||||
import { ApiError } from "../lib/api";
|
||||
import {
|
||||
canvasToJpegBlob,
|
||||
maxImageLabel,
|
||||
} from "../lib/image";
|
||||
import { uploadImage } from "../lib/services";
|
||||
import { IconButton } from "./IconButton";
|
||||
import "./ImageCropper.css";
|
||||
|
||||
interface ImageCropperProps {
|
||||
label: string;
|
||||
value: string | null;
|
||||
onChange: (value: string | null) => void;
|
||||
aspect?: number;
|
||||
folder?: string;
|
||||
}
|
||||
|
||||
function createImage(url: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.addEventListener("load", () => resolve(img));
|
||||
img.addEventListener("error", reject);
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
async function getCroppedBlob(imageSrc: string, crop: Area): Promise<Blob> {
|
||||
const image = await createImage(imageSrc);
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) throw new Error("Canvas not supported");
|
||||
|
||||
canvas.width = crop.width;
|
||||
canvas.height = crop.height;
|
||||
ctx.drawImage(
|
||||
image,
|
||||
crop.x,
|
||||
crop.y,
|
||||
crop.width,
|
||||
crop.height,
|
||||
0,
|
||||
0,
|
||||
crop.width,
|
||||
crop.height,
|
||||
);
|
||||
return canvasToJpegBlob(canvas, 0.85);
|
||||
}
|
||||
|
||||
export function ImageCropper({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
aspect = 1,
|
||||
folder = "uploads",
|
||||
}: ImageCropperProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [rawSrc, setRawSrc] = useState<string | null>(null);
|
||||
const [crop, setCrop] = useState({ x: 0, y: 0 });
|
||||
const [zoom, setZoom] = useState(1);
|
||||
const [croppedArea, setCroppedArea] = useState<Area | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const onCropComplete = useCallback((_: Area, croppedPixels: Area) => {
|
||||
setCroppedArea(croppedPixels);
|
||||
}, []);
|
||||
|
||||
function onFileChange(file: File | undefined) {
|
||||
if (!file) return;
|
||||
setError("");
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
setRawSrc(String(reader.result));
|
||||
setCrop({ x: 0, y: 0 });
|
||||
setZoom(1);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
async function applyCrop() {
|
||||
if (!rawSrc || !croppedArea) return;
|
||||
setError("");
|
||||
setUploading(true);
|
||||
try {
|
||||
const blob = await getCroppedBlob(rawSrc, croppedArea);
|
||||
const uploaded = await uploadImage(blob, folder);
|
||||
onChange(uploaded.url);
|
||||
setRawSrc(null);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError || err instanceof Error
|
||||
? err.message
|
||||
: "Upload failed",
|
||||
);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="field">
|
||||
<span className="field__label">{label}</span>
|
||||
<div className="image-cropper">
|
||||
{value ? (
|
||||
<div className="image-cropper__preview">
|
||||
<img src={value} alt="Main preview" />
|
||||
<div className="image-cropper__preview-actions">
|
||||
<IconButton
|
||||
label="Replace image"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
>
|
||||
<ImagePlus size={16} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Remove image"
|
||||
variant="danger"
|
||||
onClick={() => onChange(null)}
|
||||
disabled={uploading}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="image-cropper__upload"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
>
|
||||
<ImagePlus size={22} />
|
||||
<span>{uploading ? "Uploading…" : "Upload main image"}</span>
|
||||
<small>JPG or PNG · max {maxImageLabel()} · crop after upload</small>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
onFileChange(e.target.files?.[0]);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? <p className="field__error">{error}</p> : null}
|
||||
|
||||
{rawSrc ? (
|
||||
<div className="crop-modal" role="dialog" aria-modal aria-label="Crop image">
|
||||
<div className="crop-modal__panel">
|
||||
<div className="crop-modal__stage">
|
||||
<Cropper
|
||||
image={rawSrc}
|
||||
crop={crop}
|
||||
zoom={zoom}
|
||||
aspect={aspect}
|
||||
onCropChange={setCrop}
|
||||
onZoomChange={setZoom}
|
||||
onCropComplete={onCropComplete}
|
||||
/>
|
||||
</div>
|
||||
<div className="crop-modal__controls">
|
||||
<label className="crop-modal__zoom">
|
||||
Zoom
|
||||
<input
|
||||
type="range"
|
||||
min={1}
|
||||
max={3}
|
||||
step={0.05}
|
||||
value={zoom}
|
||||
onChange={(e) => setZoom(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<div className="crop-modal__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => setRawSrc(null)}
|
||||
disabled={uploading}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--primary"
|
||||
onClick={() => void applyCrop()}
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? "Uploading…" : "Apply & upload"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{error ? <p className="crop-modal__error">{error}</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
.image-gallery {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.image-gallery__item {
|
||||
position: relative;
|
||||
aspect-ratio: 1 / 1;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
background: var(--gray-100);
|
||||
}
|
||||
|
||||
.image-gallery__item img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.image-gallery__item-actions {
|
||||
position: absolute;
|
||||
top: 0.45rem;
|
||||
right: 0.45rem;
|
||||
}
|
||||
|
||||
.image-gallery__add {
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.3rem;
|
||||
border: 1px dashed var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--gray-50);
|
||||
color: var(--gray-600);
|
||||
padding: 0.75rem;
|
||||
text-align: center;
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.image-gallery__add:hover:not(:disabled) {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.image-gallery__add:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.image-gallery__add span {
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.image-gallery__add small {
|
||||
font-size: 0.72rem;
|
||||
color: var(--gray-400);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { ImagePlus, Trash2 } from "lucide-react";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { maxImageLabel } from "../lib/image";
|
||||
import { uploadImage } from "../lib/services";
|
||||
import { IconButton } from "./IconButton";
|
||||
import "./ImageGallery.css";
|
||||
|
||||
interface ImageGalleryProps {
|
||||
label: string;
|
||||
value: string[];
|
||||
onChange: (value: string[]) => void;
|
||||
folder?: string;
|
||||
}
|
||||
|
||||
export function ImageGallery({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
folder = "brands",
|
||||
}: ImageGalleryProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function onFilesSelected(files: FileList | null) {
|
||||
if (!files?.length) return;
|
||||
setError("");
|
||||
setUploading(true);
|
||||
|
||||
try {
|
||||
const uploadedUrls: string[] = [];
|
||||
for (const file of Array.from(files)) {
|
||||
const uploaded = await uploadImage(file, folder);
|
||||
uploadedUrls.push(uploaded.url);
|
||||
}
|
||||
onChange([...value, ...uploadedUrls]);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError || err instanceof Error
|
||||
? err.message
|
||||
: "Upload failed",
|
||||
);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
onChange(value.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="field">
|
||||
<span className="field__label">{label}</span>
|
||||
<div className="image-gallery">
|
||||
{value.map((url, index) => (
|
||||
<div key={`${url}-${index}`} className="image-gallery__item">
|
||||
<img src={url} alt={`Gallery ${index + 1}`} />
|
||||
<div className="image-gallery__item-actions">
|
||||
<IconButton
|
||||
label="Remove image"
|
||||
variant="danger"
|
||||
onClick={() => removeAt(index)}
|
||||
disabled={uploading}
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="image-gallery__add"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
>
|
||||
<ImagePlus size={20} />
|
||||
<span>{uploading ? "Uploading…" : "Add images"}</span>
|
||||
<small>No crop · max {maxImageLabel()} each</small>
|
||||
</button>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
void onFilesSelected(e.target.files);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="field__error">{error}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
.layout {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
background: var(--gray-50);
|
||||
}
|
||||
|
||||
.layout__main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.9rem 1.75rem;
|
||||
background: var(--white);
|
||||
border-bottom: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.topbar__label {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.topbar__meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.topbar__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.3rem 0.65rem;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.layout__content {
|
||||
padding: 1.75rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.layout {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.topbar,
|
||||
.layout__content {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
.layout__content {
|
||||
padding-top: 1.25rem;
|
||||
padding-bottom: 1.25rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Outlet, useNavigate } from "react-router-dom";
|
||||
import { ExternalLink, LogOut } from "lucide-react";
|
||||
import { getCurrentUser, logoutSession } from "../lib/auth";
|
||||
import { WEB_URL } from "../lib/config";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { Sidebar } from "./Sidebar";
|
||||
import "./Layout.css";
|
||||
|
||||
export function Layout() {
|
||||
const navigate = useNavigate();
|
||||
const user = getCurrentUser();
|
||||
|
||||
function onLogout() {
|
||||
logoutSession();
|
||||
navigate("/login", { replace: true });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="layout">
|
||||
<Sidebar />
|
||||
<div className="layout__main">
|
||||
<header className="topbar">
|
||||
<p className="topbar__label">Admin Dashboard</p>
|
||||
<div className="topbar__meta">
|
||||
<span className="topbar__chip">{user?.email ?? "Super Admin"}</span>
|
||||
<IconButton
|
||||
label="Go to website"
|
||||
onClick={() => window.open(WEB_URL, "_blank", "noopener,noreferrer")}
|
||||
>
|
||||
<ExternalLink size={15} />
|
||||
</IconButton>
|
||||
<IconButton label="Sign out" onClick={onLogout}>
|
||||
<LogOut size={15} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</header>
|
||||
<main className="layout__content">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
.list-toolbar {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.list-toolbar .btn--primary {
|
||||
gap: 0.4rem;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Filter } from "lucide-react";
|
||||
import type { Category, VerificationStatus } from "../lib/types";
|
||||
import "./ListToolbar.css";
|
||||
|
||||
export interface ListFilterValues {
|
||||
query: string;
|
||||
status: "all" | VerificationStatus;
|
||||
categoryId: string;
|
||||
}
|
||||
|
||||
interface ListToolbarProps {
|
||||
draft: ListFilterValues;
|
||||
onDraftChange: (next: ListFilterValues) => void;
|
||||
onFilter: () => void;
|
||||
categories: Category[];
|
||||
searchPlaceholder?: string;
|
||||
filtering?: boolean;
|
||||
}
|
||||
|
||||
export function ListToolbar({
|
||||
draft,
|
||||
onDraftChange,
|
||||
onFilter,
|
||||
categories,
|
||||
searchPlaceholder = "Search…",
|
||||
filtering = false,
|
||||
}: ListToolbarProps) {
|
||||
return (
|
||||
<div className="toolbar list-toolbar">
|
||||
<input
|
||||
className="search-input"
|
||||
type="search"
|
||||
placeholder={searchPlaceholder}
|
||||
value={draft.query}
|
||||
onChange={(e) => onDraftChange({ ...draft, query: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
onFilter();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<select
|
||||
className="filter-select"
|
||||
value={draft.status}
|
||||
onChange={(e) =>
|
||||
onDraftChange({
|
||||
...draft,
|
||||
status: e.target.value as ListFilterValues["status"],
|
||||
})
|
||||
}
|
||||
aria-label="Filter by status"
|
||||
>
|
||||
<option value="all">All statuses</option>
|
||||
<option value="PENDING">Pending</option>
|
||||
<option value="APPROVED">Approved</option>
|
||||
<option value="REJECTED">Rejected</option>
|
||||
</select>
|
||||
<select
|
||||
className="filter-select"
|
||||
value={draft.categoryId}
|
||||
onChange={(e) =>
|
||||
onDraftChange({ ...draft, categoryId: e.target.value })
|
||||
}
|
||||
aria-label="Filter by category"
|
||||
>
|
||||
<option value="">All categories</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id}>
|
||||
{category.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--primary"
|
||||
onClick={onFilter}
|
||||
disabled={filtering}
|
||||
>
|
||||
<Filter size={15} />
|
||||
Filter
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.field__label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.field__hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.field-input,
|
||||
.field-textarea,
|
||||
.field-select {
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
color: var(--gray-800);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.field-input:focus,
|
||||
.field-textarea:focus,
|
||||
.field-select:focus {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.field-textarea {
|
||||
min-height: 110px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.multiselect {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.multiselect__control {
|
||||
width: 100%;
|
||||
min-height: 42px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.65rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.multiselect--open .multiselect__control {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.multiselect__chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.multiselect__placeholder {
|
||||
color: var(--gray-400);
|
||||
font-size: 0.875rem;
|
||||
padding: 0.2rem 0.15rem;
|
||||
}
|
||||
|
||||
.multiselect__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.2rem 0.45rem;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.multiselect__chip-remove {
|
||||
display: inline-flex;
|
||||
cursor: pointer;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.multiselect__chip-remove:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.multiselect__chevron {
|
||||
color: var(--gray-400);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.multiselect__dropdown {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.multiselect__search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
color: var(--gray-400);
|
||||
}
|
||||
|
||||
.multiselect__search input {
|
||||
flex: 1;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
color: var(--gray-800);
|
||||
}
|
||||
|
||||
.multiselect__list {
|
||||
list-style: none;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.multiselect__option {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
padding: 0.55rem 0.85rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--gray-800);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.multiselect__option-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.multiselect__tree {
|
||||
position: relative;
|
||||
flex: 0 0 auto;
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
min-height: 1.4rem;
|
||||
}
|
||||
|
||||
.multiselect__tree-col {
|
||||
position: relative;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.multiselect__tree-col::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 1px;
|
||||
background: var(--gray-200);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.multiselect__tree-col.is-branch::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 50%;
|
||||
height: 1px;
|
||||
background: var(--gray-200);
|
||||
}
|
||||
|
||||
.multiselect__option-label {
|
||||
min-width: 0;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.multiselect__option:hover,
|
||||
.multiselect__option.is-selected {
|
||||
background: var(--blue-soft);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.multiselect__option:hover .multiselect__tree-col::before,
|
||||
.multiselect__option:hover .multiselect__tree-col.is-branch::after,
|
||||
.multiselect__option.is-selected .multiselect__tree-col::before,
|
||||
.multiselect__option.is-selected .multiselect__tree-col.is-branch::after {
|
||||
background: #b7c9e8;
|
||||
}
|
||||
|
||||
.multiselect__empty {
|
||||
padding: 0.85rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState } from "react";
|
||||
import { Check, ChevronDown, Search, X } from "lucide-react";
|
||||
import "./MultiSelect.css";
|
||||
|
||||
export interface SelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
depth?: number;
|
||||
}
|
||||
|
||||
interface MultiSelectProps {
|
||||
label: string;
|
||||
options: SelectOption[];
|
||||
value: string[];
|
||||
onChange: (value: string[]) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function MultiSelect({
|
||||
label,
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "Search categories…",
|
||||
}: MultiSelectProps) {
|
||||
const id = useId();
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const selected = useMemo(
|
||||
() => options.filter((o) => value.includes(o.value)),
|
||||
[options, value],
|
||||
);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return options;
|
||||
// Keep matches and their ancestors so hierarchy stays readable while searching
|
||||
const matched = new Set(
|
||||
options.filter((o) => o.label.toLowerCase().includes(q)).map((o) => o.value),
|
||||
);
|
||||
if (matched.size === 0) return [];
|
||||
|
||||
const indexByValue = new Map(options.map((o, i) => [o.value, i]));
|
||||
const keep = new Set<string>(matched);
|
||||
|
||||
for (const option of options) {
|
||||
if (!matched.has(option.value)) continue;
|
||||
const depth = option.depth ?? 0;
|
||||
if (depth === 0) continue;
|
||||
const idx = indexByValue.get(option.value) ?? 0;
|
||||
for (let i = idx - 1; i >= 0; i -= 1) {
|
||||
const ancestor = options[i];
|
||||
if ((ancestor.depth ?? 0) < depth) {
|
||||
keep.add(ancestor.value);
|
||||
if ((ancestor.depth ?? 0) === 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return options.filter((o) => keep.has(o.value));
|
||||
}, [options, query]);
|
||||
|
||||
useEffect(() => {
|
||||
function onDocClick(e: MouseEvent) {
|
||||
if (!rootRef.current?.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", onDocClick);
|
||||
return () => document.removeEventListener("mousedown", onDocClick);
|
||||
}, []);
|
||||
|
||||
function toggle(optionValue: string) {
|
||||
if (value.includes(optionValue)) {
|
||||
onChange(value.filter((v) => v !== optionValue));
|
||||
} else {
|
||||
onChange([...value, optionValue]);
|
||||
}
|
||||
}
|
||||
|
||||
function remove(optionValue: string) {
|
||||
onChange(value.filter((v) => v !== optionValue));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="field" ref={rootRef}>
|
||||
<label className="field__label" htmlFor={id}>
|
||||
{label}
|
||||
</label>
|
||||
<div className={`multiselect${open ? " multiselect--open" : ""}`}>
|
||||
<button
|
||||
type="button"
|
||||
id={id}
|
||||
className="multiselect__control"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
>
|
||||
<div className="multiselect__chips">
|
||||
{selected.length === 0 ? (
|
||||
<span className="multiselect__placeholder">Select categories</span>
|
||||
) : (
|
||||
selected.map((item) => (
|
||||
<span key={item.value} className="multiselect__chip">
|
||||
{item.label}
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className="multiselect__chip-remove"
|
||||
aria-label={`Remove ${item.label}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
remove(item.value);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
remove(item.value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<X size={12} />
|
||||
</span>
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<ChevronDown size={16} className="multiselect__chevron" />
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div className="multiselect__dropdown" role="listbox" aria-multiselectable>
|
||||
<div className="multiselect__search">
|
||||
<Search size={14} />
|
||||
<input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<ul className="multiselect__list">
|
||||
{filtered.length === 0 ? (
|
||||
<li className="multiselect__empty">No categories found</li>
|
||||
) : (
|
||||
filtered.map((option) => {
|
||||
const active = value.includes(option.value);
|
||||
const depth = option.depth ?? 0;
|
||||
return (
|
||||
<li key={option.value}>
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={active}
|
||||
className={`multiselect__option${active ? " is-selected" : ""}`}
|
||||
onClick={() => toggle(option.value)}
|
||||
>
|
||||
<span className="multiselect__option-main">
|
||||
{depth > 0 ? (
|
||||
<span
|
||||
className="multiselect__tree"
|
||||
aria-hidden
|
||||
style={{ width: `${depth * 1.35}rem` }}
|
||||
>
|
||||
{Array.from({ length: depth }, (_, level) => (
|
||||
<span
|
||||
key={level}
|
||||
className={`multiselect__tree-col${level === depth - 1 ? " is-branch" : ""}`}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="multiselect__option-label">
|
||||
{option.label}
|
||||
</span>
|
||||
</span>
|
||||
{active ? <Check size={14} /> : null}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.page-header__title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--dark-blue);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.page-header__desc {
|
||||
margin-top: 0.25rem;
|
||||
color: var(--gray-600);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.55rem 1rem;
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn__icon {
|
||||
flex-shrink: 0;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.btn--primary {
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.btn--primary:hover {
|
||||
background: var(--blue-hover);
|
||||
}
|
||||
|
||||
.btn--ghost {
|
||||
background: transparent;
|
||||
color: var(--gray-600);
|
||||
border: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.btn--ghost:hover {
|
||||
background: var(--gray-100);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.btn--danger {
|
||||
background: transparent;
|
||||
color: var(--danger);
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.btn--danger:hover {
|
||||
background: var(--danger-soft);
|
||||
}
|
||||
|
||||
.btn--sm {
|
||||
padding: 0.35rem 0.65rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.page-header {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Plus } from "lucide-react";
|
||||
import "./PageHeader.css";
|
||||
|
||||
interface PageHeaderProps {
|
||||
title: string;
|
||||
description: string;
|
||||
actionLabel?: string;
|
||||
onAction?: () => void;
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
actionLabel,
|
||||
onAction,
|
||||
}: PageHeaderProps) {
|
||||
return (
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1 className="page-header__title">{title}</h1>
|
||||
<p className="page-header__desc">{description}</p>
|
||||
</div>
|
||||
{actionLabel && onAction ? (
|
||||
<button type="button" className="btn btn--primary" onClick={onAction}>
|
||||
<Plus className="btn__icon" size={16} strokeWidth={2.5} aria-hidden />
|
||||
<span>{actionLabel.replace(/^\+\s*/, "")}</span>
|
||||
</button>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
.pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.pagination__meta {
|
||||
font-size: 0.85rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.pagination__controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.pagination__page {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--dark-blue);
|
||||
min-width: 5.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import "./Pagination.css";
|
||||
|
||||
interface PaginationProps {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
onPageChange: (page: number) => void;
|
||||
}
|
||||
|
||||
export function Pagination({
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange,
|
||||
}: PaginationProps) {
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
const safePage = Math.min(page, totalPages);
|
||||
const from = total === 0 ? 0 : (safePage - 1) * pageSize + 1;
|
||||
const to = Math.min(safePage * pageSize, total);
|
||||
|
||||
return (
|
||||
<div className="pagination">
|
||||
<p className="pagination__meta">
|
||||
{total === 0 ? "No results" : `Showing ${from}–${to} of ${total}`}
|
||||
</p>
|
||||
<div className="pagination__controls">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost btn--sm"
|
||||
onClick={() => onPageChange(safePage - 1)}
|
||||
disabled={safePage <= 1}
|
||||
aria-label="Previous page"
|
||||
>
|
||||
<ChevronLeft size={15} />
|
||||
Prev
|
||||
</button>
|
||||
<span className="pagination__page">
|
||||
Page {safePage} / {totalPages}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost btn--sm"
|
||||
onClick={() => onPageChange(safePage + 1)}
|
||||
disabled={safePage >= totalPages}
|
||||
aria-label="Next page"
|
||||
>
|
||||
Next
|
||||
<ChevronRight size={15} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Navigate, Outlet } from "react-router-dom";
|
||||
import { isAuthenticated } from "../lib/auth";
|
||||
|
||||
export function RequireAuth() {
|
||||
if (!isAuthenticated()) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
.richtext {
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.richtext__toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
padding: 0.55rem;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
background: var(--gray-50);
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap {
|
||||
min-height: 220px;
|
||||
padding: 0.9rem 1rem;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap p.is-editor-empty:first-child::before {
|
||||
content: attr(data-placeholder);
|
||||
float: left;
|
||||
color: var(--gray-400);
|
||||
pointer-events: none;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap h2 {
|
||||
font-size: 1.2rem;
|
||||
margin: 0.85rem 0 0.4rem;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap p,
|
||||
.richtext__editor .tiptap ul,
|
||||
.richtext__editor .tiptap ol,
|
||||
.richtext__editor .tiptap blockquote {
|
||||
margin: 0.45rem 0;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap ul,
|
||||
.richtext__editor .tiptap ol {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap blockquote {
|
||||
border-left: 3px solid var(--blue);
|
||||
padding-left: 0.75rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
border-radius: 4px;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-wrapper] {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
line-height: 0;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-wrapper] img {
|
||||
margin: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* Resize chrome only when the image is selected (or actively resizing) */
|
||||
.richtext__editor .tiptap [data-resize-handle] {
|
||||
position: absolute;
|
||||
background: var(--blue);
|
||||
border: 1px solid var(--white);
|
||||
border-radius: 2px;
|
||||
z-index: 10;
|
||||
box-shadow: 0 0 0 1px rgba(11, 31, 58, 0.15);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-container].ProseMirror-selectednode [data-resize-handle],
|
||||
.richtext__editor .tiptap [data-resize-state="true"] [data-resize-handle] {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle]:hover {
|
||||
background: var(--blue-hover);
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="top-left"],
|
||||
.richtext__editor .tiptap [data-resize-handle="top-right"],
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom-left"],
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom-right"] {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="top-left"] {
|
||||
top: -4px;
|
||||
left: -4px;
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="top-right"] {
|
||||
top: -4px;
|
||||
right: -4px;
|
||||
cursor: nesw-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom-left"] {
|
||||
bottom: -4px;
|
||||
left: -4px;
|
||||
cursor: nesw-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom-right"] {
|
||||
bottom: -4px;
|
||||
right: -4px;
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="top"],
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom"] {
|
||||
height: 6px;
|
||||
left: 8px;
|
||||
right: 8px;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="top"] {
|
||||
top: -3px;
|
||||
cursor: ns-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="bottom"] {
|
||||
bottom: -3px;
|
||||
cursor: ns-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="left"],
|
||||
.richtext__editor .tiptap [data-resize-handle="right"] {
|
||||
width: 6px;
|
||||
top: 8px;
|
||||
bottom: 8px;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="left"] {
|
||||
left: -3px;
|
||||
cursor: ew-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-handle="right"] {
|
||||
right: -3px;
|
||||
cursor: ew-resize;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-container].ProseMirror-selectednode [data-resize-wrapper],
|
||||
.richtext__editor .tiptap [data-resize-state="true"] [data-resize-wrapper] {
|
||||
outline: 1px solid var(--blue);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap [data-resize-container].ProseMirror-selectednode {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.richtext__editor .tiptap a {
|
||||
color: var(--blue);
|
||||
text-decoration: underline;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useRef } from "react";
|
||||
import { EditorContent, useEditor } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import Placeholder from "@tiptap/extension-placeholder";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import {
|
||||
Bold,
|
||||
Heading2,
|
||||
ImagePlus,
|
||||
Italic,
|
||||
Link2,
|
||||
List,
|
||||
ListOrdered,
|
||||
Quote,
|
||||
} from "lucide-react";
|
||||
import { IconButton } from "./IconButton";
|
||||
import "./RichTextEditor.css";
|
||||
|
||||
interface RichTextEditorProps {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (html: string) => void;
|
||||
placeholder?: string;
|
||||
allowImages?: boolean;
|
||||
}
|
||||
|
||||
export function RichTextEditor({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "Write content…",
|
||||
allowImages = true,
|
||||
}: RichTextEditorProps) {
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
...(allowImages
|
||||
? [
|
||||
Image.configure({
|
||||
allowBase64: true,
|
||||
resize: {
|
||||
enabled: true,
|
||||
directions: [
|
||||
"top",
|
||||
"bottom",
|
||||
"left",
|
||||
"right",
|
||||
"top-left",
|
||||
"top-right",
|
||||
"bottom-left",
|
||||
"bottom-right",
|
||||
],
|
||||
minWidth: 48,
|
||||
minHeight: 48,
|
||||
alwaysPreserveAspectRatio: true,
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
Link.configure({ openOnClick: false }),
|
||||
Placeholder.configure({ placeholder }),
|
||||
],
|
||||
content: value,
|
||||
immediatelyRender: false,
|
||||
onUpdate: ({ editor: ed }) => onChange(ed.getHTML()),
|
||||
});
|
||||
|
||||
function insertImage(file: File | undefined) {
|
||||
if (!file || !editor || !allowImages) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.setImage({ src: String(reader.result) })
|
||||
.run();
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function setLink() {
|
||||
if (!editor) return;
|
||||
const previous = editor.getAttributes("link").href as string | undefined;
|
||||
const url = window.prompt("URL", previous ?? "https://");
|
||||
if (url === null) return;
|
||||
if (url === "") {
|
||||
editor.chain().focus().extendMarkRange("link").unsetLink().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
|
||||
}
|
||||
|
||||
if (!editor) return null;
|
||||
|
||||
return (
|
||||
<div className="field">
|
||||
<span className="field__label">{label}</span>
|
||||
<div className="richtext">
|
||||
<div className="richtext__toolbar">
|
||||
<IconButton
|
||||
label="Bold"
|
||||
variant={editor.isActive("bold") ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleBold().run()}
|
||||
>
|
||||
<Bold size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Italic"
|
||||
variant={editor.isActive("italic") ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleItalic().run()}
|
||||
>
|
||||
<Italic size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Heading"
|
||||
variant={editor.isActive("heading", { level: 2 }) ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
|
||||
>
|
||||
<Heading2 size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Bullet list"
|
||||
variant={editor.isActive("bulletList") ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleBulletList().run()}
|
||||
>
|
||||
<List size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Numbered list"
|
||||
variant={editor.isActive("orderedList") ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleOrderedList().run()}
|
||||
>
|
||||
<ListOrdered size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Quote"
|
||||
variant={editor.isActive("blockquote") ? "primary" : "default"}
|
||||
onClick={() => editor.chain().focus().toggleBlockquote().run()}
|
||||
>
|
||||
<Quote size={15} />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
label="Link"
|
||||
variant={editor.isActive("link") ? "primary" : "default"}
|
||||
onClick={setLink}
|
||||
>
|
||||
<Link2 size={15} />
|
||||
</IconButton>
|
||||
{allowImages ? (
|
||||
<>
|
||||
<IconButton
|
||||
label="Insert image"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
<ImagePlus size={15} />
|
||||
</IconButton>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
insertImage(e.target.files?.[0]);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
<EditorContent editor={editor} className="richtext__editor" />
|
||||
</div>
|
||||
<p className="field__hint">
|
||||
{allowImages
|
||||
? "Click an image to select it, then drag the handles to resize."
|
||||
: "Images are not allowed in this text. Use the gallery below."}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { IconButton } from "./IconButton";
|
||||
|
||||
interface RowActionsProps {
|
||||
onEdit?: () => void;
|
||||
onDelete?: () => void;
|
||||
}
|
||||
|
||||
export function RowActions({ onEdit, onDelete }: RowActionsProps) {
|
||||
return (
|
||||
<div className="row-actions">
|
||||
<IconButton label="Edit" onClick={onEdit}>
|
||||
<Pencil size={15} />
|
||||
</IconButton>
|
||||
<IconButton label="Delete" variant="danger" onClick={onDelete}>
|
||||
<Trash2 size={15} />
|
||||
</IconButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
.sidebar {
|
||||
width: var(--sidebar-width);
|
||||
min-height: 100vh;
|
||||
background: var(--dark-blue);
|
||||
color: var(--white);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1.5rem 1rem;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar__brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0 0.5rem 1.75rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.sidebar__mark {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.sidebar__name {
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.sidebar__role {
|
||||
font-size: 0.72rem;
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
font-weight: 500;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.sidebar__nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar__link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem 0.75rem;
|
||||
border-radius: var(--radius);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
transition: background 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
.sidebar__link:hover {
|
||||
background: var(--dark-blue-mid);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.sidebar__link--active {
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.sidebar__icon {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font-size: 0.68rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.sidebar__link--active .sidebar__icon {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.sidebar__footer {
|
||||
padding: 1rem 0.75rem 0.25rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.sidebar__footer-label {
|
||||
font-size: 0.7rem;
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
.sidebar__footer-user {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
margin-top: 0.15rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.sidebar__footer-link {
|
||||
display: inline-block;
|
||||
margin-top: 0.55rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--blue);
|
||||
}
|
||||
|
||||
.sidebar__footer-link:hover {
|
||||
color: #7eb0ff;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
min-height: auto;
|
||||
position: relative;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.sidebar__brand {
|
||||
padding-bottom: 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.sidebar__nav {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sidebar__footer {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NavLink } from "react-router-dom";
|
||||
import { Building2, FileText, Home, Newspaper } from "lucide-react";
|
||||
import { getCurrentUser } from "../lib/auth";
|
||||
import { WEB_URL } from "../lib/config";
|
||||
import "./Sidebar.css";
|
||||
|
||||
const navItems = [
|
||||
{ to: "/", label: "Home", icon: Home, end: true },
|
||||
{ to: "/blog", label: "Blog", icon: Newspaper },
|
||||
{ to: "/reportage", label: "Reportage", icon: FileText },
|
||||
{ to: "/brands", label: "Brands", icon: Building2 },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
const user = getCurrentUser();
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar__brand">
|
||||
<span className="sidebar__mark">NT</span>
|
||||
<div>
|
||||
<p className="sidebar__name">NovinTrades</p>
|
||||
<p className="sidebar__role">Super Admin</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar__nav" aria-label="Main">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
end={item.end}
|
||||
className={({ isActive }) =>
|
||||
`sidebar__link${isActive ? " sidebar__link--active" : ""}`
|
||||
}
|
||||
>
|
||||
<span className="sidebar__icon" aria-hidden>
|
||||
<item.icon size={14} />
|
||||
</span>
|
||||
{item.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar__footer">
|
||||
<p className="sidebar__footer-label">Signed in as</p>
|
||||
<p className="sidebar__footer-user">
|
||||
{user?.email ?? "admin@novintrades.com"}
|
||||
</p>
|
||||
<a
|
||||
className="sidebar__footer-link"
|
||||
href={WEB_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Go To Website
|
||||
</a>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { VerificationStatus } from "../lib/types";
|
||||
import { verificationLabel } from "../lib/format";
|
||||
|
||||
interface StatusBadgeProps {
|
||||
status: VerificationStatus;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export function StatusBadge({ status, onClick }: StatusBadgeProps) {
|
||||
const tone = status.toLowerCase();
|
||||
const label = verificationLabel(status);
|
||||
|
||||
if (onClick) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`badge badge--${tone} badge--clickable`}
|
||||
onClick={onClick}
|
||||
aria-label={`Change status (current: ${label})`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return <span className={`badge badge--${tone}`}>{label}</span>;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
.status-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 100;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
background: rgba(11, 31, 58, 0.45);
|
||||
}
|
||||
|
||||
.status-modal__panel {
|
||||
width: min(440px, 100%);
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.15rem;
|
||||
}
|
||||
|
||||
.status-modal__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.status-modal__title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.status-modal__subtitle {
|
||||
margin-top: 0.2rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.status-modal__options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.status-modal__option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.75rem 0.85rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
text-align: left;
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.status-modal__option:hover:not(:disabled) {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
|
||||
.status-modal__option:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.status-modal__option.is-active {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
|
||||
.status-modal__option-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-modal__option--approved .status-modal__option-icon {
|
||||
background: var(--success-soft);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.status-modal__option--rejected .status-modal__option-icon {
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.status-modal__option--pending .status-modal__option-icon {
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
}
|
||||
|
||||
.status-modal__option-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.status-modal__option-text strong {
|
||||
font-size: 0.9rem;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.status-modal__option-text small {
|
||||
font-size: 0.75rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.status-modal__current {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
color: var(--blue);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.status-modal__error {
|
||||
margin-top: 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--danger);
|
||||
background: var(--danger-soft);
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.status-modal__hint,
|
||||
.status-modal__footer {
|
||||
margin-top: 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.status-modal__footer strong {
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Check, Clock, X } from "lucide-react";
|
||||
import type { VerificationStatus } from "../lib/types";
|
||||
import { verificationLabel } from "../lib/format";
|
||||
import "./StatusModal.css";
|
||||
|
||||
const OPTIONS: {
|
||||
value: VerificationStatus;
|
||||
label: string;
|
||||
description: string;
|
||||
icon: typeof Check;
|
||||
}[] = [
|
||||
{
|
||||
value: "APPROVED",
|
||||
label: "Approve",
|
||||
description: "Mark as approved and visible when published.",
|
||||
icon: Check,
|
||||
},
|
||||
{
|
||||
value: "REJECTED",
|
||||
label: "Reject",
|
||||
description: "Mark as rejected.",
|
||||
icon: X,
|
||||
},
|
||||
{
|
||||
value: "PENDING",
|
||||
label: "Pend",
|
||||
description: "Keep waiting for review.",
|
||||
icon: Clock,
|
||||
},
|
||||
];
|
||||
|
||||
interface StatusModalProps {
|
||||
title: string;
|
||||
current: VerificationStatus;
|
||||
saving?: boolean;
|
||||
error?: string;
|
||||
onSelect: (status: VerificationStatus) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function StatusModal({
|
||||
title,
|
||||
current,
|
||||
saving = false,
|
||||
error = "",
|
||||
onSelect,
|
||||
onClose,
|
||||
}: StatusModalProps) {
|
||||
return (
|
||||
<div
|
||||
className="status-modal"
|
||||
role="dialog"
|
||||
aria-modal
|
||||
aria-labelledby="status-modal-title"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="status-modal__panel"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className="status-modal__header">
|
||||
<div>
|
||||
<h2 id="status-modal-title" className="status-modal__title">
|
||||
Change status
|
||||
</h2>
|
||||
<p className="status-modal__subtitle">{title}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost btn--sm"
|
||||
onClick={onClose}
|
||||
disabled={saving}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="status-modal__options">
|
||||
{OPTIONS.map((option) => {
|
||||
const Icon = option.icon;
|
||||
const active = current === option.value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
className={`status-modal__option status-modal__option--${option.value.toLowerCase()}${active ? " is-active" : ""}`}
|
||||
onClick={() => onSelect(option.value)}
|
||||
disabled={saving || active}
|
||||
>
|
||||
<span className="status-modal__option-icon" aria-hidden>
|
||||
<Icon size={16} />
|
||||
</span>
|
||||
<span className="status-modal__option-text">
|
||||
<strong>{option.label}</strong>
|
||||
<small>{option.description}</small>
|
||||
</span>
|
||||
{active ? (
|
||||
<span className="status-modal__current">Current</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{error ? <p className="status-modal__error">{error}</p> : null}
|
||||
{saving ? <p className="status-modal__hint">Saving…</p> : null}
|
||||
|
||||
<p className="status-modal__footer">
|
||||
Current: <strong>{verificationLabel(current)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
.tag-input {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
min-height: 42px;
|
||||
padding: 0.4rem 0.55rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
}
|
||||
|
||||
.tag-input:focus-within {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.tag-input__chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.2rem 0.45rem;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tag-input__remove {
|
||||
display: inline-flex;
|
||||
color: inherit;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
.tag-input__remove:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tag-input__field {
|
||||
flex: 1;
|
||||
min-width: 140px;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
color: var(--gray-800);
|
||||
padding: 0.2rem 0.15rem;
|
||||
}
|
||||
|
||||
.tag-input__field::placeholder {
|
||||
color: var(--gray-400);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useState, type KeyboardEvent } from "react";
|
||||
import { X } from "lucide-react";
|
||||
import "./TagInput.css";
|
||||
|
||||
interface TagInputProps {
|
||||
label: string;
|
||||
value: string[];
|
||||
onChange: (value: string[]) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function TagInput({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "Type a tag and press Enter",
|
||||
}: TagInputProps) {
|
||||
const [draft, setDraft] = useState("");
|
||||
|
||||
function addTag(raw: string) {
|
||||
const tag = raw.trim().replace(/^#/, "");
|
||||
if (!tag) return;
|
||||
if (value.some((item) => item.toLowerCase() === tag.toLowerCase())) {
|
||||
setDraft("");
|
||||
return;
|
||||
}
|
||||
onChange([...value, tag]);
|
||||
setDraft("");
|
||||
}
|
||||
|
||||
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
|
||||
if (e.key === "Enter" || e.key === ",") {
|
||||
e.preventDefault();
|
||||
addTag(draft);
|
||||
} else if (e.key === "Backspace" && !draft && value.length > 0) {
|
||||
onChange(value.slice(0, -1));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="field">
|
||||
<label className="field__label">{label}</label>
|
||||
<div className="tag-input">
|
||||
{value.map((tag) => (
|
||||
<span key={tag} className="tag-input__chip">
|
||||
{tag}
|
||||
<button
|
||||
type="button"
|
||||
className="tag-input__remove"
|
||||
aria-label={`Remove ${tag}`}
|
||||
onClick={() => onChange(value.filter((item) => item !== tag))}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
<input
|
||||
className="tag-input__field"
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onBlur={() => addTag(draft)}
|
||||
placeholder={value.length === 0 ? placeholder : "Add another…"}
|
||||
/>
|
||||
</div>
|
||||
<p className="field__hint">Press Enter to add a tag.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
.title-preview {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
min-width: 220px;
|
||||
max-width: 440px;
|
||||
}
|
||||
|
||||
.title-preview__media {
|
||||
flex: 0 0 60px;
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
max-height: 60px;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
background: var(--gray-100);
|
||||
border: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.title-preview__media img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 60px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.title-preview__placeholder {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(135deg, var(--gray-100), var(--gray-200));
|
||||
}
|
||||
|
||||
.title-preview__body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
|
||||
.title-preview__title {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
color: var(--dark-blue);
|
||||
line-height: 1.35;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 1;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.title-preview__abstract {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.35;
|
||||
color: var(--gray-600);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import "./TitlePreviewCell.css";
|
||||
|
||||
interface TitlePreviewCellProps {
|
||||
title: string;
|
||||
abstract?: string | null;
|
||||
imageUrl?: string | null;
|
||||
}
|
||||
|
||||
export function TitlePreviewCell({
|
||||
title,
|
||||
abstract,
|
||||
imageUrl,
|
||||
}: TitlePreviewCellProps) {
|
||||
return (
|
||||
<div className="title-preview">
|
||||
<div className="title-preview__media" aria-hidden={!imageUrl}>
|
||||
{imageUrl ? (
|
||||
<img src={imageUrl} alt="" />
|
||||
) : (
|
||||
<span className="title-preview__placeholder" />
|
||||
)}
|
||||
</div>
|
||||
<div className="title-preview__body">
|
||||
<p className="title-preview__title">{title}</p>
|
||||
<p className="title-preview__abstract">
|
||||
{abstract?.trim() || "No abstract"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export const countries = [
|
||||
"Iran",
|
||||
"UAE",
|
||||
"Turkey",
|
||||
"Saudi Arabia",
|
||||
"Qatar",
|
||||
"Oman",
|
||||
"Germany",
|
||||
"China",
|
||||
"India",
|
||||
"Other",
|
||||
];
|
||||
@@ -0,0 +1,160 @@
|
||||
:root {
|
||||
--blue: #1a6cf0;
|
||||
--blue-hover: #1558c9;
|
||||
--blue-soft: #e8f0fe;
|
||||
--dark-blue: #0b1f3a;
|
||||
--dark-blue-mid: #132a4a;
|
||||
--white: #ffffff;
|
||||
--gray-50: #f5f7fa;
|
||||
--gray-100: #eef1f6;
|
||||
--gray-200: #dde3ec;
|
||||
--gray-400: #8b97a8;
|
||||
--gray-600: #5a6577;
|
||||
--gray-800: #1f2937;
|
||||
--danger: #d64545;
|
||||
--danger-soft: #fdecec;
|
||||
--success: #1f9d6c;
|
||||
--success-soft: #e6f7f0;
|
||||
--sidebar-width: 240px;
|
||||
--radius: 6px;
|
||||
--font: "Plus Jakarta Sans", sans-serif;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: var(--font);
|
||||
background: var(--gray-50);
|
||||
color: var(--gray-800);
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.field__label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.field__hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.field-input,
|
||||
.field-textarea,
|
||||
.field-select {
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
background: var(--white);
|
||||
color: var(--gray-800);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.field-input:focus,
|
||||
.field-textarea:focus,
|
||||
.field-select:focus {
|
||||
border-color: var(--blue);
|
||||
}
|
||||
|
||||
.field-textarea {
|
||||
min-height: 110px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.55rem 1rem;
|
||||
border-radius: var(--radius);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn--primary {
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.btn--primary:hover {
|
||||
background: var(--blue-hover);
|
||||
}
|
||||
|
||||
.btn--ghost {
|
||||
background: transparent;
|
||||
color: var(--gray-600);
|
||||
border: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.btn--ghost:hover {
|
||||
background: var(--gray-100);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.btn--danger {
|
||||
background: transparent;
|
||||
color: var(--danger);
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.btn--danger:hover {
|
||||
background: var(--danger-soft);
|
||||
}
|
||||
|
||||
.btn--sm {
|
||||
padding: 0.35rem 0.65rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function parseError(response: Response): Promise<string> {
|
||||
try {
|
||||
const data = (await response.json()) as { error?: unknown };
|
||||
if (typeof data.error === "string") return data.error;
|
||||
return response.statusText || "Request failed";
|
||||
} catch {
|
||||
return response.statusText || "Request failed";
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<T> {
|
||||
const response = await fetch(path, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(response.status, await parseError(response));
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { AuthUser } from "./types";
|
||||
|
||||
const AUTH_KEY = "novintrades_admin_session";
|
||||
|
||||
interface Session {
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
export function getSession(): Session | null {
|
||||
const raw = localStorage.getItem(AUTH_KEY);
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as Session;
|
||||
} catch {
|
||||
localStorage.removeItem(AUTH_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return getSession() !== null;
|
||||
}
|
||||
|
||||
export function getCurrentUser(): AuthUser | null {
|
||||
return getSession()?.user ?? null;
|
||||
}
|
||||
|
||||
export function loginSession(user: AuthUser): void {
|
||||
localStorage.setItem(AUTH_KEY, JSON.stringify({ user }));
|
||||
}
|
||||
|
||||
export function logoutSession(): void {
|
||||
localStorage.removeItem(AUTH_KEY);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { SelectOption } from "../components/MultiSelect";
|
||||
import type { Category } from "./types";
|
||||
|
||||
/** Flatten categories into tree order with depth for indented multi-select. */
|
||||
export function flattenCategoryOptions(
|
||||
categories: Category[],
|
||||
): SelectOption[] {
|
||||
const byParent = new Map<string | null, Category[]>();
|
||||
|
||||
for (const category of categories) {
|
||||
const key = category.parentId;
|
||||
const list = byParent.get(key) ?? [];
|
||||
list.push(category);
|
||||
byParent.set(key, list);
|
||||
}
|
||||
|
||||
for (const list of byParent.values()) {
|
||||
list.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
const options: SelectOption[] = [];
|
||||
|
||||
function walk(parentId: string | null, depth: number) {
|
||||
for (const category of byParent.get(parentId) ?? []) {
|
||||
options.push({
|
||||
value: category.id,
|
||||
label: category.name,
|
||||
depth,
|
||||
});
|
||||
walk(category.id, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
walk(null, 0);
|
||||
return options;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/** Public website URL (override with VITE_WEB_URL). */
|
||||
export const WEB_URL =
|
||||
import.meta.env.VITE_WEB_URL ?? "http://novintrades.local:5174";
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Category, VerificationStatus } from "./types";
|
||||
|
||||
export function formatDate(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "—";
|
||||
const day = date.toLocaleDateString("en-CA");
|
||||
const time = date.toLocaleTimeString("en-GB", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
return `${day} ${time}`;
|
||||
}
|
||||
|
||||
export function categoryNames(
|
||||
links: { category: Pick<Category, "name"> }[],
|
||||
): string {
|
||||
if (!links.length) return "—";
|
||||
return links.map((link) => link.category.name).join(", ");
|
||||
}
|
||||
|
||||
export function verificationLabel(status: VerificationStatus): string {
|
||||
switch (status) {
|
||||
case "APPROVED":
|
||||
return "Approved";
|
||||
case "REJECTED":
|
||||
return "Rejected";
|
||||
default:
|
||||
return "Pending";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export const MAX_IMAGE_BYTES = 250 * 1024;
|
||||
|
||||
export function maxImageLabel(): string {
|
||||
return `${Math.round(MAX_IMAGE_BYTES / 1024)}KB`;
|
||||
}
|
||||
|
||||
export function assertClientImageSize(bytes: number): void {
|
||||
if (bytes > MAX_IMAGE_BYTES) {
|
||||
throw new Error(`Image must be ${maxImageLabel()} or smaller`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function dataUrlToBlob(dataUrl: string): Promise<Blob> {
|
||||
const response = await fetch(dataUrl);
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
export async function canvasToJpegBlob(
|
||||
canvas: HTMLCanvasElement,
|
||||
quality = 0.85,
|
||||
): Promise<Blob> {
|
||||
const blob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob((result) => resolve(result), "image/jpeg", quality);
|
||||
});
|
||||
if (!blob) throw new Error("Could not encode image");
|
||||
return blob;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ListFilterValues } from "../components/ListToolbar";
|
||||
import type { VerificationStatus } from "./types";
|
||||
|
||||
export const PAGE_SIZE = 10;
|
||||
|
||||
export const emptyFilters: ListFilterValues = {
|
||||
query: "",
|
||||
status: "all",
|
||||
categoryId: "",
|
||||
};
|
||||
|
||||
export function matchesListFilters<
|
||||
T extends {
|
||||
title: string;
|
||||
verificationStatus: VerificationStatus;
|
||||
categories: { categoryId: string }[];
|
||||
},
|
||||
>(
|
||||
row: T,
|
||||
filters: ListFilterValues,
|
||||
extraSearch?: string,
|
||||
): boolean {
|
||||
const q = filters.query.trim().toLowerCase();
|
||||
const haystack = `${row.title} ${extraSearch ?? ""}`.toLowerCase();
|
||||
const matchesQuery = !q || haystack.includes(q);
|
||||
const matchesStatus =
|
||||
filters.status === "all" || row.verificationStatus === filters.status;
|
||||
const matchesCategory =
|
||||
!filters.categoryId ||
|
||||
row.categories.some((link) => link.categoryId === filters.categoryId);
|
||||
return matchesQuery && matchesStatus && matchesCategory;
|
||||
}
|
||||
|
||||
export function paginateRows<T>(rows: T[], page: number, pageSize = PAGE_SIZE) {
|
||||
const total = rows.length;
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
const safePage = Math.min(Math.max(1, page), totalPages);
|
||||
const start = (safePage - 1) * pageSize;
|
||||
return {
|
||||
page: safePage,
|
||||
total,
|
||||
items: rows.slice(start, start + pageSize),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { api, ApiError } from "./api";
|
||||
import { assertClientImageSize } from "./image";
|
||||
import type {
|
||||
AuthUser,
|
||||
Blog,
|
||||
Brand,
|
||||
BrandContact,
|
||||
Category,
|
||||
Reportage,
|
||||
VerificationStatus,
|
||||
} from "./types";
|
||||
|
||||
export function login(email: string, password: string) {
|
||||
return api<{ user: AuthUser }>("/api/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
}
|
||||
|
||||
export function listCategories() {
|
||||
return api<Category[]>("/api/categories");
|
||||
}
|
||||
|
||||
export function listBlogs() {
|
||||
return api<Blog[]>("/api/blogs");
|
||||
}
|
||||
|
||||
export function getBlog(id: string) {
|
||||
return api<Blog>(`/api/blogs/${id}`);
|
||||
}
|
||||
|
||||
export function createBlog(input: {
|
||||
title: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
tags?: string[];
|
||||
categoryIds?: string[];
|
||||
authorId: string;
|
||||
verificationStatus?: VerificationStatus;
|
||||
}) {
|
||||
return api<Blog>("/api/blogs", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateBlog(
|
||||
id: string,
|
||||
input: {
|
||||
title?: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
tags?: string[];
|
||||
categoryIds?: string[];
|
||||
verificationStatus?: VerificationStatus;
|
||||
publishedAt?: string | null;
|
||||
},
|
||||
) {
|
||||
return api<Blog>(`/api/blogs/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function listReportages() {
|
||||
return api<Reportage[]>("/api/reportages");
|
||||
}
|
||||
|
||||
export function getReportage(id: string) {
|
||||
return api<Reportage>(`/api/reportages/${id}`);
|
||||
}
|
||||
|
||||
export function createReportage(input: {
|
||||
title: string;
|
||||
businessOwner: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
tags?: string[];
|
||||
categoryIds?: string[];
|
||||
authorId: string;
|
||||
verificationStatus?: VerificationStatus;
|
||||
}) {
|
||||
return api<Reportage>("/api/reportages", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateReportage(
|
||||
id: string,
|
||||
input: {
|
||||
title?: string;
|
||||
businessOwner?: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
tags?: string[];
|
||||
categoryIds?: string[];
|
||||
verificationStatus?: VerificationStatus;
|
||||
publishedAt?: string | null;
|
||||
},
|
||||
) {
|
||||
return api<Reportage>(`/api/reportages/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function listBrands() {
|
||||
return api<Brand[]>("/api/brands");
|
||||
}
|
||||
|
||||
export function getBrand(id: string) {
|
||||
return api<Brand>(`/api/brands/${id}`);
|
||||
}
|
||||
|
||||
export function createBrand(input: {
|
||||
title: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
galleryUrls?: string[];
|
||||
tags?: string[];
|
||||
country: string;
|
||||
city?: string;
|
||||
address?: string;
|
||||
contacts?: BrandContact[];
|
||||
categoryIds?: string[];
|
||||
authorId: string;
|
||||
verificationStatus?: VerificationStatus;
|
||||
}) {
|
||||
return api<Brand>("/api/brands", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function updateBrand(
|
||||
id: string,
|
||||
input: {
|
||||
title?: string;
|
||||
abstract?: string;
|
||||
content?: string;
|
||||
imageUrl?: string | null;
|
||||
galleryUrls?: string[];
|
||||
tags?: string[];
|
||||
country?: string;
|
||||
city?: string;
|
||||
address?: string;
|
||||
contacts?: BrandContact[];
|
||||
categoryIds?: string[];
|
||||
verificationStatus?: VerificationStatus;
|
||||
publishedAt?: string | null;
|
||||
},
|
||||
) {
|
||||
return api<Brand>(`/api/brands/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export async function uploadImage(
|
||||
file: Blob,
|
||||
folder: string,
|
||||
): Promise<{ url: string; key: string; size: number }> {
|
||||
assertClientImageSize(file.size);
|
||||
|
||||
const form = new FormData();
|
||||
const filename =
|
||||
file instanceof File && file.name
|
||||
? file.name
|
||||
: `image.${file.type.includes("png") ? "png" : "jpg"}`;
|
||||
form.append("file", file, filename);
|
||||
|
||||
const response = await fetch(
|
||||
`/api/uploads?folder=${encodeURIComponent(folder)}`,
|
||||
{
|
||||
method: "POST",
|
||||
body: form,
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
let message = "Upload failed";
|
||||
try {
|
||||
const data = (await response.json()) as { error?: string };
|
||||
if (data.error) message = data.error;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw new ApiError(response.status, message);
|
||||
}
|
||||
|
||||
return (await response.json()) as {
|
||||
url: string;
|
||||
key: string;
|
||||
size: number;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
export type VerificationStatus = "PENDING" | "APPROVED" | "REJECTED";
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
parentId: string | null;
|
||||
children?: Category[];
|
||||
}
|
||||
|
||||
export interface CategoryLink {
|
||||
categoryId: string;
|
||||
category: Category;
|
||||
}
|
||||
|
||||
export interface Blog {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
abstract: string | null;
|
||||
content: string;
|
||||
imageUrl: string | null;
|
||||
tags: string[];
|
||||
verificationStatus: VerificationStatus;
|
||||
authorId: string;
|
||||
author: AuthUser;
|
||||
categories: CategoryLink[];
|
||||
publishedAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Reportage {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
businessOwner: string;
|
||||
abstract: string | null;
|
||||
content: string;
|
||||
imageUrl: string | null;
|
||||
tags: string[];
|
||||
verificationStatus: VerificationStatus;
|
||||
authorId: string;
|
||||
author: AuthUser;
|
||||
categories: CategoryLink[];
|
||||
publishedAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface BrandContact {
|
||||
type:
|
||||
| "phone"
|
||||
| "landline"
|
||||
| "email"
|
||||
| "instagram"
|
||||
| "website"
|
||||
| "whatsapp"
|
||||
| "other";
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface Brand {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
abstract: string | null;
|
||||
content: string;
|
||||
imageUrl: string | null;
|
||||
galleryUrls: string[];
|
||||
tags: string[];
|
||||
country: string;
|
||||
city: string | null;
|
||||
address: string | null;
|
||||
contacts: BrandContact[];
|
||||
verificationStatus: VerificationStatus;
|
||||
authorId: string;
|
||||
author: AuthUser;
|
||||
categories: CategoryLink[];
|
||||
publishedAt: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { ImageCropper } from "../components/ImageCropper";
|
||||
import { MultiSelect } from "../components/MultiSelect";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { RichTextEditor } from "../components/RichTextEditor";
|
||||
import { TagInput } from "../components/TagInput";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { getCurrentUser } from "../lib/auth";
|
||||
import { flattenCategoryOptions } from "../lib/categories";
|
||||
import {
|
||||
createBlog,
|
||||
getBlog,
|
||||
listCategories,
|
||||
updateBlog,
|
||||
} from "../lib/services";
|
||||
import type { SelectOption } from "../components/MultiSelect";
|
||||
import "../styles/forms.css";
|
||||
|
||||
export function BlogNewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams();
|
||||
const isEdit = Boolean(id);
|
||||
const user = getCurrentUser();
|
||||
|
||||
const [categoryOptions, setCategoryOptions] = useState<SelectOption[]>([]);
|
||||
const [categories, setCategories] = useState<string[]>([]);
|
||||
const [title, setTitle] = useState("");
|
||||
const [image, setImage] = useState<string | null>(null);
|
||||
const [abstract, setAbstract] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [loading, setLoading] = useState(isEdit);
|
||||
const [ready, setReady] = useState(!isEdit);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await listCategories();
|
||||
if (cancelled) return;
|
||||
setCategoryOptions(flattenCategoryOptions(data));
|
||||
|
||||
if (id) {
|
||||
const blog = await getBlog(id);
|
||||
if (cancelled) return;
|
||||
setTitle(blog.title);
|
||||
setAbstract(blog.abstract ?? "");
|
||||
setContent(blog.content);
|
||||
setImage(blog.imageUrl);
|
||||
setTags(blog.tags);
|
||||
setCategories(blog.categories.map((c) => c.categoryId));
|
||||
setReady(true);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not load post.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!user) {
|
||||
setError("You must be signed in.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const payload = {
|
||||
title: title.trim(),
|
||||
abstract: abstract.trim() || undefined,
|
||||
content,
|
||||
imageUrl: image,
|
||||
tags,
|
||||
categoryIds: categories,
|
||||
};
|
||||
|
||||
if (isEdit && id) {
|
||||
await updateBlog(id, payload);
|
||||
} else {
|
||||
await createBlog({ ...payload, authorId: user.id });
|
||||
}
|
||||
navigate("/blog");
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not save post.",
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader title="Edit post" description="Loading…" />
|
||||
<div className="empty-state">
|
||||
<strong>Loading post…</strong>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader
|
||||
title={isEdit ? "Edit post" : "New post"}
|
||||
description={
|
||||
isEdit
|
||||
? "Update this blog article."
|
||||
: "Create a blog article for the website."
|
||||
}
|
||||
/>
|
||||
|
||||
<form className="form-card" onSubmit={onSubmit}>
|
||||
<div className="form-col-3">
|
||||
<ImageCropper
|
||||
label="Main image"
|
||||
value={image}
|
||||
onChange={setImage}
|
||||
aspect={1}
|
||||
folder="blogs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-col-9">
|
||||
<div className="form-stack">
|
||||
<MultiSelect
|
||||
label="Category"
|
||||
options={categoryOptions}
|
||||
value={categories}
|
||||
onChange={setCategories}
|
||||
/>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="post-title">
|
||||
Title
|
||||
</label>
|
||||
<input
|
||||
id="post-title"
|
||||
className="field-input"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Post title"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="post-abstract">
|
||||
Abstract
|
||||
</label>
|
||||
<textarea
|
||||
id="post-abstract"
|
||||
className="field-textarea"
|
||||
value={abstract}
|
||||
onChange={(e) => setAbstract(e.target.value)}
|
||||
placeholder="Short summary shown in lists and previews"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
{ready ? (
|
||||
<RichTextEditor
|
||||
key={id ?? "new"}
|
||||
label="Main content"
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write the full article…"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
<TagInput label="Tags" value={tags} onChange={setTags} />
|
||||
</div>
|
||||
|
||||
{error ? <p className="form-error">{error}</p> : null}
|
||||
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => navigate("/blog")}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn--primary"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? "Saving…" : isEdit ? "Update post" : "Save post"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { DataTable } from "../components/DataTable";
|
||||
import {
|
||||
ListToolbar,
|
||||
type ListFilterValues,
|
||||
} from "../components/ListToolbar";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { Pagination } from "../components/Pagination";
|
||||
import { RowActions } from "../components/RowActions";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
import { StatusModal } from "../components/StatusModal";
|
||||
import { TitlePreviewCell } from "../components/TitlePreviewCell";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { categoryNames, formatDate } from "../lib/format";
|
||||
import {
|
||||
emptyFilters,
|
||||
matchesListFilters,
|
||||
PAGE_SIZE,
|
||||
paginateRows,
|
||||
} from "../lib/list";
|
||||
import { listBlogs, listCategories, updateBlog } from "../lib/services";
|
||||
import type { Blog, Category, VerificationStatus } from "../lib/types";
|
||||
|
||||
export function BlogPage() {
|
||||
const navigate = useNavigate();
|
||||
const [draft, setDraft] = useState<ListFilterValues>(emptyFilters);
|
||||
const [applied, setApplied] = useState<ListFilterValues>(emptyFilters);
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<Blog[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [selected, setSelected] = useState<Blog | null>(null);
|
||||
const [savingStatus, setSavingStatus] = useState(false);
|
||||
const [statusError, setStatusError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const [posts, cats] = await Promise.all([
|
||||
listBlogs(),
|
||||
listCategories(),
|
||||
]);
|
||||
if (!cancelled) {
|
||||
setRows(posts);
|
||||
setCategories(cats);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Failed to load posts.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return rows.filter((post) => {
|
||||
const author = post.author.name ?? post.author.email;
|
||||
return matchesListFilters(post, applied, author);
|
||||
});
|
||||
}, [applied, rows]);
|
||||
|
||||
const paged = useMemo(
|
||||
() => paginateRows(filtered, page, PAGE_SIZE),
|
||||
[filtered, page],
|
||||
);
|
||||
|
||||
function applyFilters() {
|
||||
setApplied(draft);
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
async function changeStatus(next: VerificationStatus) {
|
||||
if (!selected || selected.verificationStatus === next) return;
|
||||
setSavingStatus(true);
|
||||
setStatusError("");
|
||||
try {
|
||||
const updated = await updateBlog(selected.id, {
|
||||
verificationStatus: next,
|
||||
publishedAt: next === "APPROVED" ? new Date().toISOString() : null,
|
||||
});
|
||||
setRows((prev) =>
|
||||
prev.map((row) => (row.id === updated.id ? updated : row)),
|
||||
);
|
||||
setSelected(null);
|
||||
} catch (err) {
|
||||
setStatusError(
|
||||
err instanceof ApiError ? err.message : "Failed to update status.",
|
||||
);
|
||||
} finally {
|
||||
setSavingStatus(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
<PageHeader
|
||||
title="Blog"
|
||||
description="Manage articles shown on the public website."
|
||||
actionLabel="New post"
|
||||
onAction={() => navigate("/blog/new")}
|
||||
/>
|
||||
|
||||
<ListToolbar
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onFilter={applyFilters}
|
||||
categories={categories}
|
||||
searchPlaceholder="Search posts…"
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">
|
||||
<strong>Loading posts…</strong>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="empty-state">
|
||||
<strong>Could not load posts</strong>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
) : paged.total === 0 ? (
|
||||
<div className="empty-state">
|
||||
<strong>No posts found</strong>
|
||||
<p>Try a different filter or create a new post.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DataTable<Blog>
|
||||
rows={paged.items}
|
||||
rowKey={(row) => row.id}
|
||||
columns={[
|
||||
{
|
||||
key: "title",
|
||||
header: "Title",
|
||||
render: (row) => (
|
||||
<TitlePreviewCell
|
||||
title={row.title}
|
||||
abstract={row.abstract}
|
||||
imageUrl={row.imageUrl}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "author",
|
||||
header: "Author",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{row.author.name ?? row.author.email}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "category",
|
||||
header: "Category",
|
||||
render: (row) => categoryNames(row.categories),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
header: "Status",
|
||||
render: (row) => (
|
||||
<StatusBadge
|
||||
status={row.verificationStatus}
|
||||
onClick={() => {
|
||||
setStatusError("");
|
||||
setSelected(row);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "publishedAt",
|
||||
header: "Published",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{formatDate(row.publishedAt)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
header: "",
|
||||
width: "100px",
|
||||
render: (row) => (
|
||||
<RowActions onEdit={() => navigate(`/blog/${row.id}/edit`)} />
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Pagination
|
||||
page={paged.page}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={paged.total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{selected ? (
|
||||
<StatusModal
|
||||
title={selected.title}
|
||||
current={selected.verificationStatus}
|
||||
saving={savingStatus}
|
||||
error={statusError}
|
||||
onSelect={changeStatus}
|
||||
onClose={() => {
|
||||
if (!savingStatus) setSelected(null);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import {
|
||||
ContactFields,
|
||||
createContact,
|
||||
type ContactItem,
|
||||
} from "../components/ContactFields";
|
||||
import { ImageCropper } from "../components/ImageCropper";
|
||||
import { ImageGallery } from "../components/ImageGallery";
|
||||
import { MultiSelect } from "../components/MultiSelect";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { RichTextEditor } from "../components/RichTextEditor";
|
||||
import { TagInput } from "../components/TagInput";
|
||||
import { countries } from "../data/options";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { getCurrentUser } from "../lib/auth";
|
||||
import { flattenCategoryOptions } from "../lib/categories";
|
||||
import {
|
||||
createBrand,
|
||||
getBrand,
|
||||
listCategories,
|
||||
updateBrand,
|
||||
} from "../lib/services";
|
||||
import type { BrandContact } from "../lib/types";
|
||||
import type { SelectOption } from "../components/MultiSelect";
|
||||
import "../styles/forms.css";
|
||||
|
||||
function toContactItems(contacts: BrandContact[]): ContactItem[] {
|
||||
if (!contacts.length) {
|
||||
return [createContact("phone"), createContact("email")];
|
||||
}
|
||||
return contacts.map((item) => ({
|
||||
id: `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
type: item.type,
|
||||
value: item.value,
|
||||
}));
|
||||
}
|
||||
|
||||
export function BrandNewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams();
|
||||
const isEdit = Boolean(id);
|
||||
const user = getCurrentUser();
|
||||
|
||||
const [categoryOptions, setCategoryOptions] = useState<SelectOption[]>([]);
|
||||
const [categories, setCategories] = useState<string[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [about, setAbout] = useState("");
|
||||
const [image, setImage] = useState<string | null>(null);
|
||||
const [gallery, setGallery] = useState<string[]>([]);
|
||||
const [content, setContent] = useState("");
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [country, setCountry] = useState("");
|
||||
const [city, setCity] = useState("");
|
||||
const [address, setAddress] = useState("");
|
||||
const [contacts, setContacts] = useState<ContactItem[]>([
|
||||
createContact("phone"),
|
||||
createContact("email"),
|
||||
]);
|
||||
const [error, setError] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [loading, setLoading] = useState(isEdit);
|
||||
const [ready, setReady] = useState(!isEdit);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await listCategories();
|
||||
if (cancelled) return;
|
||||
setCategoryOptions(flattenCategoryOptions(data));
|
||||
|
||||
if (id) {
|
||||
const brand = await getBrand(id);
|
||||
if (cancelled) return;
|
||||
setName(brand.title);
|
||||
setAbout(brand.abstract ?? "");
|
||||
setContent(brand.content);
|
||||
setImage(brand.imageUrl);
|
||||
setGallery(brand.galleryUrls ?? []);
|
||||
setTags(brand.tags);
|
||||
setCountry(brand.country);
|
||||
setCity(brand.city ?? "");
|
||||
setAddress(brand.address ?? "");
|
||||
setContacts(toContactItems(brand.contacts ?? []));
|
||||
setCategories(brand.categories.map((c) => c.categoryId));
|
||||
setReady(true);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not load brand.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!user) {
|
||||
setError("You must be signed in.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const payload = {
|
||||
title: name.trim(),
|
||||
abstract: about.trim() || undefined,
|
||||
content,
|
||||
imageUrl: image,
|
||||
galleryUrls: gallery,
|
||||
tags,
|
||||
country,
|
||||
city: city.trim() || undefined,
|
||||
address: address.trim() || undefined,
|
||||
contacts: contacts
|
||||
.filter((item) => item.value.trim())
|
||||
.map(({ type, value }) => ({ type, value: value.trim() })),
|
||||
categoryIds: categories,
|
||||
};
|
||||
|
||||
if (isEdit && id) {
|
||||
await updateBrand(id, payload);
|
||||
} else {
|
||||
await createBrand({ ...payload, authorId: user.id });
|
||||
}
|
||||
navigate("/brands");
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not save brand.",
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader title="Edit brand" description="Loading…" />
|
||||
<div className="empty-state">
|
||||
<strong>Loading brand…</strong>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader
|
||||
title={isEdit ? "Edit brand" : "New brand"}
|
||||
description={
|
||||
isEdit
|
||||
? "Update this business profile."
|
||||
: "Add a business profile to NovinTrades."
|
||||
}
|
||||
/>
|
||||
|
||||
<form className="form-card" onSubmit={onSubmit}>
|
||||
<div className="form-col-3">
|
||||
<ImageCropper
|
||||
label="Main image"
|
||||
value={image}
|
||||
onChange={setImage}
|
||||
aspect={1}
|
||||
folder="brands"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-col-9">
|
||||
<div className="form-stack">
|
||||
<MultiSelect
|
||||
label="Category"
|
||||
options={categoryOptions}
|
||||
value={categories}
|
||||
onChange={setCategories}
|
||||
/>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="brand-name">
|
||||
Title
|
||||
</label>
|
||||
<input
|
||||
id="brand-name"
|
||||
className="field-input"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Brand name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="brand-about">
|
||||
Abstract
|
||||
</label>
|
||||
<textarea
|
||||
id="brand-about"
|
||||
className="field-textarea"
|
||||
value={about}
|
||||
onChange={(e) => setAbout(e.target.value)}
|
||||
placeholder="Short description of the business"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
{ready ? (
|
||||
<RichTextEditor
|
||||
key={id ?? "new"}
|
||||
label="Main content"
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write the full brand story…"
|
||||
allowImages={false}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
<ImageGallery
|
||||
label="Image gallery"
|
||||
value={gallery}
|
||||
onChange={setGallery}
|
||||
folder="brands"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
<TagInput label="Tags" value={tags} onChange={setTags} />
|
||||
</div>
|
||||
|
||||
<div className="form-col-2">
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="brand-country">
|
||||
Country
|
||||
</label>
|
||||
<select
|
||||
id="brand-country"
|
||||
className="field-select"
|
||||
value={country}
|
||||
onChange={(e) => setCountry(e.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="">Select country</option>
|
||||
{countries.map((item) => (
|
||||
<option key={item} value={item}>
|
||||
{item}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-2">
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="brand-city">
|
||||
City
|
||||
</label>
|
||||
<input
|
||||
id="brand-city"
|
||||
className="field-input"
|
||||
value={city}
|
||||
onChange={(e) => setCity(e.target.value)}
|
||||
placeholder="City"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-8">
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="brand-address">
|
||||
Address
|
||||
</label>
|
||||
<input
|
||||
id="brand-address"
|
||||
className="field-input"
|
||||
value={address}
|
||||
onChange={(e) => setAddress(e.target.value)}
|
||||
placeholder="Street, building, unit"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
<ContactFields value={contacts} onChange={setContacts} />
|
||||
</div>
|
||||
|
||||
{error ? <p className="form-error">{error}</p> : null}
|
||||
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => navigate("/brands")}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn--primary"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? "Saving…" : isEdit ? "Update brand" : "Save brand"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { DataTable } from "../components/DataTable";
|
||||
import {
|
||||
ListToolbar,
|
||||
type ListFilterValues,
|
||||
} from "../components/ListToolbar";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { Pagination } from "../components/Pagination";
|
||||
import { RowActions } from "../components/RowActions";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
import { StatusModal } from "../components/StatusModal";
|
||||
import { TitlePreviewCell } from "../components/TitlePreviewCell";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { categoryNames, formatDate } from "../lib/format";
|
||||
import {
|
||||
emptyFilters,
|
||||
matchesListFilters,
|
||||
PAGE_SIZE,
|
||||
paginateRows,
|
||||
} from "../lib/list";
|
||||
import { listBrands, listCategories, updateBrand } from "../lib/services";
|
||||
import type { Brand, Category, VerificationStatus } from "../lib/types";
|
||||
|
||||
function websiteFromContacts(brand: Brand): string {
|
||||
const website = brand.contacts.find((c) => c.type === "website" && c.value);
|
||||
return website?.value || "—";
|
||||
}
|
||||
|
||||
export function BrandsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [draft, setDraft] = useState<ListFilterValues>(emptyFilters);
|
||||
const [applied, setApplied] = useState<ListFilterValues>(emptyFilters);
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<Brand[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [selected, setSelected] = useState<Brand | null>(null);
|
||||
const [savingStatus, setSavingStatus] = useState(false);
|
||||
const [statusError, setStatusError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const [items, cats] = await Promise.all([
|
||||
listBrands(),
|
||||
listCategories(),
|
||||
]);
|
||||
if (!cancelled) {
|
||||
setRows(items);
|
||||
setCategories(cats);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Failed to load brands.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return rows.filter((brand) =>
|
||||
matchesListFilters(
|
||||
brand,
|
||||
applied,
|
||||
`${brand.country} ${brand.city ?? ""} ${categoryNames(brand.categories)}`,
|
||||
),
|
||||
);
|
||||
}, [applied, rows]);
|
||||
|
||||
const paged = useMemo(
|
||||
() => paginateRows(filtered, page, PAGE_SIZE),
|
||||
[filtered, page],
|
||||
);
|
||||
|
||||
function applyFilters() {
|
||||
setApplied(draft);
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
async function changeStatus(next: VerificationStatus) {
|
||||
if (!selected || selected.verificationStatus === next) return;
|
||||
setSavingStatus(true);
|
||||
setStatusError("");
|
||||
try {
|
||||
const updated = await updateBrand(selected.id, {
|
||||
verificationStatus: next,
|
||||
publishedAt: next === "APPROVED" ? new Date().toISOString() : null,
|
||||
});
|
||||
setRows((prev) =>
|
||||
prev.map((row) => (row.id === updated.id ? updated : row)),
|
||||
);
|
||||
setSelected(null);
|
||||
} catch (err) {
|
||||
setStatusError(
|
||||
err instanceof ApiError ? err.message : "Failed to update status.",
|
||||
);
|
||||
} finally {
|
||||
setSavingStatus(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
<PageHeader
|
||||
title="Brands"
|
||||
description="Business profiles listed on NovinTrades."
|
||||
actionLabel="New brand"
|
||||
onAction={() => navigate("/brands/new")}
|
||||
/>
|
||||
|
||||
<ListToolbar
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onFilter={applyFilters}
|
||||
categories={categories}
|
||||
searchPlaceholder="Search brands…"
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">
|
||||
<strong>Loading brands…</strong>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="empty-state">
|
||||
<strong>Could not load brands</strong>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
) : paged.total === 0 ? (
|
||||
<div className="empty-state">
|
||||
<strong>No brands found</strong>
|
||||
<p>Try a different filter or create a new brand.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DataTable<Brand>
|
||||
rows={paged.items}
|
||||
rowKey={(row) => row.id}
|
||||
columns={[
|
||||
{
|
||||
key: "name",
|
||||
header: "Brand",
|
||||
render: (row) => (
|
||||
<TitlePreviewCell
|
||||
title={row.title}
|
||||
abstract={row.abstract}
|
||||
imageUrl={row.imageUrl}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "category",
|
||||
header: "Category",
|
||||
render: (row) => categoryNames(row.categories),
|
||||
},
|
||||
{
|
||||
key: "country",
|
||||
header: "Country",
|
||||
render: (row) => row.country,
|
||||
},
|
||||
{
|
||||
key: "website",
|
||||
header: "Website",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{websiteFromContacts(row)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
header: "Status",
|
||||
render: (row) => (
|
||||
<StatusBadge
|
||||
status={row.verificationStatus}
|
||||
onClick={() => {
|
||||
setStatusError("");
|
||||
setSelected(row);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "createdAt",
|
||||
header: "Created",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{formatDate(row.createdAt)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
header: "",
|
||||
width: "100px",
|
||||
render: (row) => (
|
||||
<RowActions
|
||||
onEdit={() => navigate(`/brands/${row.id}/edit`)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Pagination
|
||||
page={paged.page}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={paged.total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{selected ? (
|
||||
<StatusModal
|
||||
title={selected.title}
|
||||
current={selected.verificationStatus}
|
||||
saving={savingStatus}
|
||||
error={statusError}
|
||||
onSelect={changeStatus}
|
||||
onClose={() => {
|
||||
if (!savingStatus) setSelected(null);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
Building2,
|
||||
FileText,
|
||||
Newspaper,
|
||||
PenLine,
|
||||
} from "lucide-react";
|
||||
import { listBlogs, listBrands, listReportages } from "../lib/services";
|
||||
import "../styles/forms.css";
|
||||
|
||||
export function HomePage() {
|
||||
const [counts, setCounts] = useState({
|
||||
blog: 0,
|
||||
reportage: 0,
|
||||
brands: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [blogs, reportages, brands] = await Promise.all([
|
||||
listBlogs(),
|
||||
listReportages(),
|
||||
listBrands(),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
setCounts({
|
||||
blog: blogs.length,
|
||||
reportage: reportages.length,
|
||||
brands: brands.length,
|
||||
});
|
||||
} catch {
|
||||
// keep zeros on failure
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const tiles = [
|
||||
{
|
||||
to: "/blog",
|
||||
title: "Blog",
|
||||
description: "Articles on the public website",
|
||||
count: counts.blog,
|
||||
icon: Newspaper,
|
||||
createTo: "/blog/new",
|
||||
createLabel: "New post",
|
||||
},
|
||||
{
|
||||
to: "/reportage",
|
||||
title: "Reportage",
|
||||
description: "Brand features and editorial pieces",
|
||||
count: counts.reportage,
|
||||
icon: FileText,
|
||||
createTo: "/reportage/new",
|
||||
createLabel: "New reportage",
|
||||
},
|
||||
{
|
||||
to: "/brands",
|
||||
title: "Brands",
|
||||
description: "Business profiles on NovinTrades",
|
||||
count: counts.brands,
|
||||
icon: Building2,
|
||||
createTo: "/brands/new",
|
||||
createLabel: "New brand",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<section>
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1 className="page-header__title">Dashboard</h1>
|
||||
<p className="page-header__desc">
|
||||
Super admin overview for content and brands.
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="dashboard-grid">
|
||||
{tiles.map((tile) => {
|
||||
const Icon = tile.icon;
|
||||
return (
|
||||
<Link key={tile.to} to={tile.to} className="dash-tile">
|
||||
<span className="dash-tile__icon" aria-hidden>
|
||||
<Icon size={20} />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="dash-tile__title">{tile.title}</h2>
|
||||
<p className="dash-tile__meta">{tile.description}</p>
|
||||
</div>
|
||||
<p className="dash-tile__count">{tile.count}</p>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="dashboard-grid dashboard-grid--actions">
|
||||
{tiles.map((tile) => (
|
||||
<Link
|
||||
key={tile.createTo}
|
||||
to={tile.createTo}
|
||||
className="dash-tile dash-tile--action"
|
||||
>
|
||||
<span className="dash-tile__icon" aria-hidden>
|
||||
<PenLine size={18} />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="dash-tile__title">{tile.createLabel}</h2>
|
||||
<p className="dash-tile__meta">Create in {tile.title}</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
.login {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1.5rem;
|
||||
background:
|
||||
radial-gradient(ellipse 80% 60% at 20% 10%, var(--blue-soft) 0%, transparent 55%),
|
||||
radial-gradient(ellipse 70% 50% at 90% 90%, #dbe8fb 0%, transparent 50%),
|
||||
linear-gradient(160deg, var(--gray-50) 0%, #e8eef7 45%, var(--blue-soft) 100%);
|
||||
}
|
||||
|
||||
.login__panel {
|
||||
width: min(420px, 100%);
|
||||
background: var(--white);
|
||||
border-radius: var(--radius);
|
||||
padding: 2rem 1.75rem 1.75rem;
|
||||
border: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.login__brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.85rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.login__mark {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 700;
|
||||
border-radius: 4px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.login__title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--dark-blue);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.login__subtitle {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--gray-600);
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.login__lead {
|
||||
font-size: 0.9rem;
|
||||
color: var(--gray-600);
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.login__form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.login__error {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--danger);
|
||||
background: var(--danger-soft);
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.login__submit {
|
||||
width: 100%;
|
||||
margin-top: 0.35rem;
|
||||
padding: 0.7rem 1rem;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Navigate, useNavigate } from "react-router-dom";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { isAuthenticated, loginSession } from "../lib/auth";
|
||||
import { login } from "../lib/services";
|
||||
import "./LoginPage.css";
|
||||
|
||||
export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
if (isAuthenticated()) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!email.trim() || !password) {
|
||||
setError("Enter email and password.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const result = await login(email.trim(), password);
|
||||
loginSession(result.user);
|
||||
navigate("/", { replace: true });
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not sign in. Try again.",
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login">
|
||||
<div className="login__panel">
|
||||
<div className="login__brand">
|
||||
<span className="login__mark">NT</span>
|
||||
<div>
|
||||
<h1 className="login__title">NovinTrades</h1>
|
||||
<p className="login__subtitle">Super Admin</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="login__lead">Sign in to the admin dashboard.</p>
|
||||
|
||||
<form className="login__form" onSubmit={onSubmit} noValidate>
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="login-email">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="login-email"
|
||||
className="field-input"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="admin@novintrades.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="login-password">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
className="field-input"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? <p className="login__error">{error}</p> : null}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn--primary login__submit"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? "Signing in…" : "Sign in"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { ImageCropper } from "../components/ImageCropper";
|
||||
import { MultiSelect } from "../components/MultiSelect";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { RichTextEditor } from "../components/RichTextEditor";
|
||||
import { TagInput } from "../components/TagInput";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { getCurrentUser } from "../lib/auth";
|
||||
import { flattenCategoryOptions } from "../lib/categories";
|
||||
import {
|
||||
createReportage,
|
||||
getReportage,
|
||||
listCategories,
|
||||
updateReportage,
|
||||
} from "../lib/services";
|
||||
import type { SelectOption } from "../components/MultiSelect";
|
||||
import "../styles/forms.css";
|
||||
|
||||
export function ReportageNewPage() {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams();
|
||||
const isEdit = Boolean(id);
|
||||
const user = getCurrentUser();
|
||||
|
||||
const [categoryOptions, setCategoryOptions] = useState<SelectOption[]>([]);
|
||||
const [categories, setCategories] = useState<string[]>([]);
|
||||
const [title, setTitle] = useState("");
|
||||
const [businessOwner, setBusinessOwner] = useState("");
|
||||
const [image, setImage] = useState<string | null>(null);
|
||||
const [abstract, setAbstract] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [loading, setLoading] = useState(isEdit);
|
||||
const [ready, setReady] = useState(!isEdit);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await listCategories();
|
||||
if (cancelled) return;
|
||||
setCategoryOptions(flattenCategoryOptions(data));
|
||||
|
||||
if (id) {
|
||||
const reportage = await getReportage(id);
|
||||
if (cancelled) return;
|
||||
setTitle(reportage.title);
|
||||
setBusinessOwner(reportage.businessOwner);
|
||||
setAbstract(reportage.abstract ?? "");
|
||||
setContent(reportage.content);
|
||||
setImage(reportage.imageUrl);
|
||||
setTags(reportage.tags);
|
||||
setCategories(reportage.categories.map((c) => c.categoryId));
|
||||
setReady(true);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: "Could not load reportage.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!user) {
|
||||
setError("You must be signed in.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const payload = {
|
||||
title: title.trim(),
|
||||
businessOwner: businessOwner.trim(),
|
||||
abstract: abstract.trim() || undefined,
|
||||
content,
|
||||
imageUrl: image,
|
||||
tags,
|
||||
categoryIds: categories,
|
||||
};
|
||||
|
||||
if (isEdit && id) {
|
||||
await updateReportage(id, payload);
|
||||
} else {
|
||||
await createReportage({ ...payload, authorId: user.id });
|
||||
}
|
||||
navigate("/reportage");
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : "Could not save reportage.",
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader title="Edit reportage" description="Loading…" />
|
||||
<div className="empty-state">
|
||||
<strong>Loading reportage…</strong>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="form-page">
|
||||
<PageHeader
|
||||
title={isEdit ? "Edit reportage" : "New reportage"}
|
||||
description={
|
||||
isEdit
|
||||
? "Update this brand feature or editorial piece."
|
||||
: "Create a brand feature or editorial piece."
|
||||
}
|
||||
/>
|
||||
|
||||
<form className="form-card" onSubmit={onSubmit}>
|
||||
<div className="form-col-3">
|
||||
<ImageCropper
|
||||
label="Main image"
|
||||
value={image}
|
||||
onChange={setImage}
|
||||
aspect={1}
|
||||
folder="reportages"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-col-9">
|
||||
<div className="form-stack">
|
||||
<MultiSelect
|
||||
label="Category"
|
||||
options={categoryOptions}
|
||||
value={categories}
|
||||
onChange={setCategories}
|
||||
/>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="reportage-title">
|
||||
Title
|
||||
</label>
|
||||
<input
|
||||
id="reportage-title"
|
||||
className="field-input"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Reportage title"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="business-owner">
|
||||
Business owner
|
||||
</label>
|
||||
<input
|
||||
id="business-owner"
|
||||
className="field-input"
|
||||
value={businessOwner}
|
||||
onChange={(e) => setBusinessOwner(e.target.value)}
|
||||
placeholder="Brand or company name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<label className="field__label" htmlFor="reportage-abstract">
|
||||
Abstract
|
||||
</label>
|
||||
<textarea
|
||||
id="reportage-abstract"
|
||||
className="field-textarea"
|
||||
value={abstract}
|
||||
onChange={(e) => setAbstract(e.target.value)}
|
||||
placeholder="Short summary for listings"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
{ready ? (
|
||||
<RichTextEditor
|
||||
key={id ?? "new"}
|
||||
label="Main content"
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write the full reportage…"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="form-col-12">
|
||||
<TagInput label="Tags" value={tags} onChange={setTags} />
|
||||
</div>
|
||||
|
||||
{error ? <p className="form-error">{error}</p> : null}
|
||||
|
||||
<div className="form-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => navigate("/reportage")}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn--primary"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting
|
||||
? "Saving…"
|
||||
: isEdit
|
||||
? "Update reportage"
|
||||
: "Save reportage"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { DataTable } from "../components/DataTable";
|
||||
import {
|
||||
ListToolbar,
|
||||
type ListFilterValues,
|
||||
} from "../components/ListToolbar";
|
||||
import { PageHeader } from "../components/PageHeader";
|
||||
import { Pagination } from "../components/Pagination";
|
||||
import { RowActions } from "../components/RowActions";
|
||||
import { StatusBadge } from "../components/StatusBadge";
|
||||
import { StatusModal } from "../components/StatusModal";
|
||||
import { TitlePreviewCell } from "../components/TitlePreviewCell";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { categoryNames, formatDate } from "../lib/format";
|
||||
import {
|
||||
emptyFilters,
|
||||
matchesListFilters,
|
||||
PAGE_SIZE,
|
||||
paginateRows,
|
||||
} from "../lib/list";
|
||||
import {
|
||||
listCategories,
|
||||
listReportages,
|
||||
updateReportage,
|
||||
} from "../lib/services";
|
||||
import type { Category, Reportage, VerificationStatus } from "../lib/types";
|
||||
|
||||
export function ReportagePage() {
|
||||
const navigate = useNavigate();
|
||||
const [draft, setDraft] = useState<ListFilterValues>(emptyFilters);
|
||||
const [applied, setApplied] = useState<ListFilterValues>(emptyFilters);
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<Reportage[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [selected, setSelected] = useState<Reportage | null>(null);
|
||||
const [savingStatus, setSavingStatus] = useState(false);
|
||||
const [statusError, setStatusError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const [items, cats] = await Promise.all([
|
||||
listReportages(),
|
||||
listCategories(),
|
||||
]);
|
||||
if (!cancelled) {
|
||||
setRows(items);
|
||||
setCategories(cats);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
err instanceof ApiError
|
||||
? err.message
|
||||
: "Failed to load reportages.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return rows.filter((item) => {
|
||||
const author = item.author.name ?? item.author.email;
|
||||
return matchesListFilters(
|
||||
item,
|
||||
applied,
|
||||
`${item.businessOwner} ${author}`,
|
||||
);
|
||||
});
|
||||
}, [applied, rows]);
|
||||
|
||||
const paged = useMemo(
|
||||
() => paginateRows(filtered, page, PAGE_SIZE),
|
||||
[filtered, page],
|
||||
);
|
||||
|
||||
function applyFilters() {
|
||||
setApplied(draft);
|
||||
setPage(1);
|
||||
}
|
||||
|
||||
async function changeStatus(next: VerificationStatus) {
|
||||
if (!selected || selected.verificationStatus === next) return;
|
||||
setSavingStatus(true);
|
||||
setStatusError("");
|
||||
try {
|
||||
const updated = await updateReportage(selected.id, {
|
||||
verificationStatus: next,
|
||||
publishedAt: next === "APPROVED" ? new Date().toISOString() : null,
|
||||
});
|
||||
setRows((prev) =>
|
||||
prev.map((row) => (row.id === updated.id ? updated : row)),
|
||||
);
|
||||
setSelected(null);
|
||||
} catch (err) {
|
||||
setStatusError(
|
||||
err instanceof ApiError ? err.message : "Failed to update status.",
|
||||
);
|
||||
} finally {
|
||||
setSavingStatus(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
<PageHeader
|
||||
title="Reportage"
|
||||
description="Brand features and sponsored editorial pieces."
|
||||
actionLabel="New reportage"
|
||||
onAction={() => navigate("/reportage/new")}
|
||||
/>
|
||||
|
||||
<ListToolbar
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onFilter={applyFilters}
|
||||
categories={categories}
|
||||
searchPlaceholder="Search reportages…"
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">
|
||||
<strong>Loading reportages…</strong>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="empty-state">
|
||||
<strong>Could not load reportages</strong>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
) : paged.total === 0 ? (
|
||||
<div className="empty-state">
|
||||
<strong>No reportages found</strong>
|
||||
<p>Try a different filter or create a new reportage.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DataTable<Reportage>
|
||||
rows={paged.items}
|
||||
rowKey={(row) => row.id}
|
||||
columns={[
|
||||
{
|
||||
key: "title",
|
||||
header: "Title",
|
||||
render: (row) => (
|
||||
<TitlePreviewCell
|
||||
title={row.title}
|
||||
abstract={row.abstract}
|
||||
imageUrl={row.imageUrl}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "brand",
|
||||
header: "Business",
|
||||
render: (row) => row.businessOwner,
|
||||
},
|
||||
{
|
||||
key: "author",
|
||||
header: "Author",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{row.author.name ?? row.author.email}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "category",
|
||||
header: "Category",
|
||||
render: (row) => categoryNames(row.categories),
|
||||
},
|
||||
{
|
||||
key: "status",
|
||||
header: "Status",
|
||||
render: (row) => (
|
||||
<StatusBadge
|
||||
status={row.verificationStatus}
|
||||
onClick={() => {
|
||||
setStatusError("");
|
||||
setSelected(row);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "publishedAt",
|
||||
header: "Published",
|
||||
render: (row) => (
|
||||
<span className="cell-muted">
|
||||
{formatDate(row.publishedAt)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
header: "",
|
||||
width: "100px",
|
||||
render: (row) => (
|
||||
<RowActions
|
||||
onEdit={() => navigate(`/reportage/${row.id}/edit`)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Pagination
|
||||
page={paged.page}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={paged.total}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{selected ? (
|
||||
<StatusModal
|
||||
title={selected.title}
|
||||
current={selected.verificationStatus}
|
||||
saving={savingStatus}
|
||||
error={statusError}
|
||||
onSelect={changeStatus}
|
||||
onClose={() => {
|
||||
if (!savingStatus) setSelected(null);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
.form-page {
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.form-card {
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.25rem;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(12, minmax(0, 1fr));
|
||||
gap: 1.1rem 1rem;
|
||||
}
|
||||
|
||||
.form-col-2 {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.form-col-3 {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
.form-col-8 {
|
||||
grid-column: span 8;
|
||||
}
|
||||
|
||||
.form-col-9 {
|
||||
grid-column: span 9;
|
||||
}
|
||||
|
||||
.form-col-12 {
|
||||
grid-column: span 12;
|
||||
}
|
||||
|
||||
.form-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.form-stack .field-textarea {
|
||||
min-height: 96px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
grid-column: span 12;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.25rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--gray-100);
|
||||
}
|
||||
|
||||
.dashboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.dash-tile {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.85rem;
|
||||
padding: 1.25rem;
|
||||
background: var(--white);
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
.dash-tile:hover {
|
||||
border-color: var(--blue);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
|
||||
.dash-tile__icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.dash-tile:hover .dash-tile__icon {
|
||||
background: var(--blue);
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.dash-tile__title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.dash-tile__meta {
|
||||
font-size: 0.85rem;
|
||||
color: var(--gray-600);
|
||||
}
|
||||
|
||||
.dash-tile__count {
|
||||
margin-top: auto;
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
color: var(--blue);
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
.dashboard-grid--actions {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.dash-tile--action {
|
||||
min-height: 88px;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field__hint {
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--gray-400);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.field__error,
|
||||
.crop-modal__error {
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.crop-modal__error {
|
||||
padding: 0 1rem 1rem;
|
||||
}
|
||||
|
||||
.form-error {
|
||||
grid-column: span 12;
|
||||
margin: 0;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border-radius: var(--radius);
|
||||
background: var(--danger-soft);
|
||||
color: var(--danger);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.form-col-2,
|
||||
.form-col-3,
|
||||
.form-col-8,
|
||||
.form-col-9,
|
||||
.form-col-12 {
|
||||
grid-column: span 12;
|
||||
}
|
||||
|
||||
.dashboard-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: "127.0.0.1",
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
allowedHosts: ["novintrades.local", "novintrades.test"],
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:3000",
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/health": {
|
||||
target: "http://127.0.0.1:3000",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "@novintrades/api",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/index.js",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"db:seed": "tsx prisma/seed.ts",
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1093.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1093.0",
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@fastify/multipart": "^10.1.0",
|
||||
"@prisma/client": "^6.16.2",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"fastify": "^5.6.0",
|
||||
"zod": "^4.1.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/node": "^24.13.2",
|
||||
"prisma": "^6.16.2",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/** Brand category tree sourced from Categories.docx (hierarchy preserved). */
|
||||
export type CategoryNode = {
|
||||
name: string;
|
||||
children?: CategoryNode[];
|
||||
};
|
||||
|
||||
export const brandCategoryTree: CategoryNode[] = [
|
||||
{
|
||||
name: "Oil, Energy & Feedstocks",
|
||||
children: [
|
||||
{
|
||||
name: "Oil Products",
|
||||
children: [
|
||||
{
|
||||
name: "Fuels",
|
||||
children: [
|
||||
{ name: "Gasoline" },
|
||||
{ name: "Diesel (EN590)" },
|
||||
{ name: "Jet Fuel" },
|
||||
{ name: "Kerosene" },
|
||||
{ name: "LPG" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Industrial & Base Oils",
|
||||
children: [
|
||||
{ name: "Base Oil" },
|
||||
{ name: "Engine Oil" },
|
||||
{ name: "Hydraulic Oil" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Heavy & Residual Products",
|
||||
children: [
|
||||
{
|
||||
name: "Bitumen",
|
||||
children: [
|
||||
{ name: "Bitumen 60/70" },
|
||||
{ name: "Bitumen 80/100" },
|
||||
{ name: "Bitumen 40/50" },
|
||||
{ name: "VG 30" },
|
||||
{ name: "VG 40" },
|
||||
],
|
||||
},
|
||||
{ name: "Petroleum Coke" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Light Distillates & Solvents",
|
||||
children: [
|
||||
{ name: "Naphtha" },
|
||||
{
|
||||
name: "Solvents",
|
||||
children: [
|
||||
{ name: "White Spirit" },
|
||||
{ name: "Industrial Solvents" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Energy Products",
|
||||
children: [{ name: "Crude Oil" }, { name: "LNG" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Industrial and Consumer Materials",
|
||||
children: [
|
||||
{
|
||||
name: "Medical & Pharmaceutical",
|
||||
children: [
|
||||
{ name: "Medicines" },
|
||||
{ name: "Medical Equipment" },
|
||||
{ name: "Healthcare Products" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Textile & Apparel",
|
||||
children: [
|
||||
{ name: "Raw Textiles" },
|
||||
{ name: "Fabrics" },
|
||||
{ name: "Garments" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Materials & Crafted Goods",
|
||||
children: [
|
||||
{ name: "Titanium Dioxide" },
|
||||
{ name: "Carbon Black" },
|
||||
{ name: "Silica Powder" },
|
||||
{ name: "Timber & Paper" },
|
||||
{ name: "Leather" },
|
||||
],
|
||||
},
|
||||
{ name: "Handicrafts" },
|
||||
{
|
||||
name: "Technology & Innovation",
|
||||
children: [
|
||||
{ name: "AI Solutions" },
|
||||
{ name: "Smart Trade Platforms" },
|
||||
{ name: "Industrial Technologies" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Chemicals & Petrochemicals",
|
||||
children: [
|
||||
{ name: "Urea" },
|
||||
{ name: "Sulfur" },
|
||||
{ name: "Methanol" },
|
||||
{ name: "Paint & Coatings Materials" },
|
||||
{ name: "Industrial Chemicals" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Metals, Mining & Minerals",
|
||||
children: [
|
||||
{ name: "Iron & Steel" },
|
||||
{ name: "Non-Ferrous Metals" },
|
||||
{
|
||||
name: "Jewelry & Precious Stones",
|
||||
children: [
|
||||
{ name: "Gold Jewelry" },
|
||||
{ name: "Silver Jewelry" },
|
||||
{ name: "Precious Stones" },
|
||||
{ name: "Semi-Precious Stones" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Minerals",
|
||||
children: [
|
||||
{ name: "Potash" },
|
||||
{ name: "Limestone" },
|
||||
{ name: "Kaolinite" },
|
||||
{ name: "Feldspar" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Food Products",
|
||||
children: [
|
||||
{ name: "Dates" },
|
||||
{ name: "Saffron" },
|
||||
{ name: "Honey" },
|
||||
{ name: "Fruits" },
|
||||
{ name: "Palm Oil" },
|
||||
{ name: "Beverages" },
|
||||
{ name: "Confectionery" },
|
||||
{ name: "Low Sodium Salt" },
|
||||
{
|
||||
name: "Seafood & Aquaculture",
|
||||
children: [
|
||||
{ name: "Shrimp" },
|
||||
{ name: "Fish" },
|
||||
{ name: "Aquaculture Products" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Building Materials",
|
||||
children: [{ name: "Construction Stones" }],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,193 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "VerificationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CategoryScope" AS ENUM ('CONTENT', 'BRAND');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "User" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"passwordHash" TEXT NOT NULL,
|
||||
"name" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Category" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"scope" "CategoryScope" NOT NULL,
|
||||
"parentId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Category_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Blog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Blog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "BlogCategory" (
|
||||
"blogId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "BlogCategory_pkey" PRIMARY KEY ("blogId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Reportage" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"businessOwner" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Reportage_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ReportageCategory" (
|
||||
"reportageId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "ReportageCategory_pkey" PRIMARY KEY ("reportageId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Brand" (
|
||||
"id" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"abstract" TEXT,
|
||||
"content" TEXT NOT NULL DEFAULT '',
|
||||
"imageUrl" TEXT,
|
||||
"tags" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"country" TEXT NOT NULL,
|
||||
"address" TEXT,
|
||||
"contacts" JSONB NOT NULL DEFAULT '[]',
|
||||
"verificationStatus" "VerificationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"authorId" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Brand_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "BrandCategory" (
|
||||
"brandId" TEXT NOT NULL,
|
||||
"categoryId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "BrandCategory_pkey" PRIMARY KEY ("brandId","categoryId")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Category_parentId_idx" ON "Category"("parentId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Category_scope_idx" ON "Category"("scope");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Category_scope_slug_key" ON "Category"("scope", "slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Blog_slug_key" ON "Blog"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Blog_authorId_idx" ON "Blog"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Blog_verificationStatus_idx" ON "Blog"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "BlogCategory_categoryId_idx" ON "BlogCategory"("categoryId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Reportage_slug_key" ON "Reportage"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Reportage_authorId_idx" ON "Reportage"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Reportage_verificationStatus_idx" ON "Reportage"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ReportageCategory_categoryId_idx" ON "ReportageCategory"("categoryId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Brand_slug_key" ON "Brand"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_authorId_idx" ON "Brand"("authorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_verificationStatus_idx" ON "Brand"("verificationStatus");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Brand_country_idx" ON "Brand"("country");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "BrandCategory_categoryId_idx" ON "BrandCategory"("categoryId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Category" ADD CONSTRAINT "Category_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "Category"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Blog" ADD CONSTRAINT "Blog_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BlogCategory" ADD CONSTRAINT "BlogCategory_blogId_fkey" FOREIGN KEY ("blogId") REFERENCES "Blog"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BlogCategory" ADD CONSTRAINT "BlogCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Reportage" ADD CONSTRAINT "Reportage_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ReportageCategory" ADD CONSTRAINT "ReportageCategory_reportageId_fkey" FOREIGN KEY ("reportageId") REFERENCES "Reportage"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ReportageCategory" ADD CONSTRAINT "ReportageCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Brand" ADD CONSTRAINT "Brand_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BrandCategory" ADD CONSTRAINT "BrandCategory_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "Brand"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "BrandCategory" ADD CONSTRAINT "BrandCategory_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Brand" ADD COLUMN "galleryUrls" TEXT[] DEFAULT ARRAY[]::TEXT[];
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Brand" ADD COLUMN "city" TEXT;
|
||||
@@ -0,0 +1,80 @@
|
||||
-- Merge duplicate categories that share the same slug across scopes,
|
||||
-- then drop scope so one Category table serves blog, reportage, and brand.
|
||||
|
||||
CREATE TEMP TABLE category_keepers AS
|
||||
SELECT DISTINCT ON (slug) id AS keeper_id, slug
|
||||
FROM "Category"
|
||||
ORDER BY slug, "createdAt" ASC, id ASC;
|
||||
|
||||
CREATE TEMP TABLE category_dupes AS
|
||||
SELECT c.id AS dupe_id, k.keeper_id
|
||||
FROM "Category" c
|
||||
JOIN category_keepers k ON k.slug = c.slug
|
||||
WHERE c.id <> k.keeper_id;
|
||||
|
||||
-- BlogCategory: remap to keeper when no conflict
|
||||
UPDATE "BlogCategory" bc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "BlogCategory" x
|
||||
WHERE x."blogId" = bc."blogId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "BlogCategory" bc
|
||||
USING category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id;
|
||||
|
||||
-- ReportageCategory
|
||||
UPDATE "ReportageCategory" rc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE rc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "ReportageCategory" x
|
||||
WHERE x."reportageId" = rc."reportageId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "ReportageCategory" rc
|
||||
USING category_dupes d
|
||||
WHERE rc."categoryId" = d.dupe_id;
|
||||
|
||||
-- BrandCategory
|
||||
UPDATE "BrandCategory" bc
|
||||
SET "categoryId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandCategory" x
|
||||
WHERE x."brandId" = bc."brandId"
|
||||
AND x."categoryId" = d.keeper_id
|
||||
);
|
||||
|
||||
DELETE FROM "BrandCategory" bc
|
||||
USING category_dupes d
|
||||
WHERE bc."categoryId" = d.dupe_id;
|
||||
|
||||
-- Point children of duplicates at the keeper
|
||||
UPDATE "Category" c
|
||||
SET "parentId" = d.keeper_id
|
||||
FROM category_dupes d
|
||||
WHERE c."parentId" = d.dupe_id;
|
||||
|
||||
DELETE FROM "Category" c
|
||||
USING category_dupes d
|
||||
WHERE c.id = d.dupe_id;
|
||||
|
||||
DROP INDEX IF EXISTS "Category_scope_slug_key";
|
||||
DROP INDEX IF EXISTS "Category_scope_idx";
|
||||
|
||||
ALTER TABLE "Category" DROP COLUMN "scope";
|
||||
|
||||
CREATE UNIQUE INDEX "Category_slug_key" ON "Category"("slug");
|
||||
|
||||
DROP TYPE "CategoryScope";
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,143 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum VerificationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
name String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
blogs Blog[]
|
||||
reportages Reportage[]
|
||||
brands Brand[]
|
||||
}
|
||||
|
||||
/// Shared categories for blog, reportage, and brand
|
||||
model Category {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
parentId String?
|
||||
parent Category? @relation("CategoryTree", fields: [parentId], references: [id], onDelete: SetNull)
|
||||
children Category[] @relation("CategoryTree")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
blogs BlogCategory[]
|
||||
reportages ReportageCategory[]
|
||||
brands BrandCategory[]
|
||||
|
||||
@@index([parentId])
|
||||
}
|
||||
|
||||
model Blog {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
tags String[] @default([])
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories BlogCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
}
|
||||
|
||||
model BlogCategory {
|
||||
blogId String
|
||||
categoryId String
|
||||
blog Blog @relation(fields: [blogId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([blogId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
|
||||
model Reportage {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
businessOwner String
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
tags String[] @default([])
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories ReportageCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
}
|
||||
|
||||
model ReportageCategory {
|
||||
reportageId String
|
||||
categoryId String
|
||||
reportage Reportage @relation(fields: [reportageId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([reportageId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
|
||||
model Brand {
|
||||
id String @id @default(cuid())
|
||||
title String
|
||||
slug String @unique
|
||||
abstract String?
|
||||
content String @default("")
|
||||
imageUrl String?
|
||||
galleryUrls String[] @default([])
|
||||
tags String[] @default([])
|
||||
country String
|
||||
city String?
|
||||
address String?
|
||||
/// [{ type: "phone"|"email"|..., value: string }]
|
||||
contacts Json @default("[]")
|
||||
verificationStatus VerificationStatus @default(PENDING)
|
||||
authorId String
|
||||
author User @relation(fields: [authorId], references: [id], onDelete: Restrict)
|
||||
categories BrandCategory[]
|
||||
publishedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([authorId])
|
||||
@@index([verificationStatus])
|
||||
@@index([country])
|
||||
}
|
||||
|
||||
model BrandCategory {
|
||||
brandId String
|
||||
categoryId String
|
||||
brand Brand @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([brandId, categoryId])
|
||||
@@index([categoryId])
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import {
|
||||
brandCategoryTree,
|
||||
type CategoryNode,
|
||||
} from "./data/brand-categories.js";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function slugify(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 120);
|
||||
}
|
||||
|
||||
async function uniqueSlug(base: string): Promise<string> {
|
||||
let slug = slugify(base) || "category";
|
||||
let candidate = slug;
|
||||
let i = 2;
|
||||
while (await prisma.category.findUnique({ where: { slug: candidate } })) {
|
||||
candidate = `${slug}-${i}`;
|
||||
i += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function insertTree(
|
||||
nodes: CategoryNode[],
|
||||
parentId: string | null = null,
|
||||
): Promise<number> {
|
||||
let count = 0;
|
||||
for (const node of nodes) {
|
||||
const slug = await uniqueSlug(node.name);
|
||||
const created = await prisma.category.create({
|
||||
data: {
|
||||
name: node.name,
|
||||
slug,
|
||||
parentId,
|
||||
},
|
||||
});
|
||||
count += 1;
|
||||
if (node.children?.length) {
|
||||
count += await insertTree(node.children, created.id);
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const passwordHash = await bcrypt.hash("admin123", 10);
|
||||
|
||||
const admin = await prisma.user.upsert({
|
||||
where: { email: "admin@novintrades.com" },
|
||||
update: {},
|
||||
create: {
|
||||
email: "admin@novintrades.com",
|
||||
name: "Admin",
|
||||
passwordHash,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.blogCategory.deleteMany();
|
||||
await prisma.reportageCategory.deleteMany();
|
||||
await prisma.brandCategory.deleteMany();
|
||||
await prisma.category.deleteMany();
|
||||
|
||||
const treeCount = await insertTree(brandCategoryTree);
|
||||
|
||||
console.log(`Seeded admin: ${admin.email}`);
|
||||
console.log(`Seeded ${treeCount} categories from Categories.docx hierarchy`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import Fastify from "fastify";
|
||||
import cors from "@fastify/cors";
|
||||
import { prisma } from "./lib/prisma.js";
|
||||
import { healthRoutes } from "./routes/health.js";
|
||||
import { categoryRoutes } from "./routes/categories.js";
|
||||
import { blogRoutes } from "./routes/blogs.js";
|
||||
import { reportageRoutes } from "./routes/reportages.js";
|
||||
import { brandRoutes } from "./routes/brands.js";
|
||||
import { authRoutes } from "./routes/auth.js";
|
||||
import { uploadRoutes } from "./routes/uploads.js";
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify({
|
||||
logger: true,
|
||||
});
|
||||
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
});
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
|
||||
await app.register(healthRoutes);
|
||||
await app.register(authRoutes, { prefix: "/api/auth" });
|
||||
await app.register(categoryRoutes, { prefix: "/api/categories" });
|
||||
await app.register(blogRoutes, { prefix: "/api/blogs" });
|
||||
await app.register(reportageRoutes, { prefix: "/api/reportages" });
|
||||
await app.register(brandRoutes, { prefix: "/api/brands" });
|
||||
await app.register(uploadRoutes, { prefix: "/api/uploads" });
|
||||
|
||||
app.addHook("onClose", async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyInstance {
|
||||
prisma: typeof prisma;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { buildApp } from "./app.js";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
const host = process.env.HOST ?? "0.0.0.0";
|
||||
|
||||
const app = await buildApp();
|
||||
|
||||
try {
|
||||
await app.listen({ port, host });
|
||||
} catch (error) {
|
||||
app.log.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export const MAX_IMAGE_BYTES = Number(
|
||||
process.env.MAX_IMAGE_BYTES ?? 250 * 1024,
|
||||
);
|
||||
|
||||
export function assertImageSize(bytes: number): void {
|
||||
if (bytes > MAX_IMAGE_BYTES) {
|
||||
const maxKb = Math.round(MAX_IMAGE_BYTES / 1024);
|
||||
throw Object.assign(
|
||||
new Error(`Image must be ${maxKb}KB or smaller`),
|
||||
{ statusCode: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
export const prisma = new PrismaClient();
|
||||
@@ -0,0 +1,87 @@
|
||||
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { assertImageSize } from "./limits.js";
|
||||
|
||||
function required(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) {
|
||||
throw new Error(`Missing env ${name}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
let client: S3Client | null = null;
|
||||
|
||||
function getClient(): S3Client {
|
||||
if (!client) {
|
||||
client = new S3Client({
|
||||
region: process.env.S3_REGION ?? "us-east-1",
|
||||
endpoint: required("S3_ENDPOINT"),
|
||||
forcePathStyle: true,
|
||||
credentials: {
|
||||
accessKeyId: required("S3_ACCESS_KEY"),
|
||||
secretAccessKey: required("S3_SECRET_KEY"),
|
||||
},
|
||||
});
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
function extensionFor(mime: string): string {
|
||||
switch (mime) {
|
||||
case "image/png":
|
||||
return "png";
|
||||
case "image/webp":
|
||||
return "webp";
|
||||
case "image/gif":
|
||||
return "gif";
|
||||
case "image/jpeg":
|
||||
case "image/jpg":
|
||||
default:
|
||||
return "jpg";
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadImageBuffer(input: {
|
||||
buffer: Buffer;
|
||||
contentType: string;
|
||||
folder?: string;
|
||||
}): Promise<{ url: string; key: string; size: number }> {
|
||||
assertImageSize(input.buffer.byteLength);
|
||||
|
||||
const allowed = new Set([
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/gif",
|
||||
]);
|
||||
if (!allowed.has(input.contentType)) {
|
||||
throw Object.assign(new Error("Only JPG, PNG, WebP, or GIF allowed"), {
|
||||
statusCode: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const folder = input.folder?.replace(/^\/+|\/+$/g, "") || "uploads";
|
||||
const key = `${folder}/${randomUUID()}.${extensionFor(input.contentType)}`;
|
||||
const bucket = required("S3_BUCKET");
|
||||
const publicBase = (
|
||||
process.env.S3_PUBLIC_BASE_URL ?? required("S3_ENDPOINT")
|
||||
).replace(/\/+$/, "");
|
||||
|
||||
await getClient().send(
|
||||
new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
Body: input.buffer,
|
||||
ContentType: input.contentType,
|
||||
ACL: "public-read",
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
key,
|
||||
size: input.buffer.byteLength,
|
||||
url: `${publicBase}/${key}`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function slugify(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"]/g, "")
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 120);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.post("/login", async (request, reply) => {
|
||||
const parsed = loginSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: "Invalid credentials payload" });
|
||||
}
|
||||
|
||||
const user = await app.prisma.user.findUnique({
|
||||
where: { email: parsed.data.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return reply.status(401).send({ error: "Invalid email or password" });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(parsed.data.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
return reply.status(401).send({ error: "Invalid email or password" });
|
||||
}
|
||||
|
||||
return {
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
export const blogRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.blog.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const blog = await app.prisma.blog.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!blog) {
|
||||
return reply.status(404).send({ error: "Blog not found" });
|
||||
}
|
||||
|
||||
return blog;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
|
||||
const blog = await app.prisma.blog.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
tags: parsed.data.tags ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(blog);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await app.prisma.blog.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Blog not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
|
||||
const blog = await app.prisma.blog.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return blog;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const contactSchema = z.object({
|
||||
type: z.enum([
|
||||
"phone",
|
||||
"landline",
|
||||
"email",
|
||||
"instagram",
|
||||
"website",
|
||||
"whatsapp",
|
||||
"other",
|
||||
]),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
galleryUrls: z.array(z.string().url()).optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
country: z.string().min(1),
|
||||
city: z.string().optional(),
|
||||
address: z.string().optional(),
|
||||
contacts: z.array(contactSchema).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
function assertNoContentImages(content: string | undefined, reply: {
|
||||
status: (code: number) => { send: (body: unknown) => unknown };
|
||||
}) {
|
||||
if (content && /<img\b/i.test(content)) {
|
||||
return reply.status(400).send({
|
||||
error: "Brand main text cannot include images. Use the gallery instead.",
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const brandRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.brand.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const brand = await app.prisma.brand.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!brand) {
|
||||
return reply.status(404).send({ error: "Brand not found" });
|
||||
}
|
||||
|
||||
return brand;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const contentBlocked = assertNoContentImages(parsed.data.content, reply);
|
||||
if (contentBlocked) return contentBlocked;
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
const galleryUrls = parsed.data.galleryUrls ?? [];
|
||||
|
||||
const brand = await app.prisma.brand.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
galleryUrls,
|
||||
tags: parsed.data.tags ?? [],
|
||||
country: parsed.data.country,
|
||||
city: parsed.data.city,
|
||||
address: parsed.data.address,
|
||||
contacts: parsed.data.contacts ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(brand);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const contentBlocked = assertNoContentImages(parsed.data.content, reply);
|
||||
if (contentBlocked) return contentBlocked;
|
||||
|
||||
const existing = await app.prisma.brand.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Brand not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
const galleryUrls = data.galleryUrls;
|
||||
|
||||
const brand = await app.prisma.brand.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(galleryUrls !== undefined ? { galleryUrls } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.country !== undefined ? { country: data.country } : {}),
|
||||
...(data.city !== undefined ? { city: data.city } : {}),
|
||||
...(data.address !== undefined ? { address: data.address } : {}),
|
||||
...(data.contacts !== undefined ? { contacts: data.contacts } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return brand;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
parentId: z.string().cuid().nullable().optional(),
|
||||
});
|
||||
|
||||
export const categoryRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.category.findMany({
|
||||
orderBy: { name: "asc" },
|
||||
include: {
|
||||
children: {
|
||||
orderBy: { name: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.name);
|
||||
if (!slug) {
|
||||
return reply.status(400).send({ error: "Invalid slug" });
|
||||
}
|
||||
|
||||
const category = await app.prisma.category.create({
|
||||
data: {
|
||||
name: parsed.data.name,
|
||||
slug,
|
||||
parentId: parsed.data.parentId ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(category);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
|
||||
export const healthRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/health", async () => ({
|
||||
ok: true,
|
||||
service: "novintrades-api",
|
||||
}));
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { VerificationStatus } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { slugify } from "../lib/slug.js";
|
||||
|
||||
const createSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1).optional(),
|
||||
businessOwner: z.string().min(1),
|
||||
abstract: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
imageUrl: z.string().url().nullable().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
categoryIds: z.array(z.string().cuid()).optional(),
|
||||
authorId: z.string().cuid(),
|
||||
verificationStatus: z.nativeEnum(VerificationStatus).optional(),
|
||||
publishedAt: z.coerce.date().nullable().optional(),
|
||||
});
|
||||
|
||||
export const reportageRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/", async () => {
|
||||
return app.prisma.reportage.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const reportage = await app.prisma.reportage.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!reportage) {
|
||||
return reply.status(404).send({ error: "Reportage not found" });
|
||||
}
|
||||
|
||||
return reportage;
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const parsed = createSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const slug = slugify(parsed.data.slug ?? parsed.data.title);
|
||||
const categoryIds = parsed.data.categoryIds ?? [];
|
||||
|
||||
const reportage = await app.prisma.reportage.create({
|
||||
data: {
|
||||
title: parsed.data.title,
|
||||
slug,
|
||||
businessOwner: parsed.data.businessOwner,
|
||||
abstract: parsed.data.abstract,
|
||||
content: parsed.data.content ?? "",
|
||||
imageUrl: parsed.data.imageUrl ?? null,
|
||||
tags: parsed.data.tags ?? [],
|
||||
authorId: parsed.data.authorId,
|
||||
verificationStatus:
|
||||
parsed.data.verificationStatus ?? VerificationStatus.PENDING,
|
||||
publishedAt: parsed.data.publishedAt ?? null,
|
||||
categories: {
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reply.status(201).send(reportage);
|
||||
});
|
||||
|
||||
app.patch("/:id", async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const updateSchema = createSchema.partial().omit({ authorId: true });
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.status(400).send({ error: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await app.prisma.reportage.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return reply.status(404).send({ error: "Reportage not found" });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const categoryIds = data.categoryIds;
|
||||
|
||||
const reportage = await app.prisma.reportage.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.title !== undefined ? { title: data.title } : {}),
|
||||
...(data.title !== undefined || data.slug !== undefined
|
||||
? { slug: slugify(data.slug ?? data.title ?? existing.title) }
|
||||
: {}),
|
||||
...(data.businessOwner !== undefined
|
||||
? { businessOwner: data.businessOwner }
|
||||
: {}),
|
||||
...(data.abstract !== undefined ? { abstract: data.abstract } : {}),
|
||||
...(data.content !== undefined ? { content: data.content } : {}),
|
||||
...(data.imageUrl !== undefined ? { imageUrl: data.imageUrl } : {}),
|
||||
...(data.tags !== undefined ? { tags: data.tags } : {}),
|
||||
...(data.verificationStatus !== undefined
|
||||
? { verificationStatus: data.verificationStatus }
|
||||
: {}),
|
||||
...(data.publishedAt !== undefined
|
||||
? { publishedAt: data.publishedAt }
|
||||
: {}),
|
||||
...(categoryIds
|
||||
? {
|
||||
categories: {
|
||||
deleteMany: {},
|
||||
create: categoryIds.map((categoryId) => ({ categoryId })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, email: true, name: true } },
|
||||
categories: { include: { category: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return reportage;
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import { MAX_IMAGE_BYTES } from "../lib/limits.js";
|
||||
import { uploadImageBuffer } from "../lib/s3.js";
|
||||
|
||||
export const uploadRoutes: FastifyPluginAsync = async (app) => {
|
||||
await app.register(multipart, {
|
||||
limits: {
|
||||
fileSize: MAX_IMAGE_BYTES,
|
||||
files: 1,
|
||||
},
|
||||
});
|
||||
|
||||
app.post("/", async (request, reply) => {
|
||||
const query = request.query as { folder?: string };
|
||||
const folder =
|
||||
typeof query.folder === "string" && query.folder.trim()
|
||||
? query.folder.trim()
|
||||
: "uploads";
|
||||
|
||||
const file = await request.file();
|
||||
if (!file) {
|
||||
return reply.status(400).send({ error: "No image file provided" });
|
||||
}
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
buffer = await file.toBuffer();
|
||||
} catch {
|
||||
return reply.status(400).send({
|
||||
error: `Image must be ${Math.round(MAX_IMAGE_BYTES / 1024)}KB or smaller`,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const uploaded = await uploadImageBuffer({
|
||||
buffer,
|
||||
contentType: file.mimetype,
|
||||
folder,
|
||||
});
|
||||
return reply.status(201).send(uploaded);
|
||||
} catch (error) {
|
||||
const statusCode =
|
||||
error && typeof error === "object" && "statusCode" in error
|
||||
? Number((error as { statusCode: number }).statusCode)
|
||||
: 500;
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Upload failed";
|
||||
return reply.status(statusCode || 500).send({ error: message });
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
# Public website
|
||||
|
||||
English marketing site for NovinTrades.
|
||||
|
||||
## Dev
|
||||
|
||||
```bash
|
||||
npm run dev:web
|
||||
```
|
||||
|
||||
- http://novintrades.local:5174 (requires `/etc/hosts` → `127.0.0.1 novintrades.local`)
|
||||
- http://127.0.0.1:5174
|
||||
|
||||
## Stack
|
||||
|
||||
- Vite + React + TypeScript
|
||||
- Montserrat
|
||||
- Light gray → blue → dark blue gradient theme
|
||||
|
||||
## Sections / pages
|
||||
|
||||
Home · About · Contact · Blog list/detail · Reportage list/detail · Brand list/detail
|
||||
|
||||
## Routes
|
||||
|
||||
- `/` home
|
||||
- `/about` `/contact`
|
||||
- `/blog` `/blog/:slug`
|
||||
- `/reportages` `/reportages/:slug`
|
||||
- `/brands` `/brands/:slug`
|
||||
@@ -0,0 +1,23 @@
|
||||
<!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" />
|
||||
<meta
|
||||
name="description"
|
||||
content="NovinTrades — discover brands, insights, and trade opportunities across industries."
|
||||
/>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<title>NovinTrades</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@novintrades/web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^1.26.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-router-dom": "^7.18.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"oxlint": "^1.71.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
|
||||
<rect width="32" height="32" rx="6" fill="#0B2A5B"/>
|
||||
<path d="M8 22V10h3.2l4.4 7.2V10H19v12h-3.2L11.4 14.8V22H8z" fill="#E8EEF6"/>
|
||||
<path d="M21 22V10h3v12h-3z" fill="#3B82C4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 263 B |
@@ -0,0 +1,9 @@
|
||||
.app {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.app main {
|
||||
flex: 1;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import Layout from "./components/Layout";
|
||||
import AboutPage from "./pages/AboutPage";
|
||||
import BlogDetailPage from "./pages/BlogDetailPage";
|
||||
import BlogListPage from "./pages/BlogListPage";
|
||||
import BrandDetailPage from "./pages/BrandDetailPage";
|
||||
import BrandListPage from "./pages/BrandListPage";
|
||||
import ContactPage from "./pages/ContactPage";
|
||||
import HomePage from "./pages/HomePage";
|
||||
import ReportageDetailPage from "./pages/ReportageDetailPage";
|
||||
import ReportageListPage from "./pages/ReportageListPage";
|
||||
import "./App.css";
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route element={<Layout />}>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="about" element={<AboutPage />} />
|
||||
<Route path="contact" element={<ContactPage />} />
|
||||
<Route path="blog" element={<BlogListPage />} />
|
||||
<Route path="blog/:slug" element={<BlogDetailPage />} />
|
||||
<Route path="reportages" element={<ReportageListPage />} />
|
||||
<Route path="reportages/:slug" element={<ReportageDetailPage />} />
|
||||
<Route path="brands" element={<BrandListPage />} />
|
||||
<Route path="brands/:slug" element={<BrandDetailPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
.about {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.about__layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1.05fr 0.95fr;
|
||||
gap: 3.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.about__visual {
|
||||
position: relative;
|
||||
min-height: 420px;
|
||||
}
|
||||
|
||||
.about__panel {
|
||||
position: absolute;
|
||||
border-radius: 0.65rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.about__panel--back {
|
||||
inset: 12% 18% 0 0;
|
||||
background: linear-gradient(145deg, var(--blue-soft), var(--blue-deep), var(--dark-blue));
|
||||
transform: rotate(-2.5deg);
|
||||
}
|
||||
|
||||
.about__panel--front {
|
||||
inset: 0 0 12% 8%;
|
||||
box-shadow: 0 18px 40px rgba(11, 42, 91, 0.18);
|
||||
}
|
||||
|
||||
.about__panel--front img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.about__lead {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.about__text {
|
||||
color: var(--gray-600);
|
||||
margin-bottom: 1.75rem;
|
||||
max-width: 34rem;
|
||||
}
|
||||
|
||||
.about__cta {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.85rem 1.3rem;
|
||||
border-radius: 0.4rem;
|
||||
background: linear-gradient(135deg, var(--blue), var(--dark-blue));
|
||||
color: var(--white);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
transition: transform 0.25s var(--ease);
|
||||
}
|
||||
|
||||
.about__cta:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.about__layout {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 2.5rem;
|
||||
}
|
||||
|
||||
.about__visual {
|
||||
min-height: 300px;
|
||||
order: -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import "./AboutUs.css";
|
||||
|
||||
export default function AboutUs() {
|
||||
return (
|
||||
<section className="section about" id="about">
|
||||
<div className="container about__layout">
|
||||
<div className="about__visual" aria-hidden="true">
|
||||
<div className="about__panel about__panel--back" />
|
||||
<div className="about__panel about__panel--front">
|
||||
<img
|
||||
src="https://images.unsplash.com/photo-1521737604893-d14cc237f11d?auto=format&fit=crop&w=1200&q=80"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="about__copy">
|
||||
<span className="section__eyebrow">Who we are</span>
|
||||
<h2 className="section__title">About us</h2>
|
||||
<p className="section__lead about__lead">
|
||||
NovinTrades is a marketplace of trusted brands, industry categories,
|
||||
and practical content — built to help businesses find the right
|
||||
partners faster.
|
||||
</p>
|
||||
<p className="about__text">
|
||||
We bring together verified company profiles, trade insights, and a
|
||||
clear category map so buyers and suppliers can navigate opportunities
|
||||
with confidence. From manufacturing floors to logistics corridors,
|
||||
our platform keeps discovery simple and professional.
|
||||
</p>
|
||||
<Link className="about__cta" to="/about">
|
||||
Learn more
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
.categories {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.categories__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.categories__item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.45rem;
|
||||
min-width: 0;
|
||||
padding: 1.25rem 1.15rem 1.35rem;
|
||||
border-radius: 0.55rem;
|
||||
background: linear-gradient(
|
||||
160deg,
|
||||
rgba(255, 255, 255, 0.78) 0%,
|
||||
rgba(232, 238, 246, 0.92) 100%
|
||||
);
|
||||
border: 1px solid rgba(11, 42, 91, 0.08);
|
||||
transition:
|
||||
transform 0.3s var(--ease),
|
||||
border-color 0.25s ease,
|
||||
background 0.25s ease;
|
||||
animation: rise-in 0.55s var(--ease) both;
|
||||
scroll-margin-top: calc(var(--header-h) + 1rem);
|
||||
}
|
||||
|
||||
.categories__item:hover {
|
||||
transform: translateY(-4px);
|
||||
border-color: rgba(31, 95, 168, 0.28);
|
||||
background: linear-gradient(
|
||||
160deg,
|
||||
rgba(255, 255, 255, 0.95) 0%,
|
||||
rgba(197, 216, 239, 0.55) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.categories__icon {
|
||||
width: 2.55rem;
|
||||
height: 2.55rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 0.45rem;
|
||||
color: var(--dark-blue);
|
||||
background: linear-gradient(145deg, var(--gray-100), var(--blue-soft));
|
||||
margin-bottom: 0.2rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.categories__name {
|
||||
font-size: 1.02rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.categories__desc {
|
||||
font-size: 0.88rem;
|
||||
color: var(--gray-600);
|
||||
line-height: 1.45;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.categories__status {
|
||||
margin-bottom: 1.25rem;
|
||||
color: var(--gray-600);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.categories__status--error {
|
||||
color: #b42318;
|
||||
}
|
||||
|
||||
@keyframes rise-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(14px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.categories__grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.categories__grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
BrickWall,
|
||||
Factory,
|
||||
Flame,
|
||||
FlaskConical,
|
||||
Gem,
|
||||
Layers,
|
||||
Package,
|
||||
UtensilsCrossed,
|
||||
} from "lucide-react";
|
||||
import { fetchTopCategories } from "../lib/services";
|
||||
import type { Category } from "../lib/types";
|
||||
import "./Categories.css";
|
||||
|
||||
const iconRules: Array<{ match: RegExp; icon: LucideIcon }> = [
|
||||
{ match: /building|construction|stone/, icon: BrickWall },
|
||||
{ match: /chemical|petro/, icon: FlaskConical },
|
||||
{ match: /food|beverage|fruit/, icon: UtensilsCrossed },
|
||||
{ match: /metal|mining|mineral|jewel/, icon: Gem },
|
||||
{ match: /oil|energy|fuel|feedstock/, icon: Flame },
|
||||
{ match: /industrial|consumer|material|textile|tech/, icon: Layers },
|
||||
{ match: /manufactur|factory/, icon: Factory },
|
||||
];
|
||||
|
||||
function categoryIcon(category: Category): LucideIcon {
|
||||
const haystack = `${category.slug} ${category.name}`.toLowerCase();
|
||||
return iconRules.find((rule) => rule.match.test(haystack))?.icon ?? Package;
|
||||
}
|
||||
|
||||
function subcategoryPreview(children: Category[] | undefined): string {
|
||||
if (!children?.length) return "Industry category";
|
||||
return children.map((child) => child.name).join(" · ");
|
||||
}
|
||||
|
||||
export default function Categories() {
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetchTopCategories()
|
||||
.then((items) => {
|
||||
if (active) setCategories(items);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (active) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "Could not load categories",
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="section categories" id="categories">
|
||||
<div className="container">
|
||||
<div className="section__head">
|
||||
<span className="section__eyebrow">Browse by industry</span>
|
||||
<h2 className="section__title">Categories</h2>
|
||||
<p className="section__lead">
|
||||
Explore first-level industries to discover brands, partners, and opportunities.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<p className="categories__status">Loading categories…</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p className="categories__status categories__status--error">{error}</p>
|
||||
) : null}
|
||||
{!loading && !error && categories.length === 0 ? (
|
||||
<p className="categories__status">No categories yet.</p>
|
||||
) : null}
|
||||
|
||||
<div className="categories__grid">
|
||||
{categories.map((category, index) => {
|
||||
const Icon = categoryIcon(category);
|
||||
return (
|
||||
<Link
|
||||
key={category.id}
|
||||
id={`category-${category.slug}`}
|
||||
className="categories__item"
|
||||
to={`/brands?category=${category.slug}`}
|
||||
style={{ animationDelay: `${index * 45}ms` }}
|
||||
>
|
||||
<span className="categories__icon" aria-hidden="true">
|
||||
<Icon size={22} strokeWidth={1.75} />
|
||||
</span>
|
||||
<span className="categories__name">{category.name}</span>
|
||||
<span className="categories__desc" title={subcategoryPreview(category.children)}>
|
||||
{subcategoryPreview(category.children)}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
.cat-filter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.55rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.cat-filter__chip {
|
||||
padding: 0.5rem 0.9rem;
|
||||
border-radius: 0.4rem;
|
||||
border: 1px solid rgba(11, 42, 91, 0.12);
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
color: var(--gray-600);
|
||||
font-size: 0.84rem;
|
||||
font-weight: 600;
|
||||
transition:
|
||||
background 0.2s ease,
|
||||
color 0.2s ease,
|
||||
border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.cat-filter__chip:hover {
|
||||
border-color: rgba(31, 95, 168, 0.3);
|
||||
color: var(--dark-blue);
|
||||
}
|
||||
|
||||
.cat-filter__chip.is-active {
|
||||
background: linear-gradient(135deg, var(--blue-deep), var(--dark-blue));
|
||||
border-color: transparent;
|
||||
color: var(--white);
|
||||
}
|
||||
|
||||
.cat-filter__clear {
|
||||
align-self: center;
|
||||
margin-left: 0.25rem;
|
||||
font-size: 0.84rem;
|
||||
font-weight: 600;
|
||||
color: var(--blue-deep);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import type { Category } from "../lib/types";
|
||||
import "./CategoryFilter.css";
|
||||
|
||||
type CategoryFilterProps = {
|
||||
categories: Category[];
|
||||
};
|
||||
|
||||
export default function CategoryFilter({ categories }: CategoryFilterProps) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const active = params.get("category");
|
||||
|
||||
function select(slug: string | null) {
|
||||
const next = new URLSearchParams(params);
|
||||
if (slug) next.set("category", slug);
|
||||
else next.delete("category");
|
||||
next.delete("page");
|
||||
setParams(next);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="cat-filter" role="list">
|
||||
<button
|
||||
type="button"
|
||||
className={`cat-filter__chip ${!active ? "is-active" : ""}`}
|
||||
onClick={() => select(null)}
|
||||
>
|
||||
All
|
||||
</button>
|
||||
{categories.map((category) => (
|
||||
<button
|
||||
key={category.id}
|
||||
type="button"
|
||||
className={`cat-filter__chip ${active === category.slug ? "is-active" : ""}`}
|
||||
onClick={() => select(category.slug)}
|
||||
>
|
||||
{category.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user