Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
9571b5b649
|
|||
|
25093606c9
|
|||
|
aa6fa39f6a
|
|||
|
2971fb298e
|
|||
|
d75501860d
|
|||
|
ff886d3002
|
|||
|
48c7d522c1
|
|||
|
531bb8750e
|
|||
|
8572e22c5d
|
15
bun.lock
15
bun.lock
@ -5,8 +5,8 @@
|
||||
"": {
|
||||
"name": "admin.gaertan.art",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.974.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.974.0",
|
||||
"@aws-sdk/client-s3": "^3.980.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.980.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
@ -39,7 +39,7 @@
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"archiver": "^7.0.1",
|
||||
"better-auth": "^1.4.17",
|
||||
"better-auth": "^1.4.18",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
@ -50,9 +50,9 @@
|
||||
"lucide-react": "^0.561.0",
|
||||
"next": "16.1.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"node-vibrant": "^4.0.3",
|
||||
"nodemailer": "^7.0.12",
|
||||
"pg": "^8.17.2",
|
||||
"node-vibrant": "^4.0.4",
|
||||
"nodemailer": "^7.0.13",
|
||||
"pg": "^8.18.0",
|
||||
"platejs": "^52.0.17",
|
||||
"react": "19.2.4",
|
||||
"react-day-picker": "^9.13.0",
|
||||
@ -65,6 +65,7 @@
|
||||
"tailwind-scrollbar-hide": "^4.0.0",
|
||||
"uuid": "^13.0.0",
|
||||
"zod": "^4.3.6",
|
||||
"zustand": "^5.0.8",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.2.0",
|
||||
@ -73,7 +74,7 @@
|
||||
"@types/culori": "^4.0.1",
|
||||
"@types/date-fns": "^2.6.3",
|
||||
"@types/node": "^20.19.30",
|
||||
"@types/nodemailer": "^7.0.5",
|
||||
"@types/nodemailer": "^7.0.9",
|
||||
"@types/pg": "^8.16.0",
|
||||
"@types/react": "19.2.10",
|
||||
"@types/react-dom": "19.2.3",
|
||||
|
||||
@ -71,6 +71,7 @@
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwind-scrollbar-hide": "^4.0.0",
|
||||
"uuid": "^13.0.0",
|
||||
"zustand": "^5.0.8",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
10
prisma/migrations/20260205135425_about_01/migration.sql
Normal file
10
prisma/migrations/20260205135425_about_01/migration.sql
Normal file
@ -0,0 +1,10 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "About" (
|
||||
"id" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"markdown" TEXT NOT NULL,
|
||||
"version" SERIAL NOT NULL,
|
||||
|
||||
CONSTRAINT "About_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
@ -524,6 +524,15 @@ model TermsOfService {
|
||||
version Int @default(autoincrement())
|
||||
}
|
||||
|
||||
model About {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
markdown String
|
||||
version Int @default(autoincrement())
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id
|
||||
name String
|
||||
|
||||
11
src/actions/about/getAbout.ts
Normal file
11
src/actions/about/getAbout.ts
Normal file
@ -0,0 +1,11 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns the most recent About Me markdown.
|
||||
export async function getLatestAboutMe(): Promise<string | null> {
|
||||
const about = await prisma.about.findFirst({
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return about?.markdown ?? null;
|
||||
}
|
||||
55
src/actions/about/images.ts
Normal file
55
src/actions/about/images.ts
Normal file
@ -0,0 +1,55 @@
|
||||
"use server";
|
||||
|
||||
import { s3 } from "@/lib/s3";
|
||||
import { PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
|
||||
const PREFIX = "about/images/";
|
||||
|
||||
function buildImageUrl(key: string) {
|
||||
return `/api/image/${encodeURI(key)}`;
|
||||
}
|
||||
|
||||
function sanitizeFilename(name: string) {
|
||||
return name.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
|
||||
export type AboutImageUpload = {
|
||||
key: string;
|
||||
url: string;
|
||||
size: number;
|
||||
lastModified: string;
|
||||
};
|
||||
|
||||
export async function uploadAboutImage(
|
||||
formData: FormData
|
||||
): Promise<AboutImageUpload> {
|
||||
const file = formData.get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new Error("Missing file");
|
||||
}
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
throw new Error("Only image uploads are allowed");
|
||||
}
|
||||
|
||||
const safeName = sanitizeFilename(file.name || "about-image");
|
||||
const key = `${PREFIX}${Date.now()}-${safeName}`;
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: `${process.env.BUCKET_NAME}`,
|
||||
Key: key,
|
||||
Body: buffer,
|
||||
ContentType: file.type,
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
key,
|
||||
url: buildImageUrl(key),
|
||||
size: file.size,
|
||||
lastModified: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
12
src/actions/about/saveAbout.ts
Normal file
12
src/actions/about/saveAbout.ts
Normal file
@ -0,0 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Saves a new About Me version.
|
||||
export async function saveAboutMeAction(markdown: string) {
|
||||
await prisma.about.create({
|
||||
data: {
|
||||
markdown,
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { prisma } from "@/lib/prisma";
|
||||
import { s3 } from "@/lib/s3";
|
||||
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
|
||||
|
||||
// Deletes an artwork and all related assets and records.
|
||||
export async function deleteArtwork(artworkId: string) {
|
||||
const artwork = await prisma.artwork.findUnique({
|
||||
where: { id: artworkId },
|
||||
|
||||
@ -54,12 +54,12 @@ function centroidFromPaletteHexes(
|
||||
};
|
||||
|
||||
const fallbackHex =
|
||||
hexByType["Vibrant"] ||
|
||||
hexByType["Muted"] ||
|
||||
hexByType["DarkVibrant"] ||
|
||||
hexByType["DarkMuted"] ||
|
||||
hexByType["LightVibrant"] ||
|
||||
hexByType["LightMuted"];
|
||||
hexByType.Vibrant ||
|
||||
hexByType.Muted ||
|
||||
hexByType.DarkVibrant ||
|
||||
hexByType.DarkMuted ||
|
||||
hexByType.LightVibrant ||
|
||||
hexByType.LightMuted;
|
||||
|
||||
let L = 0,
|
||||
A = 0,
|
||||
@ -123,7 +123,9 @@ export async function generateArtworkColorsForArtwork(artworkId: string) {
|
||||
for (const { type, hex } of vibrantHexes) {
|
||||
if (!hex) continue;
|
||||
|
||||
const [r, g, b] = hex.match(/\w\w/g)!.map((h) => parseInt(h, 16));
|
||||
const match = hex.match(/\w\w/g);
|
||||
if (!match) continue;
|
||||
const [r, g, b] = match.map((h) => parseInt(h, 16));
|
||||
const name = generateColorName(hex);
|
||||
|
||||
const color = await prisma.color.upsert({
|
||||
|
||||
@ -8,6 +8,7 @@ import sharp from "sharp";
|
||||
|
||||
const GALLERY_TARGET_SIZE = 300;
|
||||
|
||||
// Generates a gallery-sized variant for a single artwork.
|
||||
export async function generateGalleryVariant(
|
||||
artworkId: string,
|
||||
opts?: { force?: boolean },
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns color swatches for a given artwork.
|
||||
export async function getArtworkColors(artworkId: string) {
|
||||
return prisma.artworkColor.findMany({
|
||||
where: { artworkId },
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns album/category options for artwork filters.
|
||||
export async function getArtworkFilterOptions() {
|
||||
const [albums, categories] = await Promise.all([
|
||||
prisma.album.findMany({ select: { id: true, name: true }, orderBy: { name: "asc" } }),
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Loads a single artwork with relations for the edit page.
|
||||
export async function getSingleArtwork(id: string) {
|
||||
return await prisma.artwork.findUnique({
|
||||
return prisma.artwork.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
// album: true,
|
||||
@ -17,7 +18,7 @@ export async function getSingleArtwork(id: string) {
|
||||
// sortContexts: true,
|
||||
tags: true,
|
||||
variants: true,
|
||||
timelapse: true
|
||||
}
|
||||
})
|
||||
timelapse: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,15 +1,19 @@
|
||||
"use server";
|
||||
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { ArtworkTableInput, artworkTableInputSchema, artworkTableOutputSchema } from "@/schemas/artworks/tableSchema";
|
||||
import { type ArtworkTableInput, artworkTableInputSchema, artworkTableOutputSchema } from "@/schemas/artworks/tableSchema";
|
||||
|
||||
// Builds the admin artworks table page with filters, sorting, and pagination.
|
||||
function triToBool(tri: "any" | "true" | "false"): boolean | undefined {
|
||||
if (tri === "any") return undefined;
|
||||
return tri === "true";
|
||||
}
|
||||
|
||||
function mapSortingToOrderBy(sorting: ArtworkTableInput["sorting"]) {
|
||||
const allowed: Record<string, (desc: boolean) => any> = {
|
||||
function mapSortingToOrderBy(
|
||||
sorting: ArtworkTableInput["sorting"]
|
||||
): Prisma.ArtworkOrderByWithRelationInput[] {
|
||||
const allowed: Record<string, (desc: boolean) => Prisma.ArtworkOrderByWithRelationInput> = {
|
||||
createdAt: (desc) => ({ createdAt: desc ? "desc" : "asc" }),
|
||||
updatedAt: (desc) => ({ updatedAt: desc ? "desc" : "asc" }),
|
||||
sortIndex: (desc) => ({ sortIndex: desc ? "desc" : "asc" }),
|
||||
@ -25,9 +29,10 @@ function mapSortingToOrderBy(sorting: ArtworkTableInput["sorting"]) {
|
||||
tagsCount: (desc) => ({ tags: { _count: desc ? "desc" : "asc" } }),
|
||||
};
|
||||
|
||||
const orderBy = sorting
|
||||
.map((s) => allowed[s.id]?.(s.desc))
|
||||
.filter(Boolean);
|
||||
const orderBy = sorting.flatMap((s) => {
|
||||
const mapper = allowed[s.id];
|
||||
return mapper ? [mapper(s.desc)] : [];
|
||||
});
|
||||
|
||||
orderBy.push({ id: "desc" });
|
||||
return orderBy;
|
||||
@ -44,7 +49,7 @@ export async function getArtworksTablePage(input: unknown) {
|
||||
const nsfw = triToBool(filters.nsfw);
|
||||
const needsWork = triToBool(filters.needsWork);
|
||||
|
||||
const where: any = {
|
||||
const where: Prisma.ArtworkWhereInput = {
|
||||
...(typeof published === "boolean" ? { published } : {}),
|
||||
...(typeof nsfw === "boolean" ? { nsfw } : {}),
|
||||
...(typeof needsWork === "boolean" ? { needsWork } : {}),
|
||||
|
||||
@ -1,13 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { GalleryVariantStats } from "@/types/Artwork";
|
||||
|
||||
export type GalleryVariantStats = {
|
||||
total: number;
|
||||
withGallery: number;
|
||||
missing: number;
|
||||
};
|
||||
|
||||
// Returns counts for gallery variant presence.
|
||||
export async function getGalleryVariantStats(): Promise<GalleryVariantStats> {
|
||||
const [total, withGallery] = await Promise.all([
|
||||
prisma.artwork.count(),
|
||||
|
||||
@ -2,25 +2,30 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { s3 } from "@/lib/s3";
|
||||
import {
|
||||
confirmArtworkTimelapseUploadSchema,
|
||||
createArtworkTimelapseUploadSchema,
|
||||
deleteArtworkTimelapseSchema,
|
||||
setArtworkTimelapseEnabledSchema,
|
||||
} from "@/schemas/artworks/timelapse";
|
||||
import type {
|
||||
ConfirmArtworkTimelapseUploadInput,
|
||||
CreateArtworkTimelapseUploadInput,
|
||||
DeleteArtworkTimelapseInput,
|
||||
SetArtworkTimelapseEnabledInput,
|
||||
} from "@/schemas/artworks/timelapse";
|
||||
import { PutObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod/v4";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
const createUploadSchema = z.object({
|
||||
artworkId: z.string().min(1),
|
||||
fileName: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates a presigned PUT url so the client can upload large timelapse videos directly to S3
|
||||
* (avoids Next.js body-size/proxy limits).
|
||||
*/
|
||||
export async function createArtworkTimelapseUpload(input: z.infer<typeof createUploadSchema>) {
|
||||
const { artworkId, fileName, mimeType, sizeBytes } = createUploadSchema.parse(input);
|
||||
export async function createArtworkTimelapseUpload(input: CreateArtworkTimelapseUploadInput) {
|
||||
const { artworkId, fileName, mimeType, sizeBytes } =
|
||||
createArtworkTimelapseUploadSchema.parse(input);
|
||||
|
||||
const ext = fileName.includes(".") ? fileName.split(".").pop() : undefined;
|
||||
const suffix = ext ? `.${ext}` : "";
|
||||
@ -41,17 +46,10 @@ export async function createArtworkTimelapseUpload(input: z.infer<typeof createU
|
||||
return { uploadUrl, s3Key, fileName, mimeType, sizeBytes };
|
||||
}
|
||||
|
||||
const confirmSchema = z.object({
|
||||
artworkId: z.string().min(1),
|
||||
s3Key: z.string().min(1),
|
||||
fileName: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/** Persist uploaded timelapse metadata in DB (upsert by artworkId). */
|
||||
export async function confirmArtworkTimelapseUpload(input: z.infer<typeof confirmSchema>) {
|
||||
const { artworkId, s3Key, fileName, mimeType, sizeBytes } = confirmSchema.parse(input);
|
||||
export async function confirmArtworkTimelapseUpload(input: ConfirmArtworkTimelapseUploadInput) {
|
||||
const { artworkId, s3Key, fileName, mimeType, sizeBytes } =
|
||||
confirmArtworkTimelapseUploadSchema.parse(input);
|
||||
|
||||
// If an old timelapse exists, delete the old object so you don't leak storage.
|
||||
const existing = await prisma.artworkTimelapse.findUnique({ where: { artworkId } });
|
||||
@ -91,13 +89,8 @@ export async function confirmArtworkTimelapseUpload(input: z.infer<typeof confir
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const enabledSchema = z.object({
|
||||
artworkId: z.string().min(1),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export async function setArtworkTimelapseEnabled(input: z.infer<typeof enabledSchema>) {
|
||||
const { artworkId, enabled } = enabledSchema.parse(input);
|
||||
export async function setArtworkTimelapseEnabled(input: SetArtworkTimelapseEnabledInput) {
|
||||
const { artworkId, enabled } = setArtworkTimelapseEnabledSchema.parse(input);
|
||||
|
||||
await prisma.artworkTimelapse.update({
|
||||
where: { artworkId },
|
||||
@ -108,12 +101,8 @@ export async function setArtworkTimelapseEnabled(input: z.infer<typeof enabledSc
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const deleteSchema = z.object({
|
||||
artworkId: z.string().min(1),
|
||||
});
|
||||
|
||||
export async function deleteArtworkTimelapse(input: z.infer<typeof deleteSchema>) {
|
||||
const { artworkId } = deleteSchema.parse(input);
|
||||
export async function deleteArtworkTimelapse(input: DeleteArtworkTimelapseInput) {
|
||||
const { artworkId } = deleteArtworkTimelapseSchema.parse(input);
|
||||
|
||||
const existing = await prisma.artworkTimelapse.findUnique({ where: { artworkId } });
|
||||
if (!existing) return { ok: true };
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { artworkSchema } from "@/schemas/artworks/imageSchema";
|
||||
import { normalizeNames, slugify } from "@/utils/artworkHelpers";
|
||||
import { z } from "zod/v4";
|
||||
import type { z } from "zod/v4";
|
||||
|
||||
// Updates an artwork and its tag/category relationships.
|
||||
export async function updateArtwork(
|
||||
values: z.infer<typeof artworkSchema>,
|
||||
id: string
|
||||
@ -36,12 +37,11 @@ export async function updateArtwork(
|
||||
const categoriesToCreate = normalizeNames(newCategoryNames);
|
||||
|
||||
const updatedArtwork = await prisma.$transaction(async (tx) => {
|
||||
|
||||
if (setAsHeader) {
|
||||
await tx.artwork.updateMany({
|
||||
where: { setAsHeader: true },
|
||||
data: { setAsHeader: false },
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
const tagsRelation =
|
||||
@ -73,7 +73,7 @@ export async function updateArtwork(
|
||||
: {};
|
||||
|
||||
return tx.artwork.update({
|
||||
where: { id: id },
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
|
||||
@ -2,28 +2,25 @@
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { z } from "zod/v4";
|
||||
import type { RegisterFirstUserInput } from "@/schemas/auth";
|
||||
import { registerFirstUserSchema } from "@/schemas/auth";
|
||||
import type { SignUpResponse } from "@/types/auth";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
email: z.string().email().max(320),
|
||||
password: z.string().min(8).max(128),
|
||||
});
|
||||
|
||||
export async function registerFirstUser(input: z.infer<typeof schema>) {
|
||||
// Registers the very first user and upgrades them to admin.
|
||||
export async function registerFirstUser(input: RegisterFirstUserInput) {
|
||||
const count = await prisma.user.count();
|
||||
if (count !== 0) throw new Error("Registration is disabled.");
|
||||
|
||||
const { name, email, password } = schema.parse(input);
|
||||
const { name, email, password } = registerFirstUserSchema.parse(input);
|
||||
|
||||
const res = await auth.api.signUpEmail({
|
||||
const res = (await auth.api.signUpEmail({
|
||||
body: { name, email, password },
|
||||
});
|
||||
})) as SignUpResponse;
|
||||
|
||||
const userId =
|
||||
(res as any)?.user?.id ??
|
||||
(res as any)?.data?.user?.id ??
|
||||
(res as any)?.data?.id;
|
||||
res.user?.id ??
|
||||
res.data?.user?.id ??
|
||||
res.data?.id;
|
||||
|
||||
if (!userId) throw new Error("Signup failed: no user id returned.");
|
||||
|
||||
|
||||
@ -1,25 +1,27 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { categorySchema } from "@/schemas/artworks/categorySchema"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { categorySchema } from "@/schemas/artworks/categorySchema";
|
||||
import type * as z from "zod/v4";
|
||||
|
||||
export async function createCategory(formData: categorySchema) {
|
||||
const parsed = categorySchema.safeParse(formData)
|
||||
// Creates a new artwork category.
|
||||
export async function createCategory(formData: z.infer<typeof categorySchema>) {
|
||||
const parsed = categorySchema.safeParse(formData);
|
||||
|
||||
if (!parsed.success) {
|
||||
console.error("Validation failed", parsed.error)
|
||||
throw new Error("Invalid input")
|
||||
console.error("Validation failed", parsed.error);
|
||||
throw new Error("Invalid input");
|
||||
}
|
||||
|
||||
const data = parsed.data
|
||||
const data = parsed.data;
|
||||
|
||||
const created = await prisma.artCategory.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
description: data.description
|
||||
description: data.description,
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
return created
|
||||
return created;
|
||||
}
|
||||
@ -3,6 +3,7 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
// Deletes a category if it is not referenced by artworks or tags.
|
||||
export async function deleteCategory(catId: string) {
|
||||
const cat = await prisma.artCategory.findUnique({
|
||||
where: { id: catId },
|
||||
@ -11,7 +12,7 @@ export async function deleteCategory(catId: string) {
|
||||
_count: {
|
||||
select: {
|
||||
tagLinks: true,
|
||||
artworks: true
|
||||
artworks: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@ -1,19 +1,20 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Category data fetchers for admin pages.
|
||||
export async function getCategoriesWithTags() {
|
||||
return await prisma.artCategory.findMany({
|
||||
return prisma.artCategory.findMany({
|
||||
include: { tagLinks: { include: { tag: true } } },
|
||||
orderBy: { sortIndex: "asc" },
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCategoriesWithCount() {
|
||||
return await prisma.artCategory.findMany({
|
||||
return prisma.artCategory.findMany({
|
||||
include: {
|
||||
_count: { select: { artworks: true, tagLinks: true } },
|
||||
},
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,27 +1,28 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { categorySchema } from '@/schemas/artworks/categorySchema';
|
||||
import { z } from 'zod/v4';
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { categorySchema } from "@/schemas/artworks/categorySchema";
|
||||
import type * as z from "zod/v4";
|
||||
|
||||
// Updates an artwork category by id.
|
||||
export async function updateCategory(id: string, rawData: z.infer<typeof categorySchema>) {
|
||||
const parsed = categorySchema.safeParse(rawData)
|
||||
const parsed = categorySchema.safeParse(rawData);
|
||||
|
||||
if (!parsed.success) {
|
||||
console.error("Validation failed", parsed.error)
|
||||
throw new Error("Invalid input")
|
||||
console.error("Validation failed", parsed.error);
|
||||
throw new Error("Invalid input");
|
||||
}
|
||||
|
||||
const data = parsed.data
|
||||
const data = parsed.data;
|
||||
|
||||
const updated = await prisma.artCategory.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
description: data.description
|
||||
description: data.description,
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
return updated
|
||||
return updated;
|
||||
}
|
||||
@ -1,16 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { ArtworkColorStats } from "@/types/colors";
|
||||
|
||||
export type ArtworkColorStats = {
|
||||
total: number;
|
||||
ready: number;
|
||||
pending: number;
|
||||
processing: number;
|
||||
failed: number;
|
||||
missingSortKey: number;
|
||||
};
|
||||
|
||||
// Aggregates color-processing status counts for artworks.
|
||||
export async function getArtworkColorStats(): Promise<ArtworkColorStats> {
|
||||
const [
|
||||
total,
|
||||
|
||||
@ -3,15 +3,9 @@
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { generateArtworkColorsForArtwork } from "../artworks/generateArtworkColors";
|
||||
import type { ProcessColorsResult } from "@/types/colors";
|
||||
|
||||
export type ProcessColorsResult = {
|
||||
picked: number;
|
||||
processed: number;
|
||||
ok: number;
|
||||
failed: number;
|
||||
results: Array<{ artworkId: string; ok: boolean; error?: string }>;
|
||||
};
|
||||
|
||||
// Processes pending/failed artwork colors with a configurable batch size.
|
||||
export async function processPendingArtworkColors(args?: {
|
||||
limit?: number;
|
||||
includeFailed?: boolean;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Deletes a custom commission card by id.
|
||||
export async function deleteCommissionCustomCard(id: string) {
|
||||
await prisma.commissionCustomCard.delete({
|
||||
where: { id },
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { s3 } from "@/lib/s3";
|
||||
import type { CommissionCustomCardImageItem } from "@/types/commissions";
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
@ -9,13 +10,6 @@ import {
|
||||
|
||||
const PREFIX = "commissions/custom-cards/";
|
||||
|
||||
export type CommissionCustomCardImageItem = {
|
||||
key: string;
|
||||
url: string;
|
||||
size: number | null;
|
||||
lastModified: string | null;
|
||||
};
|
||||
|
||||
function buildImageUrl(key: string) {
|
||||
return `/api/image/${encodeURI(key)}`;
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ import {
|
||||
type CommissionCustomCardValues,
|
||||
} from "@/schemas/commissionCustomCard";
|
||||
|
||||
// Creates a new custom commission card with options/extras.
|
||||
export async function createCommissionCustomCard(
|
||||
formData: CommissionCustomCardValues
|
||||
) {
|
||||
|
||||
@ -6,6 +6,7 @@ import {
|
||||
type CommissionCustomCardValues,
|
||||
} from "@/schemas/commissionCustomCard";
|
||||
|
||||
// Updates a custom commission card and resets related options/extras.
|
||||
export async function updateCommissionCustomCard(
|
||||
id: string,
|
||||
rawData: CommissionCustomCardValues
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Updates sort order for custom commission cards.
|
||||
export async function updateCommissionCustomCardSortOrder(
|
||||
items: { id: string; sortIndex: number }[]
|
||||
) {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { s3 } from "@/lib/s3";
|
||||
import type { CommissionExampleItem } from "@/types/commissions";
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
@ -9,13 +10,6 @@ import {
|
||||
|
||||
const PREFIX = "commissions/examples/";
|
||||
|
||||
export type CommissionExampleItem = {
|
||||
key: string;
|
||||
url: string;
|
||||
size: number | null;
|
||||
lastModified: string | null;
|
||||
};
|
||||
|
||||
function buildImageUrl(key: string) {
|
||||
return `/api/image/${encodeURI(key)}`;
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns the latest active commission guidelines (markdown + example image).
|
||||
export async function getActiveGuidelines(): Promise<{
|
||||
markdown: string | null;
|
||||
exampleImageUrl: string | null;
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Deactivates existing guidelines and creates a new active version.
|
||||
export async function saveGuidelines(markdown: string, exampleImageUrl: string | null) {
|
||||
await prisma.commissionGuidelines.updateMany({
|
||||
where: { isActive: true },
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { z } from "zod";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
// Deletes a commission request by id.
|
||||
export async function deleteCommissionRequest(id: string) {
|
||||
const parsed = z.string().min(1).parse(id);
|
||||
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { calculatePriceRange, PriceSource } from "@/utils/commissionPricing";
|
||||
import { calculatePriceRange, type PriceSource } from "@/utils/commissionPricing";
|
||||
|
||||
// Loads a commission request with related data and computed price estimate.
|
||||
export async function getCommissionRequestById(id: string) {
|
||||
const req = await prisma.commissionRequest.findUnique({
|
||||
where: { id },
|
||||
|
||||
@ -1,39 +1,24 @@
|
||||
"use server";
|
||||
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
commissionRequestTableRowSchema,
|
||||
commissionStatusSchema,
|
||||
} from "@/schemas/commissions/requests";
|
||||
import { z } from "zod";
|
||||
|
||||
export type CursorPagination = { pageIndex: number; pageSize: number };
|
||||
export type SortDir = "asc" | "desc";
|
||||
|
||||
const triStateSchema = z.enum(["any", "true", "false"]);
|
||||
|
||||
const sortingSchema = z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
desc: z.boolean(),
|
||||
})
|
||||
);
|
||||
|
||||
const filtersSchema = z.object({
|
||||
q: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
status: z.union([z.literal("any"), commissionStatusSchema]).default("any"),
|
||||
hasFiles: triStateSchema.default("any"),
|
||||
});
|
||||
import { commissionRequestTableRowSchema } from "@/schemas/commissions/requests";
|
||||
import type {
|
||||
CommissionRequestsTableFilters,
|
||||
CommissionRequestsTableSorting,
|
||||
} from "@/schemas/commissions/requestsTable";
|
||||
import type { CursorPagination } from "@/types/pagination";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
// Builds a paginated, filtered, and sorted commission-requests table payload for the admin UI.
|
||||
export async function getCommissionRequestsTablePage(input: {
|
||||
pagination: CursorPagination;
|
||||
sorting: z.infer<typeof sortingSchema>;
|
||||
filters: z.infer<typeof filtersSchema>;
|
||||
sorting: CommissionRequestsTableSorting;
|
||||
filters: CommissionRequestsTableFilters;
|
||||
}) {
|
||||
const { pagination, sorting, filters } = input;
|
||||
|
||||
const where: any = {};
|
||||
const where: Prisma.CommissionRequestWhereInput = {};
|
||||
|
||||
if (filters.q) {
|
||||
const q = filters.q.trim();
|
||||
@ -60,7 +45,7 @@ export async function getCommissionRequestsTablePage(input: {
|
||||
|
||||
// sorting
|
||||
const sort = sorting?.[0] ?? { id: "createdAt", desc: true };
|
||||
const orderBy: any =
|
||||
const orderBy: Prisma.CommissionRequestOrderByWithRelationInput =
|
||||
sort.id === "createdAt"
|
||||
? { createdAt: sort.desc ? "desc" : "asc" }
|
||||
: sort.id === "status"
|
||||
@ -94,7 +79,7 @@ export async function getCommissionRequestsTablePage(input: {
|
||||
customerName: r.customerName,
|
||||
customerEmail: r.customerEmail,
|
||||
customerSocials: r.customerSocials ?? null,
|
||||
status: r.status as any,
|
||||
status: r.status,
|
||||
fileCount: r._count.files,
|
||||
}));
|
||||
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { commissionStatusSchema } from "@/schemas/commissions/requests";
|
||||
import { z } from "zod";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
// Sets a commission request status (admin action).
|
||||
export async function setCommissionRequestStatus(input: {
|
||||
id: string;
|
||||
status: z.infer<typeof commissionStatusSchema>;
|
||||
|
||||
@ -1,20 +1,14 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { commissionStatusSchema } from "@/schemas/commissions/requests";
|
||||
import { z } from "zod/v4";
|
||||
import {
|
||||
updateCommissionRequestSchema,
|
||||
} from "@/schemas/commissions/updateRequest";
|
||||
import type { UpdateCommissionRequestInput } from "@/schemas/commissions/updateRequest";
|
||||
|
||||
const updateSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
status: commissionStatusSchema,
|
||||
customerName: z.string().min(1).max(200),
|
||||
customerEmail: z.string().email().max(320),
|
||||
customerSocials: z.string().max(2000).optional().nullable(),
|
||||
message: z.string().min(1).max(20_000),
|
||||
});
|
||||
|
||||
export async function updateCommissionRequest(input: z.infer<typeof updateSchema>) {
|
||||
const data = updateSchema.parse(input);
|
||||
// Updates editable fields on a commission request.
|
||||
export async function updateCommissionRequest(input: UpdateCommissionRequestInput) {
|
||||
const data = updateCommissionRequestSchema.parse(input);
|
||||
|
||||
await prisma.commissionRequest.update({
|
||||
where: { id: data.id },
|
||||
|
||||
@ -1,21 +1,18 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
|
||||
import { COMMISSION_STATUSES } from "@/lib/commissions/kanban";
|
||||
import { prisma } from "@/lib/prisma"; // adjust to your prisma import
|
||||
// import { requireAdmin } from "@/lib/auth/requireAdmin"; // recommended if you have it
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
updateCommissionRequestStatusSchema,
|
||||
} from "@/schemas/commissions/updateRequestStatus";
|
||||
import type { UpdateCommissionRequestStatusInput } from "@/schemas/commissions/updateRequestStatus";
|
||||
|
||||
const schema = z.object({
|
||||
id: z.string().min(1),
|
||||
status: z.enum(COMMISSION_STATUSES),
|
||||
});
|
||||
|
||||
export async function updateCommissionRequestStatus(input: z.infer<typeof schema>) {
|
||||
// await requireAdmin(); // enforce auth/role check here
|
||||
|
||||
const { id, status } = schema.parse(input);
|
||||
// Updates a commission request status and revalidates the kanban page.
|
||||
export async function updateCommissionRequestStatus(
|
||||
input: UpdateCommissionRequestStatusInput
|
||||
) {
|
||||
const { id, status } = updateCommissionRequestStatusSchema.parse(input);
|
||||
|
||||
await prisma.commissionRequest.update({
|
||||
where: { id },
|
||||
@ -23,5 +20,5 @@ export async function updateCommissionRequestStatus(input: z.infer<typeof schema
|
||||
});
|
||||
|
||||
// revalidate the board page so a refresh always reflects server truth
|
||||
revalidatePath("/commissions/board");
|
||||
revalidatePath("/commissions/kanban");
|
||||
}
|
||||
|
||||
@ -1,19 +1,18 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Deletes a commission type and its link records.
|
||||
export async function deleteCommissionType(typeId: string) {
|
||||
|
||||
await prisma.commissionTypeOption.deleteMany({
|
||||
where: { typeId },
|
||||
})
|
||||
});
|
||||
|
||||
await prisma.commissionTypeExtra.deleteMany({
|
||||
where: { typeId },
|
||||
})
|
||||
});
|
||||
|
||||
await prisma.commissionType.delete({
|
||||
where: { id: typeId },
|
||||
})
|
||||
|
||||
});
|
||||
}
|
||||
@ -4,8 +4,9 @@ import { prisma } from "@/lib/prisma";
|
||||
import { commissionExtraSchema } from "@/schemas/commissionType";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
const LIST_PATH = "/commissions/extras";
|
||||
const LIST_PATH = "/commissions/types/extras";
|
||||
|
||||
// CRUD helpers for commission extras (admin-only pages).
|
||||
export async function createCommissionExtra(input: unknown) {
|
||||
const data = commissionExtraSchema.parse(input);
|
||||
const created = await prisma.commissionExtra.create({ data });
|
||||
@ -24,7 +25,6 @@ export async function deleteCommissionExtra(id: string) {
|
||||
// Optional safety:
|
||||
// const used = await prisma.commissionTypeExtra.count({ where: { extraId: id } });
|
||||
// if (used > 0) throw new Error("Extra is linked to types.");
|
||||
console.log("TBD");
|
||||
// await prisma.commissionExtra.delete({ where: { id } });
|
||||
// revalidatePath(LIST_PATH);
|
||||
await prisma.commissionExtra.delete({ where: { id } });
|
||||
revalidatePath(LIST_PATH);
|
||||
}
|
||||
|
||||
@ -2,9 +2,11 @@
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { commissionTypeSchema } from "@/schemas/commissionType";
|
||||
import type * as z from "zod/v4";
|
||||
|
||||
// Creates a commission option entry.
|
||||
export async function createCommissionOption(data: { name: string }) {
|
||||
return await prisma.commissionOption.create({
|
||||
return prisma.commissionOption.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
description: "",
|
||||
@ -12,8 +14,9 @@ export async function createCommissionOption(data: { name: string }) {
|
||||
});
|
||||
}
|
||||
|
||||
// Creates a commission extra entry.
|
||||
export async function createCommissionExtra(data: { name: string }) {
|
||||
return await prisma.commissionExtra.create({
|
||||
return prisma.commissionExtra.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
description: "",
|
||||
@ -21,11 +24,12 @@ export async function createCommissionExtra(data: { name: string }) {
|
||||
});
|
||||
}
|
||||
|
||||
// Creates a commission custom input entry.
|
||||
export async function createCommissionCustomInput(data: {
|
||||
name: string;
|
||||
fieldId: string;
|
||||
}) {
|
||||
return await prisma.commissionCustomInput.create({
|
||||
return prisma.commissionCustomInput.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
fieldId: data.fieldId,
|
||||
@ -33,7 +37,10 @@ export async function createCommissionCustomInput(data: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function createCommissionType(formData: commissionTypeSchema) {
|
||||
// Creates a commission type with nested options/extras/custom inputs.
|
||||
export async function createCommissionType(
|
||||
formData: z.infer<typeof commissionTypeSchema>
|
||||
) {
|
||||
const parsed = commissionTypeSchema.safeParse(formData);
|
||||
|
||||
if (!parsed.success) {
|
||||
|
||||
@ -4,13 +4,9 @@ import { prisma } from "@/lib/prisma";
|
||||
import { commissionOptionSchema } from "@/schemas/commissionType";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
const LIST_PATH = "/commissions/options";
|
||||
|
||||
function toInt(v: string) {
|
||||
const n = Number.parseInt(v, 10);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
const LIST_PATH = "/commissions/types/options";
|
||||
|
||||
// CRUD helpers for commission options (admin-only pages).
|
||||
export async function createCommissionOption(input: unknown) {
|
||||
const data = commissionOptionSchema.parse(input);
|
||||
const created = await prisma.commissionOption.create({
|
||||
@ -37,7 +33,6 @@ export async function updateCommissionOption(id: string, input: unknown) {
|
||||
}
|
||||
|
||||
export async function deleteCommissionOption(id: string) {
|
||||
console.log("TBD");
|
||||
// await prisma.commissionOption.delete({ where: { id } });
|
||||
// revalidatePath(LIST_PATH);
|
||||
await prisma.commissionOption.delete({ where: { id } });
|
||||
revalidatePath(LIST_PATH);
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Updates sort order for commission types.
|
||||
export async function updateCommissionTypeSortOrder(
|
||||
ordered: { id: string; sortIndex: number }[]
|
||||
) {
|
||||
@ -10,7 +11,7 @@ export async function updateCommissionTypeSortOrder(
|
||||
where: { id },
|
||||
data: { sortIndex },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
await Promise.all(updates)
|
||||
await Promise.all(updates);
|
||||
}
|
||||
@ -4,9 +4,10 @@ import { prisma } from "@/lib/prisma";
|
||||
import { commissionTypeSchema } from "@/schemas/commissionType";
|
||||
import type * as z from "zod/v4";
|
||||
|
||||
// Updates a commission type and resets related nested records.
|
||||
export async function updateCommissionType(
|
||||
id: string,
|
||||
rawData: z.infer<typeof commissionTypeSchema>,
|
||||
rawData: z.infer<typeof commissionTypeSchema>
|
||||
) {
|
||||
const data = commissionTypeSchema.parse(rawData);
|
||||
|
||||
|
||||
@ -1,12 +1,10 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { CountRow } from "@/types/dashboard";
|
||||
|
||||
type CountRow<K extends string> = {
|
||||
[P in K]: string;
|
||||
} & { _count: { _all: number } };
|
||||
|
||||
function toCountMapSafe(rows: any[], key: string) {
|
||||
// Aggregates dashboard stats for admin overview cards and tables.
|
||||
function toCountMapSafe<K extends string>(rows: Array<CountRow<K>>, key: K) {
|
||||
const out: Record<string, number> = {};
|
||||
for (const r of rows) out[String(r[key])] = Number(r?._count?._all ?? 0);
|
||||
return out;
|
||||
|
||||
@ -1,17 +1,19 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { TagFormInput, tagSchema } from "@/schemas/artworks/tagSchema"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { tagSchema } from "@/schemas/artworks/tagSchema";
|
||||
import type { TagFormInput } from "@/schemas/artworks/tagSchema";
|
||||
|
||||
// Creates a tag and related category links/aliases.
|
||||
export async function createTag(formData: TagFormInput) {
|
||||
const parsed = tagSchema.safeParse(formData)
|
||||
const parsed = tagSchema.safeParse(formData);
|
||||
|
||||
if (!parsed.success) {
|
||||
console.error("Validation failed", parsed.error)
|
||||
throw new Error("Invalid input")
|
||||
console.error("Validation failed", parsed.error);
|
||||
throw new Error("Invalid input");
|
||||
}
|
||||
|
||||
const data = parsed.data
|
||||
const data = parsed.data;
|
||||
|
||||
const parentId = data.parentId ?? null;
|
||||
const tagSlug = data.name.toLowerCase().replace(/\s+/g, "-");
|
||||
@ -52,5 +54,5 @@ export async function createTag(formData: TagFormInput) {
|
||||
return tag;
|
||||
});
|
||||
|
||||
return created
|
||||
return created;
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
// Deletes a tag if it has no artwork references or child tags.
|
||||
export async function deleteTag(tagId: string) {
|
||||
const tag = await prisma.tag.findUnique({
|
||||
where: { id: tagId },
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns tags ordered by sortIndex.
|
||||
export async function getTags() {
|
||||
return await prisma.tag.findMany({ orderBy: { sortIndex: "asc" } })
|
||||
return prisma.tag.findMany({ orderBy: { sortIndex: "asc" } });
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns true if possibleAncestorId is a descendant of tagId (cycle check).
|
||||
export async function isDescendant(tagId: string, possibleAncestorId: string): Promise<boolean> {
|
||||
// Walk upwards across any category hierarchy; if we hit tagId, it's a cycle.
|
||||
const visited = new Set<string>();
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { TagFormInput, tagSchema } from '@/schemas/artworks/tagSchema';
|
||||
import { isDescendant } from './isDescendant';
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { tagSchema } from "@/schemas/artworks/tagSchema";
|
||||
import type { TagFormInput } from "@/schemas/artworks/tagSchema";
|
||||
import { isDescendant } from "./isDescendant";
|
||||
|
||||
// Updates a tag and its category/alias relationships.
|
||||
export async function updateTag(id: string, rawData: TagFormInput) {
|
||||
const parsed = tagSchema.safeParse(rawData)
|
||||
const parsed = tagSchema.safeParse(rawData);
|
||||
|
||||
if (!parsed.success) {
|
||||
console.error("Validation failed", parsed.error)
|
||||
throw new Error("Invalid input")
|
||||
console.error("Validation failed", parsed.error);
|
||||
throw new Error("Invalid input");
|
||||
}
|
||||
|
||||
const data = parsed.data
|
||||
const data = parsed.data;
|
||||
|
||||
const parentId = data.parentId ?? null;
|
||||
const tagSlug = data.name.toLowerCase().replace(/\s+/g, "-");
|
||||
@ -111,5 +113,5 @@ export async function updateTag(id: string, rawData: TagFormInput) {
|
||||
return tag;
|
||||
});
|
||||
|
||||
return updated
|
||||
return updated;
|
||||
}
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Returns the most recent Terms of Service markdown.
|
||||
export async function getLatestTos(): Promise<string | null> {
|
||||
const tos = await prisma.termsOfService.findFirst({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return tos?.markdown ?? null;
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Saves a new Terms of Service version.
|
||||
export async function saveTosAction(markdown: string) {
|
||||
await prisma.termsOfService.create({
|
||||
data: {
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import { createImageFromFile } from "./createImageFromFile";
|
||||
import type { BulkResult } from "@/types/uploads";
|
||||
|
||||
type BulkResult =
|
||||
| { ok: true; artworkId: string; name: string }
|
||||
| { ok: false; name: string; error: string };
|
||||
|
||||
// Bulk image upload server action used by the admin UI.
|
||||
export async function createImagesBulk(formData: FormData): Promise<BulkResult[]> {
|
||||
const entries = formData.getAll("file");
|
||||
const files = entries.filter((x): x is File => x instanceof File);
|
||||
|
||||
@ -1,203 +1,12 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { fileUploadSchema } from "@/schemas/artworks/imageSchema";
|
||||
import type { fileUploadSchema } from "@/schemas/artworks/imageSchema";
|
||||
import "dotenv/config";
|
||||
import { z } from "zod/v4";
|
||||
import type { z } from "zod/v4";
|
||||
import { createImageFromFile } from "./createImageFromFile";
|
||||
|
||||
// Creates a single artwork image using the shared upload pipeline.
|
||||
export async function createImage(values: z.infer<typeof fileUploadSchema>) {
|
||||
const imageFile = values.file[0];
|
||||
return createImageFromFile(imageFile, { colorMode: "inline" });
|
||||
}
|
||||
|
||||
/*
|
||||
export async function createImage(values: z.infer<typeof fileUploadSchema>) {
|
||||
const imageFile = values.file[0];
|
||||
|
||||
if (!(imageFile instanceof File)) {
|
||||
console.log("No image or invalid type");
|
||||
return null;
|
||||
}
|
||||
|
||||
const fileName = imageFile.name;
|
||||
const fileType = imageFile.type;
|
||||
const fileSize = imageFile.size;
|
||||
const lastModified = new Date(imageFile.lastModified);
|
||||
|
||||
const fileKey = uuidv4();
|
||||
|
||||
const arrayBuffer = await imageFile.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const realFileType = fileType.split("/")[1];
|
||||
const originalKey = `original/${fileKey}.${realFileType}`;
|
||||
const modifiedKey = `modified/${fileKey}.webp`;
|
||||
const resizedKey = `resized/${fileKey}.webp`;
|
||||
const thumbnailKey = `thumbnail/${fileKey}.webp`;
|
||||
|
||||
const sharpData = sharp(buffer);
|
||||
const metadata = await sharpData.metadata();
|
||||
|
||||
//--- Original file
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: `${process.env.BUCKET_NAME}`,
|
||||
Key: originalKey,
|
||||
Body: buffer,
|
||||
ContentType: "image/" + metadata.format,
|
||||
})
|
||||
);
|
||||
//--- Modified file
|
||||
const modifiedBuffer = await sharp(buffer)
|
||||
.toFormat('webp')
|
||||
.toBuffer()
|
||||
const modifiedMetadata = await sharp(modifiedBuffer).metadata();
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: `${process.env.BUCKET_NAME}`,
|
||||
Key: modifiedKey,
|
||||
Body: modifiedBuffer,
|
||||
ContentType: "image/" + modifiedMetadata.format,
|
||||
})
|
||||
);
|
||||
//--- Resized file
|
||||
const { width, height } = modifiedMetadata;
|
||||
const targetSize = 400;
|
||||
let resizeOptions;
|
||||
if (width && height) {
|
||||
if (height < width) {
|
||||
resizeOptions = { height: targetSize };
|
||||
} else {
|
||||
resizeOptions = { width: targetSize };
|
||||
}
|
||||
} else {
|
||||
resizeOptions = { height: targetSize };
|
||||
}
|
||||
const resizedBuffer = await sharp(modifiedBuffer)
|
||||
.resize({ ...resizeOptions, withoutEnlargement: true })
|
||||
.toFormat('webp')
|
||||
.toBuffer();
|
||||
const resizedMetadata = await sharp(resizedBuffer).metadata();
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: `${process.env.BUCKET_NAME}`,
|
||||
Key: resizedKey,
|
||||
Body: resizedBuffer,
|
||||
ContentType: "image/" + resizedMetadata.format,
|
||||
})
|
||||
);
|
||||
//--- Thumbnail file
|
||||
const thumbnailTargetSize = 160;
|
||||
let thumbnailOptions;
|
||||
if (width && height) {
|
||||
if (height < width) {
|
||||
thumbnailOptions = { height: thumbnailTargetSize };
|
||||
} else {
|
||||
thumbnailOptions = { width: thumbnailTargetSize };
|
||||
}
|
||||
} else {
|
||||
thumbnailOptions = { height: thumbnailTargetSize };
|
||||
}
|
||||
const thumbnailBuffer = await sharp(modifiedBuffer)
|
||||
.resize({ ...thumbnailOptions, withoutEnlargement: true })
|
||||
.toFormat('webp')
|
||||
.toBuffer();
|
||||
const thumbnailMetadata = await sharp(thumbnailBuffer).metadata();
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: `${process.env.BUCKET_NAME}`,
|
||||
Key: thumbnailKey,
|
||||
Body: thumbnailBuffer,
|
||||
ContentType: "image/" + thumbnailMetadata.format,
|
||||
})
|
||||
);
|
||||
|
||||
const fileRecord = await prisma.fileData.create({
|
||||
data: {
|
||||
name: fileName,
|
||||
fileKey,
|
||||
originalFile: fileName,
|
||||
uploadDate: lastModified,
|
||||
fileType: realFileType,
|
||||
fileSize: fileSize,
|
||||
},
|
||||
});
|
||||
|
||||
const artworkSlug = fileName.toLowerCase().replace(/\s+/g, "-");
|
||||
const artworkRecord = await prisma.artwork.create({
|
||||
data: {
|
||||
name: fileName,
|
||||
slug: artworkSlug,
|
||||
creationDate: lastModified,
|
||||
fileId: fileRecord.id,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.artworkMetadata.create({
|
||||
data: {
|
||||
artworkId: artworkRecord.id,
|
||||
format: metadata.format || "unknown",
|
||||
width: metadata.width || 0,
|
||||
height: metadata.height || 0,
|
||||
space: metadata.space || "unknown",
|
||||
channels: metadata.channels || 0,
|
||||
depth: metadata.depth || "unknown",
|
||||
density: metadata.density ?? undefined,
|
||||
bitsPerSample: metadata.bitsPerSample ?? undefined,
|
||||
isProgressive: metadata.isProgressive ?? undefined,
|
||||
isPalette: metadata.isPalette ?? undefined,
|
||||
hasProfile: metadata.hasProfile ?? undefined,
|
||||
hasAlpha: metadata.hasAlpha ?? undefined,
|
||||
autoOrientW: metadata.autoOrient?.width ?? undefined,
|
||||
autoOrientH: metadata.autoOrient?.height ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.fileVariant.createMany({
|
||||
data: [
|
||||
{
|
||||
s3Key: originalKey,
|
||||
type: "original",
|
||||
height: metadata.height,
|
||||
width: metadata.width,
|
||||
fileExtension: metadata.format,
|
||||
mimeType: "image/" + metadata.format,
|
||||
sizeBytes: metadata.size,
|
||||
artworkId: artworkRecord.id
|
||||
},
|
||||
{
|
||||
s3Key: modifiedKey,
|
||||
type: "modified",
|
||||
height: modifiedMetadata.height,
|
||||
width: modifiedMetadata.width,
|
||||
fileExtension: modifiedMetadata.format,
|
||||
mimeType: "image/" + modifiedMetadata.format,
|
||||
sizeBytes: modifiedMetadata.size,
|
||||
artworkId: artworkRecord.id
|
||||
},
|
||||
{
|
||||
s3Key: resizedKey,
|
||||
type: "resized",
|
||||
height: resizedMetadata.height,
|
||||
width: resizedMetadata.width,
|
||||
fileExtension: resizedMetadata.format,
|
||||
mimeType: "image/" + resizedMetadata.format,
|
||||
sizeBytes: resizedMetadata.size,
|
||||
artworkId: artworkRecord.id
|
||||
},
|
||||
{
|
||||
s3Key: thumbnailKey,
|
||||
type: "thumbnail",
|
||||
height: thumbnailMetadata.height,
|
||||
width: thumbnailMetadata.width,
|
||||
fileExtension: thumbnailMetadata.format,
|
||||
mimeType: "image/" + thumbnailMetadata.format,
|
||||
sizeBytes: thumbnailMetadata.size,
|
||||
artworkId: artworkRecord.id
|
||||
}
|
||||
],
|
||||
});
|
||||
|
||||
return artworkRecord
|
||||
}
|
||||
*/
|
||||
@ -8,12 +8,12 @@ import sharp from "sharp";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { generateArtworkColorsForArtwork } from "../artworks/generateArtworkColors";
|
||||
|
||||
// Upload pipeline that generates variants and metadata, then creates artwork records.
|
||||
export async function createImageFromFile(
|
||||
imageFile: File,
|
||||
opts?: { originalName?: string; colorMode?: "inline" | "defer" | "off" },
|
||||
) {
|
||||
if (!(imageFile instanceof File)) {
|
||||
console.log("No image or invalid type");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@ -2,24 +2,20 @@
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { z } from "zod/v4";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
import { createUserSchema } from "@/schemas/users";
|
||||
import type { CreateUserInput } from "@/schemas/users";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
email: z.string().email().max(320),
|
||||
password: z.string().min(8).max(128),
|
||||
role: z.enum(["user", "admin"]).default("user"),
|
||||
});
|
||||
|
||||
export async function createUser(input: z.infer<typeof schema>) {
|
||||
// Creates a new user account (admin-only).
|
||||
export async function createUser(input: CreateUserInput) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
|
||||
if (!session || role !== "admin") {
|
||||
throw new Error("Forbidden");
|
||||
}
|
||||
|
||||
const data = schema.parse(input);
|
||||
const data = createUserSchema.parse(input);
|
||||
|
||||
return auth.api.createUser({
|
||||
body: {
|
||||
|
||||
@ -4,13 +4,15 @@ import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { headers } from "next/headers";
|
||||
import { z } from "zod/v4";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
|
||||
// Deletes a user account with safety checks (admin-only, cannot delete self or last admin).
|
||||
export async function deleteUser(id: string) {
|
||||
const userId = z.string().min(1).parse(id);
|
||||
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role as string | undefined;
|
||||
const currentUserId = (session as any)?.user?.id as string | undefined;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
const currentUserId = (session as SessionWithRole)?.user?.id;
|
||||
|
||||
if (!session || role !== "admin") throw new Error("Forbidden");
|
||||
if (!currentUserId) throw new Error("Session missing user id");
|
||||
@ -40,5 +42,5 @@ async function await_attachTarget(userId: string) {
|
||||
select: { id: true, role: true },
|
||||
});
|
||||
if (!target) throw new Error("User not found.");
|
||||
return target as { id: string; role: "admin" | "user" };
|
||||
return target;
|
||||
}
|
||||
|
||||
@ -2,21 +2,14 @@
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
import type { UserRole, UsersListRow } from "@/types/users";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export type UsersListRow = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string;
|
||||
role: "admin" | "user";
|
||||
emailVerified: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
// Returns all users for the admin users table.
|
||||
export async function getUsers(): Promise<UsersListRow[]> {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role as string | undefined;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
|
||||
if (!session || role !== "admin") {
|
||||
throw new Error("Forbidden");
|
||||
@ -35,5 +28,16 @@ export async function getUsers(): Promise<UsersListRow[]> {
|
||||
},
|
||||
});
|
||||
|
||||
return rows as UsersListRow[];
|
||||
return rows.map((r) => {
|
||||
if (r.role !== "admin" && r.role !== "user") {
|
||||
throw new Error(`Unexpected user role: ${r.role}`);
|
||||
}
|
||||
|
||||
return {
|
||||
...r,
|
||||
role: r.role as UserRole,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
updatedAt: r.updatedAt.toISOString(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@ -2,21 +2,20 @@
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { z } from "zod/v4";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
import { resendVerificationSchema } from "@/schemas/users";
|
||||
import type { ResendVerificationInput } from "@/schemas/users";
|
||||
|
||||
const schema = z.object({
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
export async function resendVerification(input: z.infer<typeof schema>) {
|
||||
// Resends a verification email for a user (admin-only).
|
||||
export async function resendVerification(input: ResendVerificationInput) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role as string | undefined;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
if (!session || role !== "admin") throw new Error("Forbidden");
|
||||
|
||||
const { email } = schema.parse(input);
|
||||
const { email } = resendVerificationSchema.parse(input);
|
||||
|
||||
// Uses the public auth route (same origin)
|
||||
const res = await fetch("http://localhost/api/auth/send-verification-email", {
|
||||
const res = await fetch(`${process.env.BETTER_AUTH_URL}/api/auth/send-verification-email`, {
|
||||
// NOTE: In production, you should use an absolute URL from env, or use authClient.
|
||||
// This is kept minimal; if you want, I'll refactor to authClient to avoid hostname concerns.
|
||||
method: "POST",
|
||||
|
||||
18
src/app/(admin)/about/page.tsx
Normal file
18
src/app/(admin)/about/page.tsx
Normal file
@ -0,0 +1,18 @@
|
||||
import { getLatestAboutMe } from "@/actions/about/getAbout";
|
||||
import AboutEditor from "@/components/about/Editor";
|
||||
|
||||
// Admin page for editing About Me content.
|
||||
export default async function AboutPage() {
|
||||
const markdown = await getLatestAboutMe();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex gap-4 justify-between pb-8">
|
||||
<h1 className="text-2xl font-bold mb-4">About Me</h1>
|
||||
</div>
|
||||
<div className="space-y-4 p-1 border rounded-xl bg-muted/20">
|
||||
<AboutEditor markdown={markdown} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -8,6 +8,7 @@ import ArtworkVariants from "@/components/artworks/single/ArtworkVariants";
|
||||
import DeleteArtworkButton from "@/components/artworks/single/DeleteArtworkButton";
|
||||
import EditArtworkForm from "@/components/artworks/single/EditArtworkForm";
|
||||
|
||||
// Single artwork edit page.
|
||||
export default async function ArtworkSinglePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
|
||||
@ -16,30 +17,30 @@ export default async function ArtworkSinglePage({ params }: { params: Promise<{
|
||||
const categories = await getCategoriesWithTags();
|
||||
const tags = await getTags();
|
||||
|
||||
if (!item) return <div>Artwork with this id not found</div>
|
||||
if (!item) return <div>Artwork with this id not found</div>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-4">Edit artwork</h1>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||
<div className="space-y-6">
|
||||
{item ? <EditArtworkForm artwork={item} tags={tags} categories={categories} /> : 'Artwork not found...'}
|
||||
<EditArtworkForm artwork={item} tags={tags} categories={categories} />
|
||||
<div>
|
||||
{item && <DeleteArtworkButton artworkId={item.id} />}
|
||||
<DeleteArtworkButton artworkId={item.id} />
|
||||
</div>
|
||||
<div>
|
||||
{item && <ArtworkTimelapse artworkId={item.id} timelapse={item.timelapse} />}
|
||||
<ArtworkTimelapse artworkId={item.id} timelapse={item.timelapse} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
{item && <ArtworkColors colors={item.colors} artworkId={item.id} />}
|
||||
<ArtworkColors colors={item.colors} artworkId={item.id} />
|
||||
</div>
|
||||
<div>
|
||||
{item && <ArtworkDetails artwork={item} />}
|
||||
<ArtworkDetails artwork={item} />
|
||||
</div>
|
||||
<div>
|
||||
{item && <ArtworkVariants artworkId={item.id} variants={item.variants} />}
|
||||
<ArtworkVariants artworkId={item.id} variants={item.variants} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { ArtworkColorProcessor } from "@/components/artworks/ArtworkColorProcessor";
|
||||
import { ArtworksTable } from "@/components/artworks/ArtworksTable";
|
||||
|
||||
// Admin artworks list page.
|
||||
export default async function ArtworksPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
import EditCategoryForm from "@/components/categories/EditCategoryForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Edit category page.
|
||||
export default async function PortfolioCategoriesEditPage({ params }: { params: { id: string } }) {
|
||||
const { id } = await params;
|
||||
const category = await prisma.artCategory.findUnique({
|
||||
where: {
|
||||
id,
|
||||
}
|
||||
})
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import NewCategoryForm from "@/components/categories/NewCategoryForm";
|
||||
|
||||
// Create a new category page.
|
||||
export default function PortfolioCategoriesNewPage() {
|
||||
return (
|
||||
<div>
|
||||
|
||||
@ -4,6 +4,7 @@ import { PlusCircleIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { Suspense } from "react";
|
||||
|
||||
// Admin categories management page.
|
||||
export default async function CategoriesPage() {
|
||||
const items = await getCategoriesWithCount();
|
||||
|
||||
@ -11,7 +12,10 @@ export default async function CategoriesPage() {
|
||||
<div>
|
||||
<div className="flex gap-4 justify-between pb-8">
|
||||
<h1 className="text-2xl font-bold mb-4">Art Categories</h1>
|
||||
<Link href="/categories/new" className="flex gap-2 items-center cursor-pointer bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded">
|
||||
<Link
|
||||
href="/categories/new"
|
||||
className="flex gap-2 items-center cursor-pointer bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded"
|
||||
>
|
||||
<PlusCircleIcon className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all text-primary-foreground" /> Add new category
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { listCommissionCustomCardImages } from "@/actions/commissions/customCards/images";
|
||||
import EditCustomCardForm from "@/components/commissions/customCards/EditCustomCardForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
// Edit custom commission card page.
|
||||
export default async function CommissionCustomCardEditPage({
|
||||
params,
|
||||
}: {
|
||||
@ -10,7 +10,7 @@ export default async function CommissionCustomCardEditPage({
|
||||
}) {
|
||||
const { id } = await params;
|
||||
|
||||
const [card, options, extras, images, tags] = await Promise.all([
|
||||
const [card, options, extras, tags] = await Promise.all([
|
||||
prisma.commissionCustomCard.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
@ -21,7 +21,6 @@ export default async function CommissionCustomCardEditPage({
|
||||
}),
|
||||
prisma.commissionOption.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
prisma.commissionExtra.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
listCommissionCustomCardImages(),
|
||||
prisma.tag.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
]);
|
||||
|
||||
@ -38,7 +37,6 @@ export default async function CommissionCustomCardEditPage({
|
||||
card={card}
|
||||
allOptions={options}
|
||||
allExtras={extras}
|
||||
images={images}
|
||||
allTags={tags}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { listCommissionCustomCardImages } from "@/actions/commissions/customCards/images";
|
||||
import NewCustomCardForm from "@/components/commissions/customCards/NewCustomCardForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// New custom commission card page.
|
||||
export default async function CommissionCustomCardsNewPage() {
|
||||
const [options, extras, images, tags] = await Promise.all([
|
||||
const [options, extras, tags] = await Promise.all([
|
||||
prisma.commissionOption.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
prisma.commissionExtra.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
listCommissionCustomCardImages(),
|
||||
prisma.tag.findMany({ orderBy: [{ sortIndex: "asc" }, { name: "asc" }] }),
|
||||
]);
|
||||
|
||||
@ -15,7 +14,7 @@ export default async function CommissionCustomCardsNewPage() {
|
||||
<div className="flex gap-4 justify-between pb-8">
|
||||
<h1 className="text-2xl font-bold mb-4">New Custom Commission Card</h1>
|
||||
</div>
|
||||
<NewCustomCardForm options={options} extras={extras} images={images} tags={tags} />
|
||||
<NewCustomCardForm options={options} extras={extras} tags={tags} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma";
|
||||
import { PlusCircleIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
// Custom commission cards list page.
|
||||
export default async function CommissionCustomCardsPage() {
|
||||
const cards = await prisma.commissionCustomCard.findMany({
|
||||
include: {
|
||||
|
||||
@ -2,6 +2,7 @@ import { listCommissionExamples } from "@/actions/commissions/examples";
|
||||
import { getActiveGuidelines } from "@/actions/commissions/guidelines/getGuidelines";
|
||||
import GuidelinesEditor from "@/components/commissions/guidelines/Editor";
|
||||
|
||||
// Admin page for editing commission guidelines.
|
||||
export default async function CommissionGuidelinesPage() {
|
||||
const [{ markdown, exampleImageUrl }, examples] = await Promise.all([
|
||||
getActiveGuidelines(),
|
||||
|
||||
@ -4,6 +4,7 @@ import { prisma } from "@/lib/prisma";
|
||||
|
||||
import type { BoardItem, ColumnsState } from "@/types/Board";
|
||||
|
||||
// Admin kanban page for commission requests.
|
||||
export default async function CommissionsBoardPage() {
|
||||
const requests = await prisma.commissionRequest.findMany({
|
||||
where: {
|
||||
|
||||
@ -2,6 +2,7 @@ import { getCommissionRequestById } from "@/actions/commissions/requests/getComm
|
||||
import { CommissionRequestEditor } from "@/components/commissions/requests/CommissionRequestEditor";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
// Admin page for editing a single commission request.
|
||||
export default async function CommissionRequestPage({
|
||||
params,
|
||||
}: {
|
||||
@ -20,7 +21,7 @@ export default async function CommissionRequestPage({
|
||||
Submitted: {new Date(request.createdAt).toLocaleString()} · ID: {request.id}
|
||||
</p>
|
||||
</div>
|
||||
<CommissionRequestEditor request={request as any} />
|
||||
<CommissionRequestEditor request={request} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import RequestsTable from "@/components/commissions/requests/RequestsTable";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Server-rendered commissions list page.
|
||||
export default async function CommissionPage() {
|
||||
const items = await prisma.commissionRequest.findMany({
|
||||
include: {
|
||||
@ -15,7 +16,7 @@ export default async function CommissionPage() {
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Commission Requests</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
List of all incomming requests via website.
|
||||
List of all incoming requests via website.
|
||||
</p>
|
||||
</div>
|
||||
<RequestsTable requests={items} />
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import EditTypeForm from "@/components/commissions/types/EditTypeForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Edit commission type page.
|
||||
export default async function CommissionTypesEditPage({ params }: { params: { id: string } }) {
|
||||
const { id } = await params;
|
||||
const commissionType = await prisma.commissionType.findUnique({
|
||||
@ -13,7 +14,7 @@ export default async function CommissionTypesEditPage({ params }: { params: { id
|
||||
customInputs: { include: { customInput: true }, orderBy: { sortIndex: "asc" } },
|
||||
tags: true,
|
||||
},
|
||||
})
|
||||
});
|
||||
const tags = await prisma.tag.findMany({
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
});
|
||||
@ -22,13 +23,10 @@ export default async function CommissionTypesEditPage({ params }: { params: { id
|
||||
});
|
||||
const extras = await prisma.commissionExtra.findMany({
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
})
|
||||
// const customInputs = await prisma.commissionCustomInput.findMany({
|
||||
// orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
// })
|
||||
});
|
||||
|
||||
if (!commissionType) {
|
||||
return <div>Type not found</div>
|
||||
return <div>Type not found</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { ExtraListClient } from "@/components/commissions/extras/ExtraListClient";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Admin page for managing commission extras.
|
||||
export default async function CommissionTypesExtrasPage() {
|
||||
const extras = await prisma.commissionExtra.findMany({
|
||||
orderBy: [{ createdAt: "asc" }, { name: "asc" }],
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import NewTypeForm from "@/components/commissions/types/NewTypeForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Create new commission type page.
|
||||
export default async function CommissionTypesNewPage() {
|
||||
const tags = await prisma.tag.findMany({
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
@ -10,10 +11,10 @@ export default async function CommissionTypesNewPage() {
|
||||
});
|
||||
const extras = await prisma.commissionExtra.findMany({
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
})
|
||||
});
|
||||
const customInputs = await prisma.commissionCustomInput.findMany({
|
||||
orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
|
||||
})
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
@ -27,6 +28,5 @@ export default async function CommissionTypesNewPage() {
|
||||
tags={tags}
|
||||
/>
|
||||
</div>
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { OptionsListClient } from "@/components/commissions/options/OptionsListClient";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Admin page for managing commission options.
|
||||
export default async function CommissionTypesOptionsPage() {
|
||||
const options = await prisma.commissionOption.findMany({
|
||||
orderBy: [{ createdAt: "asc" }, { name: "asc" }],
|
||||
|
||||
@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma";
|
||||
import { PlusCircleIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
// Commission types list page.
|
||||
export default async function CommissionTypesPage() {
|
||||
const types = await prisma.commissionType.findMany({
|
||||
include: {
|
||||
@ -17,11 +18,18 @@ export default async function CommissionTypesPage() {
|
||||
<div>
|
||||
<div className="flex gap-4 justify-between pb-8">
|
||||
<h1 className="text-2xl font-bold mb-4">Commission Types</h1>
|
||||
<Link href="/commissions/types/new" className="flex gap-2 items-center cursor-pointer bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded">
|
||||
<Link
|
||||
href="/commissions/types/new"
|
||||
className="flex gap-2 items-center cursor-pointer bg-primary hover:bg-primary/90 text-primary-foreground px-4 py-2 rounded"
|
||||
>
|
||||
<PlusCircleIcon className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all text-primary-foreground" /> Add new Type
|
||||
</Link>
|
||||
</div>
|
||||
{types && types.length > 0 ? <ListTypes types={types} /> : <p className="text-muted-foreground italic">No types found.</p>}
|
||||
{types && types.length > 0 ? (
|
||||
<ListTypes types={types} />
|
||||
) : (
|
||||
<p className="text-muted-foreground italic">No types found.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -3,25 +3,15 @@ import Footer from "@/components/global/Footer";
|
||||
import MobileSidebar from "@/components/global/MobileSidebar";
|
||||
import ModeToggle from "@/components/global/ModeToggle";
|
||||
import Sidebar from "@/components/global/Sidebar";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
// Main admin layout with sidebar, header actions, and footer.
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
// <div className="flex flex-col min-h-screen min-w-screen">
|
||||
// <header className="sticky top-0 z-50 h-14 w-full border-b bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60 px-4 py-2">
|
||||
// <Header />
|
||||
// </header>
|
||||
// <main className="container mx-auto px-4 py-8">
|
||||
// {children}
|
||||
// </main>
|
||||
// <footer className="mt-auto px-4 py-2 h-14 border-t bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60">
|
||||
// <Footer />
|
||||
// </footer>
|
||||
// <Toaster />
|
||||
// </div>
|
||||
<div className="min-h-screen w-full">
|
||||
<div className="flex min-h-screen w-full">
|
||||
<aside className="hidden md:flex md:w-64 md:flex-col md:border-r md:bg-background">
|
||||
|
||||
@ -6,14 +6,7 @@ import { StatusPill } from "@/components/home/StatusPill";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
function fmtDate(d: Date) {
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(d);
|
||||
}
|
||||
|
||||
// Admin dashboard summary page.
|
||||
export default async function HomePage() {
|
||||
const data = await getAdminDashboard();
|
||||
|
||||
@ -28,9 +21,6 @@ export default async function HomePage() {
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* <Button asChild variant="secondary">
|
||||
<Link href="/artworks/new">Add artwork</Link>
|
||||
</Button> */}
|
||||
<Button asChild>
|
||||
<Link href="/commissions/requests">Review requests</Link>
|
||||
</Button>
|
||||
@ -80,48 +70,6 @@ export default async function HomePage() {
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 lg:grid-cols-3">
|
||||
{/* Artwork status */}
|
||||
{/* <Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Artwork status</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<StatusPill label="Published" value={data.artworks.published} />
|
||||
<StatusPill label="Unpublished" value={data.artworks.unpublished} />
|
||||
<StatusPill label="NSFW" value={data.artworks.nsfw} />
|
||||
<StatusPill label="Set as header" value={data.artworks.header} />
|
||||
</CardContent>
|
||||
</Card> */}
|
||||
|
||||
{/* Color pipeline */}
|
||||
{/* <Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Color pipeline</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<StatusPill
|
||||
label="Pending"
|
||||
value={data.artworks.colorStatus.PENDING}
|
||||
/>
|
||||
<StatusPill
|
||||
label="Processing"
|
||||
value={data.artworks.colorStatus.PROCESSING}
|
||||
/>
|
||||
<StatusPill
|
||||
label="Ready"
|
||||
value={data.artworks.colorStatus.READY}
|
||||
/>
|
||||
<StatusPill
|
||||
label="Failed"
|
||||
value={data.artworks.colorStatus.FAILED}
|
||||
/>
|
||||
<div className="pt-2 text-sm text-muted-foreground">
|
||||
Tip: keep “Failed” near zero—those typically need a re-run or file
|
||||
fix.
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card> */}
|
||||
|
||||
{/* Commissions status */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@ -153,84 +101,6 @@ export default async function HomePage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Recent activity */}
|
||||
{/* <section className="grid gap-4 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base">Recent artworks</CardTitle>
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link href="/artworks">Open</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{data.artworks.recent.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">No artworks yet.</div>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{data.artworks.recent.map((a) => (
|
||||
<li
|
||||
key={a.id}
|
||||
className="flex items-center justify-between gap-3 rounded-md border px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{a.name}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{fmtDate(a.createdAt)} · {a.colorStatus}
|
||||
{a.published ? " · published" : " · draft"}
|
||||
{a.needsWork ? " · needs work" : ""}
|
||||
</div>
|
||||
</div>
|
||||
<Button asChild variant="secondary" size="sm">
|
||||
<Link href={`/artworks/${a.slug}`}>Open</Link>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base">Recent commission requests</CardTitle>
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link href="/commissions/requests">Open</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{data.commissions.recent.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
No commission requests yet.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{data.commissions.recent.map((r) => (
|
||||
<li
|
||||
key={r.id}
|
||||
className="flex items-center justify-between gap-3 rounded-md border px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">
|
||||
{r.customerName}{" "}
|
||||
<span className="text-muted-foreground">
|
||||
({r.customerEmail})
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{fmtDate(r.createdAt)} · {r.status}
|
||||
</div>
|
||||
</div>
|
||||
<Button asChild variant="secondary" size="sm">
|
||||
<Link href={`/commissions/requests/${r.id}`}>Open</Link>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import EditTagForm from "@/components/tags/EditTagForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Edit tag page.
|
||||
export default async function PortfolioTagsEditPage({ params }: { params: { id: string } }) {
|
||||
const { id } = await params;
|
||||
const tag = await prisma.tag.findUnique({
|
||||
@ -15,8 +16,8 @@ export default async function PortfolioTagsEditPage({ params }: { params: { id:
|
||||
},
|
||||
},
|
||||
aliases: true
|
||||
}
|
||||
})
|
||||
},
|
||||
});
|
||||
|
||||
const categories = await prisma.artCategory.findMany({
|
||||
include: { tagLinks: true },
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import NewTagForm from "@/components/tags/NewTagForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
// Create a new tag page.
|
||||
export default async function PortfolioTagsNewPage() {
|
||||
const categories = await prisma.artCategory.findMany({
|
||||
include: { tagLinks: true },
|
||||
|
||||
@ -4,6 +4,7 @@ import { prisma } from "@/lib/prisma";
|
||||
import { PlusCircleIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
// Admin tags management page.
|
||||
export default async function ArtTagsPage() {
|
||||
const items = await prisma.tag.findMany({
|
||||
include: {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { getLatestTos } from "@/actions/tos/getTos";
|
||||
import TosEditor from "@/components/tos/Editor";
|
||||
|
||||
// Admin page for editing Terms of Service.
|
||||
export default async function TosPage() {
|
||||
const markdown = await getLatestTos();
|
||||
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
import UploadBulkImageForm from "@/components/uploads/UploadBulkImageForm";
|
||||
|
||||
// Bulk image upload page.
|
||||
export default function UploadsBulkPage() {
|
||||
return (
|
||||
<div><UploadBulkImageForm /></div>
|
||||
<div>
|
||||
<UploadBulkImageForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,7 +1,10 @@
|
||||
import UploadImageForm from "@/components/uploads/UploadImageForm";
|
||||
|
||||
// Single image upload page.
|
||||
export default function UploadsSinglePage() {
|
||||
return (
|
||||
<div><UploadImageForm /></div>
|
||||
<div>
|
||||
<UploadImageForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,11 +1,13 @@
|
||||
import { CreateUserForm } from "@/components/users/CreateUserForm";
|
||||
import { auth } from "@/lib/auth";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// Admin-only user creation page.
|
||||
export default async function NewUserPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
|
||||
if (!session) redirect("/login");
|
||||
if (role !== "admin") redirect("/");
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
import { UsersTable } from "@/components/users/UsersTable";
|
||||
import { auth } from "@/lib/auth";
|
||||
import type { SessionWithRole } from "@/types/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// Admin users list page.
|
||||
export default async function UsersPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const role = (session as any)?.user?.role as string | undefined;
|
||||
const role = (session as SessionWithRole)?.user?.role;
|
||||
|
||||
if (!session) redirect("/login");
|
||||
if (role !== "admin") redirect("/");
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { ForgotPasswordForm } from "@/components/auth/ForgotPasswordForm";
|
||||
|
||||
// Forgot password page.
|
||||
export default function ForgotPasswordPage() {
|
||||
return (
|
||||
<div className="mx-auto max-w-md p-6">
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
// Layout wrapper for auth routes.
|
||||
export default function AuthLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen min-w-screen">
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import LoginForm from "@/components/auth/LoginForm";
|
||||
import { Suspense } from "react";
|
||||
|
||||
// Admin login page.
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
|
||||
@ -2,6 +2,7 @@ import { RegisterForm } from "@/components/auth/RegisterForm";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// One-time admin registration page (only when no users exist).
|
||||
export default async function RegisterPage() {
|
||||
const count = await prisma.user.count();
|
||||
if (count !== 0) redirect("/login");
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { ResetPasswordForm } from "@/components/auth/ResetPasswordForm";
|
||||
import Link from "next/link";
|
||||
|
||||
// Reset password page, expects a token query param.
|
||||
export default async function ResetPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
@ -13,7 +14,7 @@ export default async function ResetPasswordPage({
|
||||
<div className="mx-auto max-w-md p-6">
|
||||
<p>No valid token, please try again or get back to <Link href="/">Home</Link></p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { getArtworksPage } from "@/lib/queryArtworks";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
// Public API for paginated artworks listing.
|
||||
export async function GET(req: NextRequest) {
|
||||
const publishedParam = req.nextUrl.searchParams.get("published") ?? "all";
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
|
||||
// Better Auth route handlers.
|
||||
export const { POST, GET } = toNextJsHandler(auth);
|
||||
@ -1,7 +1,24 @@
|
||||
import { s3 } from "@/lib/s3";
|
||||
import type { S3Body } from "@/types/s3";
|
||||
import { GetObjectCommand } from "@aws-sdk/client-s3";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
function isWebReadableStream(value: unknown): value is ReadableStream<Uint8Array> {
|
||||
return !!value && typeof (value as ReadableStream<Uint8Array>).getReader === "function";
|
||||
}
|
||||
|
||||
function toBodyInit(body: S3Body): BodyInit {
|
||||
if (body instanceof Readable) {
|
||||
return Readable.toWeb(body) as ReadableStream<Uint8Array>;
|
||||
}
|
||||
if (isWebReadableStream(body)) {
|
||||
return body;
|
||||
}
|
||||
return body as BodyInit;
|
||||
}
|
||||
|
||||
// Streams images from S3 for the admin app.
|
||||
export async function GET(_req: NextRequest, context: { params: Promise<{ key: string[] }> }) {
|
||||
const { key } = await context.params;
|
||||
const s3Key = key.join("/");
|
||||
@ -20,7 +37,7 @@ export async function GET(_req: NextRequest, context: { params: Promise<{ key: s
|
||||
|
||||
const contentType = response.ContentType ?? "application/octet-stream";
|
||||
|
||||
return new Response(response.Body as ReadableStream, {
|
||||
return new Response(toBodyInit(response.Body as S3Body), {
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
@ -28,7 +45,7 @@ export async function GET(_req: NextRequest, context: { params: Promise<{ key: s
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
console.error(err);
|
||||
return new Response("Image not found", { status: 404 });
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,12 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { s3 } from "@/lib/s3";
|
||||
import type { S3Body } from "@/types/s3";
|
||||
import { GetObjectCommand } from "@aws-sdk/client-s3";
|
||||
import archiver from "archiver";
|
||||
import { NextRequest } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
// Streams commission request files (single or zip) from S3.
|
||||
type Mode = "display" | "download" | "bulk";
|
||||
|
||||
function contentDisposition(filename: string, mode: Mode) {
|
||||
@ -14,7 +17,38 @@ function contentDisposition(filename: string, mode: Mode) {
|
||||
}
|
||||
|
||||
function sanitizeZipEntryName(name: string) {
|
||||
return name.replace(/[^\w.\- ()\[\]]+/g, "_").slice(0, 180);
|
||||
return name.replace(/[^\w.\- ()[\]]+/g, "_").slice(0, 180);
|
||||
}
|
||||
|
||||
function isWebReadableStream(value: unknown): value is ReadableStream<Uint8Array> {
|
||||
return !!value && typeof (value as ReadableStream<Uint8Array>).getReader === "function";
|
||||
}
|
||||
|
||||
function webStreamToAsyncIterable(stream: ReadableStream<Uint8Array>) {
|
||||
const reader = stream.getReader();
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) yield value;
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function toBodyInit(body: S3Body): BodyInit {
|
||||
if (body instanceof Readable) {
|
||||
return Readable.toWeb(body) as ReadableStream<Uint8Array>;
|
||||
}
|
||||
if (isWebReadableStream(body)) {
|
||||
return body;
|
||||
}
|
||||
return body as BodyInit;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
@ -52,7 +86,7 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const contentType = file.fileType || s3Res.ContentType || "application/octet-stream";
|
||||
|
||||
return new Response(s3Res.Body as ReadableStream, {
|
||||
return new Response(toBodyInit(s3Res.Body as S3Body), {
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
// You can tune caching; admin-only content usually should be private.
|
||||
@ -117,8 +151,24 @@ export async function GET(req: NextRequest) {
|
||||
f.originalFile || f.fileKey.split("/").pop() || "file"
|
||||
);
|
||||
|
||||
// obj.Body is a Node stream in Node runtime; works with archiver
|
||||
archive.append(obj.Body as any, { name: entryName });
|
||||
// obj.Body can be a Node Readable, web ReadableStream, or Buffer.
|
||||
const body = obj.Body;
|
||||
if (!body) continue;
|
||||
|
||||
if (body instanceof Readable) {
|
||||
archive.append(body, { name: entryName });
|
||||
} else if (isWebReadableStream(body)) {
|
||||
archive.append(Readable.from(webStreamToAsyncIterable(body)), { name: entryName });
|
||||
} else if (body instanceof Blob) {
|
||||
const stream = body.stream();
|
||||
archive.append(Readable.from(webStreamToAsyncIterable(stream)), { name: entryName });
|
||||
} else if (Buffer.isBuffer(body)) {
|
||||
archive.append(body, { name: entryName });
|
||||
} else if (body instanceof Uint8Array) {
|
||||
archive.append(Buffer.from(body), { name: entryName });
|
||||
} else {
|
||||
throw new Error("Unsupported S3 body type for zip entry");
|
||||
}
|
||||
}
|
||||
|
||||
await archive.finalize();
|
||||
|
||||
@ -1,38 +1,11 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { s3 } from "@/lib/s3";
|
||||
import { publicCommissionRequestSchema } from "@/schemas/commissions/publicRequest";
|
||||
import { DeleteObjectsCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||
import { NextResponse } from "next/server";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const payloadSchema = z.object({
|
||||
typeId: z.string().min(1).optional().nullable(),
|
||||
customCardId: z.string().min(1).optional().nullable(),
|
||||
optionId: z.string().min(1).optional().nullable(),
|
||||
extraIds: z.array(z.string().min(1)).default([]),
|
||||
|
||||
customerName: z.string().min(1).max(200),
|
||||
customerEmail: z.string().email().max(320),
|
||||
customerSocials: z.string().max(2000).optional().nullable(),
|
||||
message: z.string().min(1).max(20_000),
|
||||
}).superRefine((data, ctx) => {
|
||||
const hasType = Boolean(data.typeId);
|
||||
const hasCustom = Boolean(data.customCardId);
|
||||
if (!hasType && !hasCustom) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["typeId"],
|
||||
message: "Missing commission type or custom card",
|
||||
});
|
||||
}
|
||||
if (hasType && hasCustom) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["typeId"],
|
||||
message: "Only one of typeId or customCardId is allowed",
|
||||
});
|
||||
}
|
||||
});
|
||||
// Public API endpoint for commission submissions (multipart form).
|
||||
|
||||
function safeJsonParse(input: string) {
|
||||
try {
|
||||
@ -64,7 +37,7 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: "Invalid payload JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const payload = payloadSchema.safeParse(parsedJson);
|
||||
const payload = publicCommissionRequestSchema.safeParse(parsedJson);
|
||||
if (!payload.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Validation error", issues: payload.error.issues },
|
||||
|
||||
@ -2,7 +2,8 @@
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function Error({
|
||||
// Global error UI for the app router segment.
|
||||
export default function ErrorPage({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
@ -26,6 +27,7 @@ export default function Error({
|
||||
|
||||
<div className="flex justify-center gap-4 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition"
|
||||
>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
// Root-level error boundary UI.
|
||||
export default function GlobalError({
|
||||
error,
|
||||
reset,
|
||||
@ -20,6 +21,7 @@ export default function GlobalError({
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition"
|
||||
>
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
export const dynamic = "force-dynamic";
|
||||
export const revalidate = 0;
|
||||
|
||||
import { ThemeProvider } from "@/components/global/ThemeProvider";
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import type { ReactNode } from "react";
|
||||
import "./globals.css";
|
||||
|
||||
// Root layout and metadata for the admin app.
|
||||
export const dynamic = "force-dynamic";
|
||||
export const revalidate = 0;
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
@ -24,7 +26,7 @@ export const metadata: Metadata = {
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
children: ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user