feat: implement full CRUD functionality for projects with image upload support and admin dashboard management
This commit is contained in:
156
src/features/projects/actions.ts
Normal file
156
src/features/projects/actions.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/core/db/prisma";
|
||||
import { uploadFileToMinio } from "@/core/storage/minio";
|
||||
import { verifySession } from "@/core/security/session";
|
||||
import { projectSchema } from "./project-schema";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export async function createProjectAction(prevState: any, formData: FormData) {
|
||||
// 1. Verify Authentication
|
||||
const session = await verifySession();
|
||||
if (!session) return { success: false, message: "Unauthorized" };
|
||||
|
||||
// 2. Extract and Validate Form Data
|
||||
const data = {
|
||||
title: formData.get("title") as string,
|
||||
slug: formData.get("slug") as string,
|
||||
description: formData.get("description") as string,
|
||||
category: formData.get("category") as string,
|
||||
repoUrl: formData.get("repoUrl") as string,
|
||||
liveUrl: formData.get("liveUrl") as string,
|
||||
isPublished: formData.get("isPublished") === "on",
|
||||
image: formData.get("image") as File | null,
|
||||
};
|
||||
|
||||
const validation = projectSchema.safeParse(data);
|
||||
if (!validation.success) {
|
||||
return { success: false, message: validation.error.issues[0].message };
|
||||
}
|
||||
|
||||
// 3. Process Image Upload
|
||||
let imageUrl: string | undefined = undefined;
|
||||
if (data.image && data.image.size > 0 && data.image.name) {
|
||||
try {
|
||||
imageUrl = await uploadFileToMinio(data.image);
|
||||
} catch (e) {
|
||||
console.error("Image upload failed:", e);
|
||||
return { success: false, message: "Failed to upload image. Ensure MinIO is running and bucket exists." };
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Save to Database
|
||||
try {
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
title: validation.data.title,
|
||||
slug: validation.data.slug,
|
||||
description: validation.data.description,
|
||||
category: validation.data.category,
|
||||
repoUrl: validation.data.repoUrl || null,
|
||||
liveUrl: validation.data.liveUrl || null,
|
||||
isPublished: validation.data.isPublished,
|
||||
imageUrl: imageUrl,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/admin/dashboard");
|
||||
revalidatePath("/");
|
||||
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
console.error("DB Error:", error);
|
||||
if (error?.code === "P2002") {
|
||||
return { success: false, message: "Project slug already exists" };
|
||||
}
|
||||
return { success: false, message: "Failed to create project" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateProjectAction(id: string, prevState: any, formData: FormData) {
|
||||
const session = await verifySession();
|
||||
if (!session) return { success: false, message: "Unauthorized" };
|
||||
|
||||
const data = {
|
||||
title: formData.get("title") as string,
|
||||
slug: formData.get("slug") as string,
|
||||
description: formData.get("description") as string,
|
||||
category: formData.get("category") as string,
|
||||
repoUrl: formData.get("repoUrl") as string,
|
||||
liveUrl: formData.get("liveUrl") as string,
|
||||
isPublished: formData.get("isPublished") === "on",
|
||||
image: formData.get("image") as File | null,
|
||||
};
|
||||
|
||||
const validation = projectSchema.safeParse(data);
|
||||
if (!validation.success) {
|
||||
return { success: false, message: validation.error.issues[0].message };
|
||||
}
|
||||
|
||||
let imageUrl: string | undefined = undefined;
|
||||
if (data.image && data.image.size > 0 && data.image.name) {
|
||||
try {
|
||||
imageUrl = await uploadFileToMinio(data.image);
|
||||
} catch (e) {
|
||||
return { success: false, message: "Failed to upload new image." };
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.project.update({
|
||||
where: { id },
|
||||
data: {
|
||||
title: validation.data.title,
|
||||
slug: validation.data.slug,
|
||||
description: validation.data.description,
|
||||
category: validation.data.category,
|
||||
repoUrl: validation.data.repoUrl || null,
|
||||
liveUrl: validation.data.liveUrl || null,
|
||||
isPublished: validation.data.isPublished,
|
||||
...(imageUrl && { imageUrl }), // only update image if a new one was uploaded
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath("/admin/dashboard");
|
||||
revalidatePath("/admin/dashboard/projects");
|
||||
revalidatePath("/");
|
||||
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
if (error?.code === "P2002") {
|
||||
return { success: false, message: "Project slug already exists" };
|
||||
}
|
||||
return { success: false, message: "Failed to update project" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteProjectAction(id: string) {
|
||||
const session = await verifySession();
|
||||
if (!session) return { success: false, message: "Unauthorized" };
|
||||
|
||||
try {
|
||||
await prisma.project.delete({ where: { id } });
|
||||
revalidatePath("/admin/dashboard");
|
||||
revalidatePath("/");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, message: "Failed to delete project" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function toggleProjectPublishAction(id: string, isPublished: boolean) {
|
||||
const session = await verifySession();
|
||||
if (!session) return { success: false, message: "Unauthorized" };
|
||||
|
||||
try {
|
||||
await prisma.project.update({
|
||||
where: { id },
|
||||
data: { isPublished: !isPublished },
|
||||
});
|
||||
revalidatePath("/admin/dashboard");
|
||||
revalidatePath("/");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, message: "Failed to update project status" };
|
||||
}
|
||||
}
|
||||
28
src/features/projects/delete-button.tsx
Normal file
28
src/features/projects/delete-button.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { deleteProjectAction } from "./actions";
|
||||
import { Trash2, Loader2 } from "lucide-react";
|
||||
|
||||
export function DeleteProjectButton({ id }: { id: string }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleDelete() {
|
||||
if (confirm("Are you sure you want to delete this project? This cannot be undone.")) {
|
||||
setLoading(true);
|
||||
await deleteProjectAction(id);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={loading}
|
||||
className="p-2 text-muted-foreground hover:text-error hover:bg-error/10 rounded-lg transition-colors disabled:opacity-50"
|
||||
title="Delete Project"
|
||||
>
|
||||
{loading ? <Loader2 size={18} className="animate-spin" /> : <Trash2 size={18} />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
210
src/features/projects/project-form.tsx
Normal file
210
src/features/projects/project-form.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { createProjectAction, updateProjectAction } from "./actions";
|
||||
import { useRouter } from "@/i18n/routing";
|
||||
import { Loader2, Upload, PlusCircle, ArrowLeft, Save } from "lucide-react";
|
||||
|
||||
export function ProjectForm({ initialData, projectId }: { initialData?: any; projectId?: string }) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState<string | null>(initialData?.imageUrl || null);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const url = projectId ? `/api/admin/projects/${projectId}` : "/api/admin/projects";
|
||||
const method = projectId ? "PUT" : "POST";
|
||||
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
setError(result.message || "An error occurred");
|
||||
setLoading(false);
|
||||
} else {
|
||||
setLoading(false);
|
||||
router.refresh();
|
||||
router.push("/admin/dashboard/projects");
|
||||
}
|
||||
} catch (err) {
|
||||
setError("An unexpected error occurred during submission.");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto p-6 lg:p-10 rounded-3xl bg-card border border-border overflow-hidden relative shadow-sm">
|
||||
<div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-accent to-purple-500" />
|
||||
|
||||
<div className="mb-8 flex items-center gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.back()}
|
||||
className="p-2 rounded-full hover:bg-muted text-muted-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">
|
||||
{projectId ? "Edit Project" : "Create New Project"}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{projectId ? "Update your portfolio case study" : "Add a new case study to your portfolio"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="p-4 rounded-xl bg-error/10 border border-error/20 text-error text-sm font-medium">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Project Title</label>
|
||||
<input
|
||||
name="title"
|
||||
required
|
||||
defaultValue={initialData?.title}
|
||||
placeholder="Core Banking API"
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">URL Slug</label>
|
||||
<input
|
||||
name="slug"
|
||||
required
|
||||
defaultValue={initialData?.slug}
|
||||
placeholder="core-banking-api"
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Category</label>
|
||||
<select
|
||||
name="category"
|
||||
required
|
||||
defaultValue={initialData?.category || "Enterprise Backend"}
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono cursor-pointer"
|
||||
>
|
||||
<option value="Enterprise Backend">Enterprise Backend</option>
|
||||
<option value="Frontend Development">Frontend Development</option>
|
||||
<option value="Mobile Development">Mobile Development</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Description</label>
|
||||
<textarea
|
||||
name="description"
|
||||
required
|
||||
defaultValue={initialData?.description}
|
||||
rows={4}
|
||||
placeholder="High-performance API Gateway handling 500K+ daily transactions..."
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono resize-y"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Live URL (Optional)</label>
|
||||
<input
|
||||
name="liveUrl"
|
||||
type="url"
|
||||
defaultValue={initialData?.liveUrl || ""}
|
||||
placeholder="https://example.com"
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Repository URL (Optional)</label>
|
||||
<input
|
||||
name="repoUrl"
|
||||
type="url"
|
||||
defaultValue={initialData?.repoUrl || ""}
|
||||
placeholder="https://github.com/..."
|
||||
className="w-full px-4 py-3 rounded-xl bg-muted/30 border border-border text-sm focus:outline-none focus:ring-2 focus:ring-accent/50 transition-all font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold">Cover Image</label>
|
||||
<label className="flex flex-col items-center justify-center w-full h-40 rounded-xl border-2 border-dashed border-border hover:border-accent/50 bg-muted/10 hover:bg-muted/30 cursor-pointer transition-colors relative overflow-hidden">
|
||||
{preview ? (
|
||||
<img src={preview} alt="Preview" className="w-full h-full object-cover opacity-80" />
|
||||
) : (
|
||||
<div className="flex flex-col items-center text-muted-foreground">
|
||||
<Upload size={24} className="mb-2" />
|
||||
<span className="text-sm font-medium">Click to upload image</span>
|
||||
<span className="text-xs mt-1 opacity-75">PNG, JPG, WEBP recommended</span>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
name="image"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) setPreview(URL.createObjectURL(file));
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="isPublished"
|
||||
id="isPublished"
|
||||
className="w-5 h-5 rounded border-border text-accent focus:ring-accent/50"
|
||||
defaultChecked={initialData ? initialData.isPublished : true}
|
||||
/>
|
||||
<label htmlFor="isPublished" className="text-sm font-medium cursor-pointer">
|
||||
Publish immediately (visible to visitors)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="pt-6 border-t border-border/50 flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 px-8 py-3 rounded-xl bg-foreground text-background font-semibold text-sm hover:opacity-90 transition-all disabled:opacity-50 disabled:scale-100 hover:scale-[1.02] shadow-md"
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
) : projectId ? (
|
||||
<>
|
||||
<Save size={18} />
|
||||
Update Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlusCircle size={18} />
|
||||
Save Project
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
src/features/projects/project-schema.ts
Normal file
19
src/features/projects/project-schema.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// Ensure image is optional but if provided it must be a File object
|
||||
export const projectSchema = z.object({
|
||||
title: z.string().min(3, "Title must be at least 3 characters long"),
|
||||
slug: z.string().min(3, "Slug must be at least 3 characters long").regex(/^[a-z0-9-]+$/, "Slug must only contain lowercase letters, numbers, and dashes"),
|
||||
description: z.string().min(10, "Description must be at least 10 characters long"),
|
||||
category: z.string().min(1, "Category is required"),
|
||||
repoUrl: z.union([z.string().url("Must be a valid URL"), z.literal("")]).optional(),
|
||||
liveUrl: z.union([z.string().url("Must be a valid URL"), z.literal("")]).optional(),
|
||||
isPublished: z.boolean().default(false),
|
||||
// Validation for image handles Server ActionFormData natively
|
||||
image: z
|
||||
.any()
|
||||
.refine((file) => !file || file?.size === 0 || file?.name, "Invalid file format")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type ProjectFormValues = z.infer<typeof projectSchema>;
|
||||
36
src/features/projects/toggle-button.tsx
Normal file
36
src/features/projects/toggle-button.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { toggleProjectPublishAction } from "./actions";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export function TogglePublishButton({ id, isPublished }: { id: string; isPublished: boolean }) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleToggle() {
|
||||
setLoading(true);
|
||||
await toggleProjectPublishAction(id, isPublished);
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
disabled={loading}
|
||||
className={`px-3 py-1 rounded-full text-xs font-bold font-mono border transition-all disabled:opacity-50 ${
|
||||
isPublished
|
||||
? "bg-success/10 text-success border-success/30 hover:bg-error/10 hover:text-error hover:border-error/30 group"
|
||||
: "bg-muted/50 text-muted-foreground border-border hover:bg-success/10 hover:text-success hover:border-success/30"
|
||||
}`}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 size={12} className="animate-spin" />
|
||||
) : isPublished ? (
|
||||
<span className="group-hover:hidden">Published</span>
|
||||
) : (
|
||||
<span>Draft</span>
|
||||
)}
|
||||
{isPublished && !loading && <span className="hidden group-hover:inline">Unpublish</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user