Implement portfolio admin management
This commit is contained in:
@@ -0,0 +1,591 @@
|
||||
"use server";
|
||||
|
||||
import { MediaUsageType, Prisma } from "@prisma/client";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { ZodError } from "zod";
|
||||
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
|
||||
import { deleteEntityMediaUsages, replaceEntityMediaUsages } from "@/lib/media";
|
||||
import { resolveMediaSelection } from "@/lib/media-service";
|
||||
import { getLocalizedPath } from "@/lib/locale";
|
||||
import { removeManagedMediaFile } from "@/lib/media-storage";
|
||||
import { mediaFieldInputSchema } from "@/lib/media-validation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
assetInputSchema,
|
||||
categoryInputSchema,
|
||||
projectInputSchema,
|
||||
sectionInputSchema,
|
||||
} from "@/lib/portfolio-validation";
|
||||
|
||||
function ensureAdmin() {
|
||||
if (!isAdminAuthenticated()) {
|
||||
clearAdminSessionCookie();
|
||||
redirect("/root");
|
||||
}
|
||||
}
|
||||
|
||||
function getRedirectPath(formData: FormData, fallbackPath: string) {
|
||||
return String(formData.get("redirectPath") ?? fallbackPath);
|
||||
}
|
||||
|
||||
function withMessage(pathname: string, type: "success" | "error", message: string) {
|
||||
const params = new URLSearchParams();
|
||||
params.set(type, message);
|
||||
|
||||
return `${pathname}?${params.toString()}`;
|
||||
}
|
||||
|
||||
function normalizeCheckboxValue(formData: FormData, key: string) {
|
||||
return formData.get(key) === "on";
|
||||
}
|
||||
|
||||
function parseJsonArray(rawValue: FormDataEntryValue | null, key: string) {
|
||||
if (typeof rawValue !== "string" || rawValue.trim() === "") {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue);
|
||||
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new Error(`${key} must be an array.`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
} catch {
|
||||
throw new Error(`Invalid ${key} payload.`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsonObject(rawValue: FormDataEntryValue | null, key: string) {
|
||||
if (typeof rawValue !== "string" || rawValue.trim() === "") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(rawValue);
|
||||
|
||||
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
|
||||
throw new Error(`${key} must be an object.`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
} catch {
|
||||
throw new Error(`Invalid ${key} payload.`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseZodError(error: ZodError) {
|
||||
return error.issues[0]?.message ?? "Validation failed.";
|
||||
}
|
||||
|
||||
async function revalidatePortfolioPages() {
|
||||
revalidatePath("/root");
|
||||
revalidatePath("/root/media");
|
||||
revalidatePath("/root/portfolio");
|
||||
revalidatePath("/root/portfolio/categories");
|
||||
revalidatePath("/root/portfolio/projects");
|
||||
revalidatePath("/portfolio");
|
||||
|
||||
for (const locale of routing.locales) {
|
||||
revalidatePath(getLocalizedPath(locale, "/portfolio"));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeManagedPaths(paths: string[]) {
|
||||
for (const filePath of Array.from(new Set(paths.filter(Boolean)))) {
|
||||
await removeManagedMediaFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
export async function upsertCategoryAction(formData: FormData) {
|
||||
ensureAdmin();
|
||||
|
||||
const redirectPath = getRedirectPath(formData, "/root/portfolio/categories");
|
||||
|
||||
try {
|
||||
const parsed = categoryInputSchema.parse({
|
||||
id: String(formData.get("id") ?? "").trim() || undefined,
|
||||
slug: String(formData.get("slug") ?? ""),
|
||||
nameAr: String(formData.get("nameAr") ?? ""),
|
||||
nameEn: String(formData.get("nameEn") ?? ""),
|
||||
nameDe: String(formData.get("nameDe") ?? ""),
|
||||
descriptionAr: String(formData.get("descriptionAr") ?? ""),
|
||||
descriptionEn: String(formData.get("descriptionEn") ?? ""),
|
||||
descriptionDe: String(formData.get("descriptionDe") ?? ""),
|
||||
sortOrder: String(formData.get("sortOrder") ?? "0"),
|
||||
isActive: normalizeCheckboxValue(formData, "isActive"),
|
||||
});
|
||||
|
||||
if (parsed.id) {
|
||||
await prisma.category.update({
|
||||
where: {
|
||||
id: parsed.id,
|
||||
},
|
||||
data: parsed,
|
||||
});
|
||||
} else {
|
||||
await prisma.category.create({
|
||||
data: parsed,
|
||||
});
|
||||
}
|
||||
|
||||
await revalidatePortfolioPages();
|
||||
redirect(withMessage(redirectPath, "success", "Category saved."));
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ZodError
|
||||
? parseZodError(error)
|
||||
: error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002"
|
||||
? "Category slug must be unique."
|
||||
: "Unable to save category.";
|
||||
|
||||
redirect(withMessage(redirectPath, "error", message));
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteCategoryAction(formData: FormData) {
|
||||
ensureAdmin();
|
||||
|
||||
const redirectPath = getRedirectPath(formData, "/root/portfolio/categories");
|
||||
const id = String(formData.get("id") ?? "");
|
||||
|
||||
try {
|
||||
const projectCount = await prisma.portfolioProject.count({
|
||||
where: {
|
||||
categoryId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (projectCount > 0) {
|
||||
redirect(withMessage(redirectPath, "error", "Cannot delete a category with projects."));
|
||||
}
|
||||
|
||||
await prisma.category.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
|
||||
await revalidatePortfolioPages();
|
||||
redirect(withMessage(redirectPath, "success", "Category deleted."));
|
||||
} catch {
|
||||
redirect(withMessage(redirectPath, "error", "Unable to delete category."));
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveProjectAction(formData: FormData) {
|
||||
ensureAdmin();
|
||||
|
||||
const fallbackRedirect = String(formData.get("id") ?? "").trim()
|
||||
? `/root/portfolio/projects/${String(formData.get("id") ?? "").trim()}`
|
||||
: "/root/portfolio/projects/new";
|
||||
const redirectPath = getRedirectPath(formData, fallbackRedirect);
|
||||
const uploadedPaths: string[] = [];
|
||||
const createdMediaAssetIds: string[] = [];
|
||||
|
||||
try {
|
||||
const sections = parseJsonArray(formData.get("sections"), "sections").map((section, index) =>
|
||||
sectionInputSchema.parse({
|
||||
...section,
|
||||
media: section.media ? mediaFieldInputSchema.parse(section.media) : undefined,
|
||||
sortOrder: section.sortOrder ?? index,
|
||||
}),
|
||||
);
|
||||
|
||||
const assets = parseJsonArray(formData.get("assets"), "assets").map((asset, index) =>
|
||||
assetInputSchema.parse({
|
||||
...asset,
|
||||
media: asset.media ? mediaFieldInputSchema.parse(asset.media) : undefined,
|
||||
sortOrder: asset.sortOrder ?? index,
|
||||
}),
|
||||
);
|
||||
|
||||
const coverMedia = parseJsonObject(formData.get("coverMedia"), "coverMedia");
|
||||
|
||||
const parsed = projectInputSchema.parse({
|
||||
id: String(formData.get("id") ?? "").trim() || undefined,
|
||||
categoryId: String(formData.get("categoryId") ?? ""),
|
||||
slug: String(formData.get("slug") ?? ""),
|
||||
titleAr: String(formData.get("titleAr") ?? ""),
|
||||
titleEn: String(formData.get("titleEn") ?? ""),
|
||||
titleDe: String(formData.get("titleDe") ?? ""),
|
||||
summaryAr: String(formData.get("summaryAr") ?? ""),
|
||||
summaryEn: String(formData.get("summaryEn") ?? ""),
|
||||
summaryDe: String(formData.get("summaryDe") ?? ""),
|
||||
clientName: String(formData.get("clientName") ?? ""),
|
||||
projectYear: String(formData.get("projectYear") ?? ""),
|
||||
serviceLabelAr: String(formData.get("serviceLabelAr") ?? ""),
|
||||
serviceLabelEn: String(formData.get("serviceLabelEn") ?? ""),
|
||||
serviceLabelDe: String(formData.get("serviceLabelDe") ?? ""),
|
||||
previewUrl: String(formData.get("previewUrl") ?? ""),
|
||||
currentCoverImagePath: String(formData.get("currentCoverImagePath") ?? ""),
|
||||
coverMedia: coverMedia ? mediaFieldInputSchema.parse(coverMedia) : undefined,
|
||||
sortOrder: String(formData.get("sortOrder") ?? "0"),
|
||||
isFeatured: normalizeCheckboxValue(formData, "isFeatured"),
|
||||
isPublished: normalizeCheckboxValue(formData, "isPublished"),
|
||||
sections,
|
||||
assets,
|
||||
});
|
||||
|
||||
const existingProject = parsed.id
|
||||
? await prisma.portfolioProject.findUnique({
|
||||
where: {
|
||||
id: parsed.id,
|
||||
},
|
||||
select: {
|
||||
isPublished: true,
|
||||
publishedAt: true,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const shouldPublishNow = parsed.isPublished && !existingProject?.publishedAt;
|
||||
|
||||
const coverSelection = await resolveMediaSelection({
|
||||
media: parsed.coverMedia,
|
||||
uploadFile: formData.get("coverFile"),
|
||||
folder: "covers",
|
||||
fallbackLabel: parsed.titleDe || parsed.titleEn || parsed.titleAr || parsed.slug,
|
||||
required: false,
|
||||
});
|
||||
|
||||
if (coverSelection.createdAssetId) {
|
||||
createdMediaAssetIds.push(coverSelection.createdAssetId);
|
||||
}
|
||||
|
||||
if (coverSelection.uploadedUrl) {
|
||||
uploadedPaths.push(coverSelection.uploadedUrl);
|
||||
}
|
||||
|
||||
const sectionRows: Array<{
|
||||
type: (typeof parsed.sections)[number]["type"];
|
||||
titleAr: string;
|
||||
titleEn: string;
|
||||
titleDe: string;
|
||||
bodyAr: string;
|
||||
bodyEn: string;
|
||||
bodyDe: string;
|
||||
imagePath: string | null;
|
||||
imageAssetId: string | null;
|
||||
linkUrl: string | null;
|
||||
sortOrder: number;
|
||||
}> = [];
|
||||
|
||||
for (let index = 0; index < parsed.sections.length; index += 1) {
|
||||
const section = parsed.sections[index];
|
||||
const sectionSelection = await resolveMediaSelection({
|
||||
media: section.media,
|
||||
uploadFile: formData.get(`section-image-upload-${index}`),
|
||||
folder: "sections",
|
||||
fallbackLabel: section.titleDe || section.titleEn || section.titleAr || `section-${index + 1}`,
|
||||
required: false,
|
||||
});
|
||||
|
||||
if (sectionSelection.createdAssetId) {
|
||||
createdMediaAssetIds.push(sectionSelection.createdAssetId);
|
||||
}
|
||||
|
||||
if (sectionSelection.uploadedUrl) {
|
||||
uploadedPaths.push(sectionSelection.uploadedUrl);
|
||||
}
|
||||
|
||||
sectionRows.push({
|
||||
type: section.type,
|
||||
titleAr: section.titleAr,
|
||||
titleEn: section.titleEn,
|
||||
titleDe: section.titleDe,
|
||||
bodyAr: section.bodyAr,
|
||||
bodyEn: section.bodyEn,
|
||||
bodyDe: section.bodyDe,
|
||||
imagePath: sectionSelection.url || null,
|
||||
imageAssetId: sectionSelection.assetId,
|
||||
linkUrl: section.linkUrl || null,
|
||||
sortOrder: index,
|
||||
});
|
||||
}
|
||||
|
||||
const assetRows: Array<{
|
||||
kind: (typeof parsed.assets)[number]["kind"];
|
||||
filePath: string;
|
||||
mediaAssetId: string | null;
|
||||
altAr: string;
|
||||
altEn: string;
|
||||
altDe: string;
|
||||
sortOrder: number;
|
||||
}> = [];
|
||||
|
||||
for (let index = 0; index < parsed.assets.length; index += 1) {
|
||||
const asset = parsed.assets[index];
|
||||
const assetSelection = await resolveMediaSelection({
|
||||
media: asset.media,
|
||||
uploadFile: asset.fileFieldName ? formData.get(asset.fileFieldName) : null,
|
||||
folder: "assets",
|
||||
fallbackLabel: asset.altDe || asset.altEn || asset.altAr || `asset-${index + 1}`,
|
||||
required: true,
|
||||
});
|
||||
|
||||
if (!assetSelection.url) {
|
||||
throw new Error("Each asset row needs either an existing file or a new upload.");
|
||||
}
|
||||
|
||||
if (assetSelection.createdAssetId) {
|
||||
createdMediaAssetIds.push(assetSelection.createdAssetId);
|
||||
}
|
||||
|
||||
if (assetSelection.uploadedUrl) {
|
||||
uploadedPaths.push(assetSelection.uploadedUrl);
|
||||
}
|
||||
|
||||
assetRows.push({
|
||||
kind: asset.kind,
|
||||
filePath: assetSelection.url,
|
||||
mediaAssetId: assetSelection.assetId,
|
||||
altAr: asset.altAr,
|
||||
altEn: asset.altEn,
|
||||
altDe: asset.altDe,
|
||||
sortOrder: index,
|
||||
});
|
||||
}
|
||||
|
||||
const projectResult = await prisma.$transaction(async (tx) => {
|
||||
const currentProject = parsed.id
|
||||
? await tx.portfolioProject.update({
|
||||
where: {
|
||||
id: parsed.id,
|
||||
},
|
||||
data: {
|
||||
categoryId: parsed.categoryId,
|
||||
slug: parsed.slug,
|
||||
titleAr: parsed.titleAr,
|
||||
titleEn: parsed.titleEn,
|
||||
titleDe: parsed.titleDe,
|
||||
summaryAr: parsed.summaryAr,
|
||||
summaryEn: parsed.summaryEn,
|
||||
summaryDe: parsed.summaryDe,
|
||||
clientName: parsed.clientName,
|
||||
projectYear: parsed.projectYear,
|
||||
serviceLabelAr: parsed.serviceLabelAr,
|
||||
serviceLabelEn: parsed.serviceLabelEn,
|
||||
serviceLabelDe: parsed.serviceLabelDe,
|
||||
previewUrl: parsed.previewUrl || null,
|
||||
coverImagePath: coverSelection.url || null,
|
||||
isFeatured: parsed.isFeatured,
|
||||
isPublished: parsed.isPublished,
|
||||
publishedAt: parsed.isPublished
|
||||
? shouldPublishNow
|
||||
? new Date()
|
||||
: existingProject?.publishedAt ?? new Date()
|
||||
: null,
|
||||
sortOrder: parsed.sortOrder,
|
||||
},
|
||||
})
|
||||
: await tx.portfolioProject.create({
|
||||
data: {
|
||||
categoryId: parsed.categoryId,
|
||||
slug: parsed.slug,
|
||||
titleAr: parsed.titleAr,
|
||||
titleEn: parsed.titleEn,
|
||||
titleDe: parsed.titleDe,
|
||||
summaryAr: parsed.summaryAr,
|
||||
summaryEn: parsed.summaryEn,
|
||||
summaryDe: parsed.summaryDe,
|
||||
clientName: parsed.clientName,
|
||||
projectYear: parsed.projectYear,
|
||||
serviceLabelAr: parsed.serviceLabelAr,
|
||||
serviceLabelEn: parsed.serviceLabelEn,
|
||||
serviceLabelDe: parsed.serviceLabelDe,
|
||||
previewUrl: parsed.previewUrl || null,
|
||||
coverImagePath: coverSelection.url || null,
|
||||
isFeatured: parsed.isFeatured,
|
||||
isPublished: parsed.isPublished,
|
||||
publishedAt: parsed.isPublished ? new Date() : null,
|
||||
sortOrder: parsed.sortOrder,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.portfolioSection.deleteMany({
|
||||
where: {
|
||||
projectId: currentProject.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.portfolioAsset.deleteMany({
|
||||
where: {
|
||||
projectId: currentProject.id,
|
||||
},
|
||||
});
|
||||
|
||||
const createdSections = [];
|
||||
|
||||
for (const section of sectionRows) {
|
||||
const createdSection = await tx.portfolioSection.create({
|
||||
data: {
|
||||
projectId: currentProject.id,
|
||||
type: section.type,
|
||||
titleAr: section.titleAr,
|
||||
titleEn: section.titleEn,
|
||||
titleDe: section.titleDe,
|
||||
bodyAr: section.bodyAr,
|
||||
bodyEn: section.bodyEn,
|
||||
bodyDe: section.bodyDe,
|
||||
imagePath: section.imagePath || null,
|
||||
linkUrl: section.linkUrl || null,
|
||||
sortOrder: section.sortOrder,
|
||||
},
|
||||
});
|
||||
|
||||
createdSections.push(createdSection);
|
||||
}
|
||||
|
||||
const createdAssets = [];
|
||||
|
||||
for (const asset of assetRows) {
|
||||
const createdAsset = await tx.portfolioAsset.create({
|
||||
data: {
|
||||
projectId: currentProject.id,
|
||||
kind: asset.kind,
|
||||
filePath: asset.filePath,
|
||||
altAr: asset.altAr,
|
||||
altEn: asset.altEn,
|
||||
altDe: asset.altDe,
|
||||
sortOrder: asset.sortOrder,
|
||||
},
|
||||
});
|
||||
|
||||
createdAssets.push(createdAsset);
|
||||
}
|
||||
|
||||
return {
|
||||
project: currentProject,
|
||||
createdSections,
|
||||
createdAssets,
|
||||
};
|
||||
});
|
||||
|
||||
await replaceEntityMediaUsages({
|
||||
entityType: "portfolio-project",
|
||||
entityId: projectResult.project.id,
|
||||
usages: [
|
||||
...(coverSelection.assetId
|
||||
? [
|
||||
{
|
||||
assetId: coverSelection.assetId,
|
||||
usageType: MediaUsageType.PORTFOLIO_COVER,
|
||||
fieldKey: "cover",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...projectResult.createdSections.flatMap((section, index) =>
|
||||
sectionRows[index]?.imageAssetId
|
||||
? [
|
||||
{
|
||||
assetId: sectionRows[index].imageAssetId as string,
|
||||
usageType: MediaUsageType.PORTFOLIO_SECTION,
|
||||
fieldKey: section.id,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
...projectResult.createdAssets.flatMap((asset, index) =>
|
||||
assetRows[index]?.mediaAssetId
|
||||
? [
|
||||
{
|
||||
assetId: assetRows[index].mediaAssetId as string,
|
||||
usageType: MediaUsageType.PORTFOLIO_ASSET,
|
||||
fieldKey: asset.id,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await revalidatePortfolioPages();
|
||||
revalidatePath(`/root/portfolio/projects/${projectResult.project.id}`);
|
||||
revalidatePath(`/portfolio/${projectResult.project.slug}`);
|
||||
|
||||
for (const locale of routing.locales) {
|
||||
revalidatePath(getLocalizedPath(locale, `/portfolio/${projectResult.project.slug}`));
|
||||
}
|
||||
|
||||
redirect(
|
||||
withMessage(`/root/portfolio/projects/${projectResult.project.id}`, "success", "Project saved."),
|
||||
);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof ZodError
|
||||
? parseZodError(error)
|
||||
: error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002"
|
||||
? "Project slug must be unique."
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: "Unable to save project.";
|
||||
|
||||
await removeManagedPaths(uploadedPaths);
|
||||
if (createdMediaAssetIds.length > 0) {
|
||||
await prisma.mediaUsage.deleteMany({
|
||||
where: {
|
||||
assetId: {
|
||||
in: createdMediaAssetIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
await prisma.mediaAsset.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: createdMediaAssetIds,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
redirect(withMessage(redirectPath, "error", message));
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteProjectAction(formData: FormData) {
|
||||
ensureAdmin();
|
||||
|
||||
const id = String(formData.get("id") ?? "");
|
||||
|
||||
try {
|
||||
const project = await prisma.portfolioProject.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!project) {
|
||||
redirect(withMessage("/root/portfolio/projects", "error", "Project not found."));
|
||||
}
|
||||
|
||||
const projectPaths = collectUniqueManagedPaths([
|
||||
project.coverImagePath,
|
||||
...project.sections.map((section) => section.imagePath),
|
||||
...project.assets.map((asset) => asset.filePath),
|
||||
]);
|
||||
|
||||
await prisma.portfolioProject.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
await deleteEntityMediaUsages("portfolio-project", id);
|
||||
|
||||
await revalidatePortfolioPages();
|
||||
revalidatePath(`/portfolio/${project.slug}`);
|
||||
|
||||
for (const locale of routing.locales) {
|
||||
revalidatePath(getLocalizedPath(locale, `/portfolio/${project.slug}`));
|
||||
}
|
||||
|
||||
redirect(withMessage("/root/portfolio/projects", "success", "Project deleted."));
|
||||
} catch {
|
||||
redirect(withMessage("/root/portfolio/projects", "error", "Unable to delete project."));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user