Fix UI Admin PPID

Profile PPID clear
This commit is contained in:
2025-06-10 00:54:29 +08:00
parent 41ae92774d
commit 6d312b7a28
24 changed files with 904 additions and 621 deletions

View File

@@ -62,8 +62,8 @@ model FileStorage {
link String link String
Berita Berita[] Berita Berita[]
PotensiDesa PotensiDesa[] PotensiDesa PotensiDesa[]
Posyandu Posyandu[] Posyandu Posyandu[]
ProfilePPID ProfilePPID[]
} }
//========================================= MENU PPID ========================================= // //========================================= MENU PPID ========================================= //
@@ -97,7 +97,8 @@ model ProfilePPID {
riwayat String @db.Text riwayat String @db.Text
pengalaman String @db.Text pengalaman String @db.Text
unggulan String @db.Text unggulan String @db.Text
imageUrl String? image FileStorage? @relation(fields: [imageId], references: [id])
imageId String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
deletedAt DateTime @default(now()) deletedAt DateTime @default(now())

View File

@@ -6,13 +6,9 @@ import caraMemperolehSalinanInformasi from "./data/list-caraMemperolehSalinanInf
import jenisInformasiDiminta from "./data/list-jenisInfromasi.json"; import jenisInformasiDiminta from "./data/list-jenisInfromasi.json";
import layanan from "./data/list-layanan.json"; import layanan from "./data/list-layanan.json";
import potensi from "./data/list-potensi.json"; import potensi from "./data/list-potensi.json";
import visiMisiPPID from "./data/ppid/visi-misi-ppid/visimisiPPID.json";
import dasarHukumPPID from "./data/ppid/dasar-hukum-ppid/dasarhukumPPID.json"; import dasarHukumPPID from "./data/ppid/dasar-hukum-ppid/dasarhukumPPID.json";
import profilePPID from "./data/ppid/profile-ppid/profilePPid.json"; import profilePPID from "./data/ppid/profile-ppid/profilePPid.json";
import path from "path"; import visiMisiPPID from "./data/ppid/visi-misi-ppid/visimisiPPID.json";
import fs from "fs";
import { mkdir, writeFile } from "fs/promises";
import { v4 as uuid } from "uuid";
(async () => { (async () => {
for (const l of layanan) { for (const l of layanan) {
@@ -124,30 +120,7 @@ import { v4 as uuid } from "uuid";
} }
console.log("cara memperoleh salinan informasi success ..."); console.log("cara memperoleh salinan informasi success ...");
const seedProfilePPID = async () => {
const targetDir = path.resolve("public", "uploads", "seeded-images", "profile-ppid")
// Buat folder hanya jika belum ada
if (!fs.existsSync(targetDir)) {
await mkdir(targetDir, { recursive: true })
}
for (const c of profilePPID) { for (const c of profilePPID) {
let finalImageUrl = c.imageUrl
if (c.imageUrl.startsWith("/uploads/seeded-images/")) {
const filename = path.basename(c.imageUrl)
const seedImagePath = path.resolve("prisma", "seed-images", filename)
const targetFilename = `${uuid()}_${filename}`
const targetPath = path.join(targetDir, targetFilename)
const buffer = fs.readFileSync(seedImagePath)
await writeFile(targetPath, buffer)
finalImageUrl = `/uploads/seeded-images/profile-ppid/${targetFilename}`
}
await prisma.profilePPID.upsert({ await prisma.profilePPID.upsert({
where: { id: c.id }, where: { id: c.id },
update: { update: {
@@ -156,7 +129,7 @@ import { v4 as uuid } from "uuid";
riwayat: c.riwayat, riwayat: c.riwayat,
pengalaman: c.pengalaman, pengalaman: c.pengalaman,
unggulan: c.unggulan, unggulan: c.unggulan,
imageUrl: finalImageUrl, // imageId tidak di-update
}, },
create: { create: {
id: c.id, id: c.id,
@@ -165,15 +138,11 @@ import { v4 as uuid } from "uuid";
riwayat: c.riwayat, riwayat: c.riwayat,
pengalaman: c.pengalaman, pengalaman: c.pengalaman,
unggulan: c.unggulan, unggulan: c.unggulan,
imageUrl: finalImageUrl, // imageId tidak di-create
}, },
}) });
} }
console.log("✅ profilePPID seeded without imageId (editable later via UI)");
console.log("✅ profilePPID seeded from JSON with image copying")
}
await seedProfilePPID()
for (const v of visiMisiPPID) { for (const v of visiMisiPPID) {
await prisma.visiMisiPPID.upsert({ await prisma.visiMisiPPID.upsert({

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

View File

@@ -1,4 +1,3 @@
import ApiFetch from "@/lib/api-fetch";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
import { proxy } from "valtio"; import { proxy } from "valtio";
@@ -13,11 +12,18 @@ const templateForm = z.object({
riwayat: z.string().min(3, "Riwayat minimal 3 karakter"), riwayat: z.string().min(3, "Riwayat minimal 3 karakter"),
pengalaman: z.string().min(3, "Pengalaman minimal 3 karakter"), pengalaman: z.string().min(3, "Pengalaman minimal 3 karakter"),
unggulan: z.string().min(3, "Unggulan minimal 3 karakter"), unggulan: z.string().min(3, "Unggulan minimal 3 karakter"),
imageId: z.string().min(1, "Gambar wajib dipilih"),
}); });
/** const defaultForm = {
* Tipe data ProfilePPID yang digunakan dalam form dan API, berdasarkan Prisma schema. name: "",
*/ biodata: "",
riwayat: "",
pengalaman: "",
unggulan: "",
imageId: "",
};
type ProfilePPIDForm = Prisma.ProfilePPIDGetPayload<{ type ProfilePPIDForm = Prisma.ProfilePPIDGetPayload<{
select: { select: {
id: true; id: true;
@@ -26,147 +32,170 @@ type ProfilePPIDForm = Prisma.ProfilePPIDGetPayload<{
riwayat: true; riwayat: true;
pengalaman: true; pengalaman: true;
unggulan: true; unggulan: true;
imageUrl: true; imageId: true;
image?: {
select: {
link: true;
};
};
}; };
}>; }>;
/** /**
* State utama ProfilePPID yang mencakup fitur: * Improved State Management - Consolidated and more robust
* - Ambil data berdasarkan ID
* - Update data
* - Upload gambar
*/ */
const stateProfilePPID = proxy({ const stateProfilePPID = proxy({
/** // Consolidated data management
* Bagian untuk ambil data berdasarkan ID profile: {
*/
findById: {
data: null as ProfilePPIDForm | null, data: null as ProfilePPIDForm | null,
loading: false, loading: false,
error: null as string | null,
/** // Single method to load profile data
* Inisialisasi data kosong ke dalam state.
*/
initialize() {
stateProfilePPID.findById.data = {
id: '',
name: '',
biodata: '',
riwayat: '',
pengalaman: '',
unggulan: '',
imageUrl: ''
} as ProfilePPIDForm;
},
/**
* Mengambil data profil berdasarkan ID.
* @param {string} id - ID dari profile yang ingin diambil.
*/
async load(id: string) { async load(id: string) {
try { if (!id) {
stateProfilePPID.findById.loading = true; toast.warn("ID tidak valid");
const res = await ApiFetch.api.ppid.profileppid["find-by-id"].get({ return null;
query: { id }, }
});
if (res.status === 200) { this.loading = true;
stateProfilePPID.findById.data = res.data?.data ?? null; this.error = null;
try {
const response = await fetch(`/api/ppid/profileppid/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
this.data = result.data;
return result.data;
} else { } else {
toast.error("Gagal mengambil data profile"); throw new Error(result.message || "Gagal mengambil data profile");
} }
} catch (error) { } catch (error) {
console.error((error as Error).message); const errorMessage = (error as Error).message;
this.error = errorMessage;
console.error("Load profile error:", errorMessage);
toast.error("Terjadi kesalahan saat mengambil data profile"); toast.error("Terjadi kesalahan saat mengambil data profile");
return null;
} finally { } finally {
stateProfilePPID.findById.loading = false; this.loading = false;
} }
}, },
// Reset profile data
reset() {
this.data = null;
this.error = null;
this.loading = false;
}
}, },
/** // Edit form management
* Bagian untuk update data profile editForm: {
*/ id: "",
update: { form: { ...defaultForm },
loading: false, loading: false,
error: null as string | null,
isReadOnly: false, // Flag untuk data yang tidak bisa diedit
/** // Initialize form with profile data
* Melakukan validasi dan menyimpan perubahan data profile ke server. initialize(profileData: ProfilePPIDForm) {
* @param {ProfilePPIDForm} data - Data profil yang akan disimpan. this.id = profileData.id;
*/ this.isReadOnly = false; // Semua data bisa diedit
async save(data: ProfilePPIDForm) { this.form = {
const cek = templateForm.safeParse(data); name: profileData.name || "",
biodata: profileData.biodata || "",
riwayat: profileData.riwayat || "",
pengalaman: profileData.pengalaman || "",
unggulan: profileData.unggulan || "",
imageId: profileData.imageId || "",
};
},
if (!cek.success) { // Update form field
const errors = cek.error.issues updateField(field: keyof typeof defaultForm, value: string) {
this.form[field] = value;
},
// Submit form
async submit() {
// Validate form
const validation = templateForm.safeParse(this.form);
if (!validation.success) {
const errors = validation.error.issues
.map((issue) => `${issue.path.join(".")}: ${issue.message}`) .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
.join(", "); .join(", ");
toast.error(`Form tidak valid: ${errors}`); toast.error(`Form tidak valid: ${errors}`);
return; return false;
} }
try { this.loading = true;
stateProfilePPID.update.loading = true; this.error = null;
const res = await ApiFetch.api.ppid.profileppid["update"].post(data);
if (res.status === 200) { try {
const response = await fetch(`/api/ppid/profileppid/${this.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(this.form),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
toast.success("Berhasil update profile"); toast.success("Berhasil update profile");
await stateProfilePPID.findById.load(data.id); // Refresh profile data
await stateProfilePPID.profile.load(this.id);
return true;
} else { } else {
toast.error("Gagal update profile"); throw new Error(result.message || "Gagal update profile");
} }
} catch (error) { } catch (error) {
console.error((error as Error).message); const errorMessage = (error as Error).message;
this.error = errorMessage;
console.error("Update profile error:", errorMessage);
toast.error("Terjadi kesalahan saat update profile"); toast.error("Terjadi kesalahan saat update profile");
return false;
} finally { } finally {
stateProfilePPID.update.loading = false; this.loading = false;
} }
}, },
},
/** // Reset form
* Bagian untuk upload gambar profil reset() {
*/ this.id = "";
uploadImage: { this.form = { ...defaultForm };
loading: false, this.error = null;
this.loading = false;
/** this.isReadOnly = false;
* Mengunggah gambar profil berdasarkan ID.
* @param {File} file - File gambar yang akan diunggah.
* @param {string} id - ID dari profil yang akan diperbarui gambarnya.
*/
async save(file: File, id: string) {
if (!file || !id) {
toast.error("File atau ID harus disertakan");
return;
}
try {
stateProfilePPID.uploadImage.loading = true;
const form = new FormData();
form.append("file", file);
form.append("id", id);
const res = await ApiFetch.api.ppid.profileppid["edit-img"].post(form);
if (res.status === 200) {
toast.success("Berhasil mengunggah gambar");
await stateProfilePPID.findById.load(id);
} else {
toast.error("Gagal mengunggah gambar");
}
} catch (error) {
console.error((error as Error).message);
toast.error("Terjadi kesalahan saat mengunggah gambar");
} finally {
stateProfilePPID.uploadImage.loading = false;
} }
}, },
// Helper methods
async loadForEdit(id: string) {
const profileData = await this.profile.load(id);
if (profileData) {
this.editForm.initialize(profileData);
}
return profileData;
}, },
reset() {
this.profile.reset();
this.editForm.reset();
}
}); });
/**
* Ekspor state utama ProfilePPID untuk digunakan di komponen lain.
*/
export default stateProfilePPID; export default stateProfilePPID;

View File

@@ -40,7 +40,7 @@ export function PPIDTextEditor({ onSubmit, onChange, showSubmit = true, initialC
}, [initialContent, editor]); }, [initialContent, editor]);
return ( return (
<Stack> <Stack >
<RichTextEditor editor={editor}> <RichTextEditor editor={editor}>
<RichTextEditor.Toolbar sticky stickyOffset={60}> <RichTextEditor.Toolbar sticky stickyOffset={60}>
<RichTextEditor.ControlsGroup> <RichTextEditor.ControlsGroup>

View File

@@ -0,0 +1,28 @@
'use client'
import { Box, Text } from '@mantine/core';
import EditPPIDEditor from '../../_com/editPPIDEditor';
function Biodata({
value,
onChange,
error,
}: {
value: string;
onChange: (val: string) => void;
error?: string;
}) {
return (<Box>
<Text fw={"bold"}>Biodata</Text>
<EditPPIDEditor
value={value}
onChange={onChange}
/>
{error && <Text c="red" size="sm">{error}</Text>}
</Box>
);
}
export default Biodata;

View File

@@ -0,0 +1,256 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'
import colors from '@/con/colors';
import { Box, Button, Center, FileInput, Group, Image, Paper, Stack, Text, TextInput, Title, Alert } from '@mantine/core';
import { useEffect, useState } from 'react';
import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../../_state/ppid/profile_ppid/profile_PPID';
import ApiFetch from '@/lib/api-fetch';
import { IconArrowBack, IconImageInPicture, IconAlertCircle } from '@tabler/icons-react';
import { useParams, useRouter } from 'next/navigation';
import { toast } from 'react-toastify';
import Biodata from './biodata/biodataForm';
import PengalamanOrganisasi from './pengalaman_organisasi/pengalamanForm';
import ProgramKerjaUnggulan from './program_kerja_unggulan/programKerjaForm';
import RiwayatKarir from './riwayat_karir/riwayatKarirForm';
function EditProfilePPID() {
const allState = useProxy(stateProfilePPID);
const params = useParams();
const router = useRouter();
// UI States
const [previewImage, setPreviewImage] = useState<string | null>(null);
const [file, setFile] = useState<File | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
// Load data on mount
useEffect(() => {
const loadData = async () => {
const id = params?.id as string;
if (!id) {
toast.error("ID tidak valid");
router.push("/admin/ppid/profile-ppid");
return;
}
try {
const profileData = await stateProfilePPID.loadForEdit(id);
if (profileData && profileData.image?.link) {
setPreviewImage(profileData.image.link);
}
} catch (error) {
console.error("Error loading profile:", error);
toast.error("Gagal memuat data profile");
}
};
loadData();
return () => {
stateProfilePPID.editForm.reset(); // cleanup form
};
}, [params?.id, router]);
const handleFieldChange = (field: string, value: string) => {
stateProfilePPID.editForm.updateField(field as any, value);
};
const handleFileChange = (newFile: File | null) => {
if (!newFile) {
setFile(null);
return;
}
setFile(newFile);
const reader = new FileReader();
reader.onload = (event) => {
setPreviewImage(event.target?.result as string);
};
reader.readAsDataURL(newFile);
};
const handleSubmit = async () => {
if (isSubmitting || !stateProfilePPID.editForm.form.name.trim()) {
toast.error("Nama wajib diisi");
return;
}
setIsSubmitting(true);
try {
// Upload file jika ada
if (file) {
const uploadResponse = await ApiFetch.api.fileStorage.create.post({ file, name: file.name });
const uploaded = uploadResponse.data?.data;
if (!uploaded?.id) {
toast.error("Gagal upload gambar");
return;
}
stateProfilePPID.editForm.form.imageId = uploaded.id;
}
// Submit form
const success = await stateProfilePPID.editForm.submit();
if (success) {
toast.success("Berhasil menyimpan perubahan");
router.push("/admin/ppid/profile-ppid");
}
} catch (error) {
console.error("Error submitting form:", error);
toast.error("Gagal menyimpan profile");
} finally {
setIsSubmitting(false);
}
};
const handleBack = () => {
router.back();
};
// Loading state
if (allState.profile.loading) {
return (
<Box>
<Center h={400}>
<Text>Memuat data profile...</Text>
</Center>
</Box>
);
}
// Error state
if (allState.profile.error) {
return (
<Box>
<Stack gap="md">
<Button variant="subtle" onClick={handleBack}>
<IconArrowBack color={colors['blue-button']} size={20} />
</Button>
<Alert icon={<IconAlertCircle size={16} />} color="red">
<Text fw="bold">Error</Text>
<Text>{allState.profile.error}</Text>
</Alert>
</Stack>
</Box>
);
}
// No data state
if (!allState.profile.data) {
return (
<Box>
<Stack gap="md">
<Button variant="subtle" onClick={handleBack}>
<IconArrowBack color={colors['blue-button']} size={20} />
</Button>
<Alert icon={<IconAlertCircle size={16} />} color="yellow">
<Text fw="bold">Data tidak ditemukan</Text>
<Text>Profile PPID tidak dapat ditemukan</Text>
</Alert>
</Stack>
</Box>
);
}
return (
<Box>
<Stack gap="xs">
<Box>
<Button variant="subtle" onClick={handleBack}>
<IconArrowBack color={colors['blue-button']} size={20} />
</Button>
</Box>
<Box>
<Paper w={{ base: "100%", md: "50%" }} bg={colors['white-1']} p="md" radius={10}>
<Stack gap="xs">
<Title order={3}>Edit Profile PPID</Title>
{/* Nama Field */}
<TextInput
label={<Text fw="bold">Nama Perbekel</Text>}
placeholder="Masukkan nama perbekel"
value={allState.editForm.form.name}
onChange={(e) => handleFieldChange('name', e.currentTarget.value)}
error={!allState.editForm.form.name && "Nama wajib diisi"}
/>
{/* File Upload */}
<FileInput
label={<Text fz="sm" fw="bold">Upload Gambar Baru (Opsional)</Text>}
value={file}
onChange={handleFileChange}
accept="image/*"
/>
{/* Preview Gambar */}
<Box>
<Text fz="sm" fw="bold" mb="xs">Preview Gambar</Text>
{previewImage ? (
<Image alt="Profile preview" src={previewImage} w={200} h={200} fit="cover" radius="md" />
) : (
<Center w={200} h={200} bg="gray.2">
<Stack align="center" gap="xs">
<IconImageInPicture size={48} color="gray" />
<Text size="sm" c="gray">Tidak ada gambar</Text>
</Stack>
</Center>
)}
</Box>
{/* Rich Components */}
<Biodata
value={allState.editForm.form.biodata}
onChange={(val) => handleFieldChange('biodata', val)}
/>
<RiwayatKarir
value={allState.editForm.form.riwayat}
onChange={(val) => handleFieldChange('riwayat', val)}
/>
<PengalamanOrganisasi
value={allState.editForm.form.pengalaman}
onChange={(val) => handleFieldChange('pengalaman', val)}
/>
<ProgramKerjaUnggulan
value={allState.editForm.form.unggulan}
onChange={(val) => handleFieldChange('unggulan', val)}
/>
{/* Submit Button */}
<Group>
<Button
bg={colors['blue-button']}
onClick={handleSubmit}
loading={isSubmitting || allState.editForm.loading}
disabled={!allState.editForm.form.name}
>
{isSubmitting ? 'Menyimpan...' : 'Simpan Perubahan'}
</Button>
<Button
variant="outline"
onClick={handleBack}
disabled={isSubmitting || allState.editForm.loading}
>
Batal
</Button>
</Group>
</Stack>
</Paper>
</Box>
</Stack>
</Box>
);
}
export default EditProfilePPID;

View File

@@ -0,0 +1,26 @@
'use client'
import { Box, Text } from '@mantine/core';
import EditPPIDEditor from '../../_com/editPPIDEditor';
function PengalamanOrganisasi({
value,
onChange,
error,
}: {
value: string;
onChange: (val: string) => void;
error?: string;
}) {
return (<Box>
<Text fw={"bold"}>Pengalaman Organisasi</Text>
<EditPPIDEditor
value={value}
onChange={onChange}
/>
{error && <Text c="red" size="sm">{error}</Text>}
</Box>
);
}
export default PengalamanOrganisasi;

View File

@@ -0,0 +1,26 @@
'use client'
import { Box, Text } from '@mantine/core';
import EditPPIDEditor from '../../_com/editPPIDEditor';
function ProgramKerjaUnggulan({
value,
onChange,
error,
}: {
value: string;
onChange: (val: string) => void;
error?: string;
}) {
return (<Box>
<Text fw={"bold"}>Program Kerja Unggulan</Text>
<EditPPIDEditor
value={value}
onChange={onChange}
/>
{error && <Text c="red" size="sm">{error}</Text>}
</Box>
);
}
export default ProgramKerjaUnggulan;

View File

@@ -0,0 +1,29 @@
'use client';
import { Box, Text } from '@mantine/core';
import EditPPIDEditor from '../../_com/editPPIDEditor';
function RiwayatKarir({
value,
onChange,
error,
}: {
value: string;
onChange: (val: string) => void;
error?: string;
}) {
return (
<Box>
<Text fw={"bold"}>Riwayat Karir</Text>
<EditPPIDEditor
value={value}
onChange={onChange}
/>
{error && <Text c="red" size="sm">{error}</Text>}
</Box>
);
}
export default RiwayatKarir;

View File

@@ -1,10 +0,0 @@
const biodata = {
id: "1",
name: "<p>I.B Surya Prabhawa Manuaba, S.H., M.H.</p>",
biodata: "<h2>Biodata</h2> <p>....</p>",
riwayat: "<h2>Riwayat Karir</h2> <ul>...</ul>",
pengalaman: "<h2>Pengalaman Organisasi</h2> <ul>...</ul>",
unggulan: "<h2>Program Kerja Unggulan</h2> <h3>...</h3>",
}
export default biodata

View File

@@ -0,0 +1,101 @@
'use client'
import { RichTextEditor, Link } from '@mantine/tiptap';
import { useEditor } from '@tiptap/react';
import Highlight from '@tiptap/extension-highlight';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import TextAlign from '@tiptap/extension-text-align';
import Superscript from '@tiptap/extension-superscript';
import SubScript from '@tiptap/extension-subscript';
import { useEffect } from 'react';
type EditEditorProps = {
value: string;
onChange: (content: string) => void;
};
export default function EditPPIDEditor({ value, onChange }: EditEditorProps) {
const editor = useEditor({
extensions: [
StarterKit,
Underline,
Link,
Superscript,
SubScript,
Highlight,
TextAlign.configure({ types: ['heading', 'paragraph'] }),
],
onUpdate({ editor }) {
onChange(editor.getHTML());
},
});
useEffect(() => {
if (editor && value && value !== editor.getHTML()) {
editor.commands.setContent(value);
}
}, [editor, value]);
useEffect(() => {
if (!editor) return;
const updateHandler = () => onChange(editor.getHTML());
editor.on('update', updateHandler);
return () => {
editor.off('update', updateHandler);
};
}, [editor, onChange]);
return (
<RichTextEditor editor={editor}>
<RichTextEditor.Toolbar sticky stickyOffset="var(--docs-header-height)">
{/* Toolbar seperti sebelumnya */}
<RichTextEditor.ControlsGroup>
<RichTextEditor.Bold />
<RichTextEditor.Italic />
<RichTextEditor.Underline />
<RichTextEditor.Strikethrough />
<RichTextEditor.ClearFormatting />
<RichTextEditor.Highlight />
<RichTextEditor.Code />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.H1 />
<RichTextEditor.H2 />
<RichTextEditor.H3 />
<RichTextEditor.H4 />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Blockquote />
<RichTextEditor.Hr />
<RichTextEditor.BulletList />
<RichTextEditor.OrderedList />
<RichTextEditor.Subscript />
<RichTextEditor.Superscript />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Link />
<RichTextEditor.Unlink />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.AlignLeft />
<RichTextEditor.AlignCenter />
<RichTextEditor.AlignJustify />
<RichTextEditor.AlignRight />
</RichTextEditor.ControlsGroup>
<RichTextEditor.ControlsGroup>
<RichTextEditor.Undo />
<RichTextEditor.Redo />
</RichTextEditor.ControlsGroup>
</RichTextEditor.Toolbar>
<RichTextEditor.Content />
</RichTextEditor>
);
}

View File

@@ -1,76 +0,0 @@
'use client'
import { Box, Group, Text } from '@mantine/core';
import { useState } from 'react';
import ApiFetch from '@/lib/api-fetch';
import { Dropzone, MIME_TYPES } from '@mantine/dropzone';
import { IconPhoto, IconUpload, IconX } from '@tabler/icons-react';
import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../../_state/ppid/profile_ppid/profile_PPID';
import { PPIDTextEditor } from '../../_com/PPIDTextEditor';
function Biodata() {
const biodataState = useProxy(stateProfilePPID)
const [loading, setLoading] = useState(false);
return (<Box>
<Text fw={"bold"}>Biodata</Text>
<Dropzone
mb={20}
onDrop={async (droppedFiles) => {
setLoading(true);
for (const file of droppedFiles) {
await ApiFetch.api.ppid.profileppid["edit-img"].post({
file: file,
id: biodataState.findById.data?.id,
});
}
setLoading(false);
if (biodataState.findById.data?.id) {
biodataState.findById.load(biodataState.findById.data.id);
}
}}
accept={[MIME_TYPES.jpeg, MIME_TYPES.png, MIME_TYPES.webp]}
loading={loading}
>
<Group justify="center" gap="md" mih={150} style={{ pointerEvents: 'none' }}>
<Dropzone.Accept>
<IconUpload size={50} stroke={1.5} />
</Dropzone.Accept>
<Dropzone.Reject>
<IconX size={50} stroke={1.5} />
</Dropzone.Reject>
<Dropzone.Idle>
<IconPhoto size={50} stroke={1.5} />
</Dropzone.Idle>
<div>
<Text size="xl" inline>
Drag & drop gambar di sini atau klik untuk pilih file
</Text>
<Text size="sm" c="dimmed" inline mt={7}>
Maksimal ukuran file 5MB. Format: JPG, PNG, WebP
</Text>
</div>
</Group>
</Dropzone>
<PPIDTextEditor
key={biodataState.findById.data?.id ?? 'new'}
showSubmit={false}
onChange={(val) => {
if (biodataState.findById.data) {
biodataState.findById.data.biodata = val;
}
}}
initialContent={biodataState.findById.data?.biodata ?? ''}
/>
</Box>
);
}
export default Biodata;

View File

@@ -1,65 +0,0 @@
import colors from '@/con/colors';
import { Stack, Skeleton, Paper, Title, Box, Text, Image } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import React from 'react';
import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../_state/ppid/profile_ppid/profile_PPID';
function ProfileList() {
const allList = useProxy(stateProfilePPID)
useShallowEffect(() => {
allList.findById.load("1") // Assuming "1" is your default ID, adjust as needed
}, [])
if (!allList.findById.data) return <Stack>
{Array.from({ length: 10 }).map((v, k) => <Skeleton key={k} h={40} />)}
</Stack>
const dataArray = Array.isArray(allList.findById.data)
? allList.findById.data
: [allList.findById.data];
return (
<Paper bg={colors['white-1']} p={'md'}>
<Stack gap={"xs"}>
<Title order={3}>List Profile PPID</Title>
{dataArray.map((item) => (
<Box key={item.id}>
{item.imageUrl && (
<Box mb={20}>
<Text fw={"bold"} mb={5}>Preview Gambar:</Text>
<Image
src={item.imageUrl ?? '/perbekel.png'}
alt="Profile"
w={200}
/>
</Box>
)}
<Box>
<Text fw={"bold"}>Nama</Text>
<Text dangerouslySetInnerHTML={{ __html: item.name }}></Text>
</Box>
<Box>
<Text fw={"bold"}>Biodata</Text>
<Text dangerouslySetInnerHTML={{ __html: item.biodata }}></Text>
</Box>
<Box>
<Text fw={"bold"}>Riwayat</Text>
<Text dangerouslySetInnerHTML={{ __html: item.riwayat }}></Text>
</Box>
<Box>
<Text fw={"bold"}>Pengalaman</Text>
<Text dangerouslySetInnerHTML={{ __html: item.pengalaman }}></Text>
</Box>
<Box>
<Text fw={"bold"}>Program Kerja Unggulan</Text>
<Text dangerouslySetInnerHTML={{ __html: item.unggulan }}></Text>
</Box>
</Box>
))}
</Stack>
</Paper>
)
}
export default ProfileList;

View File

@@ -1,89 +1,118 @@
'use client' 'use client'
import colors from '@/con/colors'; import colors from '@/con/colors';
import { Box, Button, Group, Paper, SimpleGrid, Stack, Text, TextInput, Title } from '@mantine/core'; import { Box, Button, Center, Divider, Flex, Grid, GridCol, Image, List, Paper, Skeleton, Stack, Text, Title } from '@mantine/core';
import Biodata from './biodata/page'; import { useShallowEffect } from '@mantine/hooks';
import PengalamanOrganisasi from './pengalaman_organisasi/page'; import { IconEdit } from '@tabler/icons-react';
import RiwayatKarir from './riwayat_karir/page'; import { useRouter } from 'next/navigation';
import ProgramKerjaUnggulan from './program_kerja_unggulan/page';
import { useProxy } from 'valtio/utils'; import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../_state/ppid/profile_ppid/profile_PPID'; import stateProfilePPID from '../../_state/ppid/profile_ppid/profile_PPID';
import { useShallowEffect } from '@mantine/hooks';
import ProfileList from './listPage';
import { useState } from 'react';
import { toast } from 'react-toastify';
function Page() { function Page() {
return ( const router = useRouter()
<Box> const allList = useProxy(stateProfilePPID)
<SimpleGrid cols={{ base: 1, md: 2 }}>
<ProfileCreate />
<ProfileList />
</SimpleGrid>
</Box>
);
}
function ProfileCreate() {
const [isLoading, setIsLoading] = useState(false)
const allState = useProxy(stateProfilePPID)
// Initialize data if it doesn't exist
useShallowEffect(() => { useShallowEffect(() => {
if (!allState.findById.data && isLoading) { allList.profile.load("1") // Assuming "1" is your default ID, adjust as needed
allState.findById.initialize() }, [])
setIsLoading(false)
}
}, [isLoading])
const submit = () => { if (!allList.profile.data) {
if ( return <Stack>
allState.findById.data?.name && <Skeleton radius={10} h={800} />
allState.findById.data?.biodata && </Stack>
allState.findById.data?.riwayat &&
allState.findById.data?.pengalaman &&
allState.findById.data?.unggulan
) {
allState.update.save(allState.findById.data)
setIsLoading(true)
toast.success("success")
console.log("[SUBMIT SUCCESS]", JSON.stringify(allState.findById.data, null, 2))
allState.findById.initialize()
} else {
toast.error("error")
}
} }
const dataArray = Array.isArray(allList.profile.data)
? allList.profile.data
: [allList.profile.data];
return ( return (
<Paper bg={colors['white-1']} p={'md'} radius={10}> <Paper bg={colors['white-1']} p={'md'}>
<Stack gap={"xs"}> <Stack gap={"xs"}>
<Title order={3}>Profile PPID</Title> <Grid>
<TextInput <GridCol span={{ base: 12, md: 11 }}>
label={<Text fw={"bold"}>Nama Perbekel</Text>} <Title order={3}>List Profile PPID</Title>
placeholder="masukkan nama perbekel" </GridCol>
value={allState.findById.data?.name || ''} <GridCol span={{ base: 12, md: 1 }}>
onChange={(val) => { <Button bg={colors['blue-button']} onClick={() => router.push(`/admin/ppid/profile-ppid/${allList.profile.data?.id}`)}>
if (allState.findById.data) { <IconEdit size={16} />
allState.findById.data.name = val.currentTarget.value </Button>
} </GridCol>
</Grid>
{dataArray.map((item) => (
<Box key={item.id} px={{ base: "md", md: 100 }}>
<Paper p={"xl"} bg={colors['BG-trans']}>
<Box px={{ base: "md", md: 100 }}>
<Flex align={"center"} gap={50}>
<Image src={"/api/img/darmasaba-icon.png"} h={{ base: 80, md: 150 }} alt='' />
<Text fz={{ base: "1.4rem", md: "1.6rem", lg: "2rem", xl: "2.5rem" }} fw={'bold'}>PROFIL PIMPINAN BADAN PUBLIK DESA DARMASABA </Text>
</Flex>
</Box>
<Divider my={"md"} />
{/* biodata perbekel */}
<Box px={{ base: 0, md: 50 }} pb={30}>
<Box px={{ base: 0, md: 50 }}>
<Paper bg={colors['BG-trans']} w={{ base: "100%", md: "100%" }}>
<Stack gap={0}>
<Center>
<Image
pt={{ base: 0, md: 90 }}
src={item.image?.link}
w={{ base: 250, md: 350 }}
alt='Foto Profil PPID'
onError={(e) => {
e.currentTarget.src = "/perbekel.png";
}} }}
/> />
<Biodata /> </Center>
<RiwayatKarir /> <Paper
<PengalamanOrganisasi />
<ProgramKerjaUnggulan />
<Group>
<Button
bg={colors['blue-button']} bg={colors['blue-button']}
onClick={submit} py={30}
loading={allState.update.loading} className="glass3"
px={{ base: 20, md: 20 }}
> >
Submit <Text ta={"center"} c={colors['white-1']} fw={"bolder"} fz={{ base: "1.5rem", md: "1.5rem" }}>
</Button> {item.name}
</Group> </Text>
</Paper>
</Stack>
</Paper>
</Box>
<Box pt={10}>
<Box>
<Text fz={{ base: "1.125rem", md: "1.375rem", lg: "1.75rem", xl: "2rem" }} fw={'bold'}>Biodata</Text>
<Text fz={{ base: "1rem", md: "1.125rem", lg: "1.25rem", xl: "1.5rem" }} ta={"justify"} dangerouslySetInnerHTML={{ __html: item.biodata }} />
</Box>
<Box>
<Text fz={{ base: "1.125rem", md: "1.375rem", lg: "1.75rem", xl: "2rem" }} fw={'bold'}>Riwayat Karir</Text>
<Text fz={{ base: "1rem", md: "1.125rem", lg: "1.25rem", xl: "1.5rem" }} dangerouslySetInnerHTML={{ __html: item.riwayat }} />
</Box>
</Box>
</Box>
<Box pb={30}>
<Text fz={{ base: "1.125rem", md: "1.375rem", lg: "1.75rem", xl: "2rem" }} fw={'bold'}>Pengalaman Organisasi</Text>
<List>
<Box px={20}>
<Text fz={{ base: "1rem", md: "1.125rem", lg: "1.25rem", xl: "1.5rem" }} ta={"justify"} dangerouslySetInnerHTML={{ __html: item.pengalaman }} />
</Box>
</List>
</Box>
<Box pb={20}>
<Text fz={{ base: "1.125rem", md: "1.375rem", lg: "1.75rem", xl: "2rem" }} fw={'bold'}>Program Kerja Unggulan</Text>
<List>
<Box px={20}>
<Text fz={{ base: "1rem", md: "1.125rem", lg: "1.25rem", xl: "1.5rem" }} ta={"justify"} dangerouslySetInnerHTML={{ __html: item.unggulan }} />
</Box>
</List>
</Box>
</Paper>
</Box>
))}
</Stack> </Stack>
</Paper> </Paper>
) )
} }
export default Page; export default Page;

View File

@@ -1,26 +0,0 @@
'use client'
import { Box, Text } from '@mantine/core';
import React from 'react';
import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../../_state/ppid/profile_ppid/profile_PPID';
import { PPIDTextEditor } from '../../_com/PPIDTextEditor';
function PengalamanOrganisasi() {
const pengalamanOrganisasiState = useProxy(stateProfilePPID)
return (<Box>
<Text fw={"bold"}>Pengalaman Organisasi</Text>
<PPIDTextEditor
key={pengalamanOrganisasiState.findById.data?.id ?? 'new'}
showSubmit={false}
onChange={(val) => {
if (pengalamanOrganisasiState.findById.data) {
pengalamanOrganisasiState.findById.data.pengalaman = val;
}
}}
initialContent={pengalamanOrganisasiState.findById.data?.pengalaman ?? ''}
/>
</Box>
);
}
export default PengalamanOrganisasi;

View File

@@ -1,26 +0,0 @@
'use client'
import { Box, Text } from '@mantine/core';
import React from 'react';
import { useProxy } from 'valtio/utils';
import stateProfilePPID from '../../../_state/ppid/profile_ppid/profile_PPID';
import { PPIDTextEditor } from '../../_com/PPIDTextEditor';
function ProgramKerjaUnggulan() {
const programKerjaUnggulanState = useProxy(stateProfilePPID)
return (<Box>
<Text fw={"bold"}>Program Kerja Unggulan</Text>
<PPIDTextEditor
key={programKerjaUnggulanState.findById.data?.id ?? 'new'}
showSubmit={false}
onChange={(val) => {
if (programKerjaUnggulanState.findById.data) {
programKerjaUnggulanState.findById.data.unggulan = val;
}
}}
initialContent={programKerjaUnggulanState.findById.data?.unggulan ?? ''}
/>
</Box>
);
}
export default ProgramKerjaUnggulan;

View File

@@ -1,33 +0,0 @@
'use client';
import { Box, Text } from '@mantine/core';
import React from 'react';
import { useProxy } from 'valtio/utils';
import dynamic from 'next/dynamic';
import stateProfilePPID from '../../../_state/ppid/profile_ppid/profile_PPID';
// ini penting
const PPIDTextEditor = dynamic(() => import('../../_com/PPIDTextEditor').then(mod => mod.PPIDTextEditor), {
ssr: false, // disable server side rendering
});
function RiwayatKarir() {
const riwayatKarirState = useProxy(stateProfilePPID);
return (
<Box>
<Text fw={"bold"}>Riwayat Karir</Text>
<PPIDTextEditor
key={riwayatKarirState.findById.data?.id ?? 'new'}
showSubmit={false}
onChange={(val) => {
if (riwayatKarirState.findById.data) {
riwayatKarirState.findById.data.riwayat = val;
}
}}
initialContent={riwayatKarirState.findById.data?.riwayat ?? ''}
/>
</Box>
);
}
export default RiwayatKarir;

View File

@@ -1,82 +0,0 @@
import prisma from "@/lib/prisma";
import { Context } from "elysia";
import { writeFile, unlink } from "fs/promises";
import path from "path";
import fs from "fs";
import { mkdir } from "fs/promises";
interface ProfilePPIDBody {
id: string;
file: Blob & { name: string; type: string };
}
export default async function editImageProfilePPID(context: Context<{ body: ProfilePPIDBody }>) {
const { id, file } = context.body;
if (!file || !id) {
return {
success: false,
message: "File atau ID harus disertakan",
};
}
// Validasi ekstensi file
const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
if (!allowedTypes.includes(file.type)) {
return {
success: false,
message: "Tipe file tidak diizinkan. Hanya JPG, PNG, atau WEBP",
};
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
const filename = `${id}_${Date.now()}_${file.name}`;
const folderPath = path.resolve("public", "assets", "images", "ppid", "profile-ppid");
try {
await mkdir(folderPath, { recursive: true });
console.log('Folder path:', folderPath);
const filePath = path.join(folderPath, filename);
console.log('File path:', filePath);
await writeFile(filePath, buffer);
if (!fs.existsSync(filePath)) {
return {
success: false,
message: "Failed to write file to disk",
};
}
const imageUrl = `/assets/images/ppid/profile-ppid/${filename}`;
// Hapus file lama (opsional, kalau mau bersih)
const oldData = await prisma.profilePPID.findUnique({ where: { id } });
if (oldData?.imageUrl) {
const oldPath = path.resolve("public", oldData.imageUrl.replace(/^\//, ""));
if (fs.existsSync(oldPath)) {
await unlink(oldPath).catch(() => {});
}
}
// Update DB
await prisma.profilePPID.update({
where: { id },
data: { imageUrl },
});
return {
success: true,
message: "Gambar berhasil diunggah",
url: imageUrl,
};
} catch (error) {
console.error('Error uploading file:', error);
return {
success: false,
message: "Gagal mengunggah gambar",
};
}
}

View File

@@ -1,33 +1,51 @@
import prisma from "@/lib/prisma"; import prisma from "@/lib/prisma";
import { Context } from "elysia";
export default async function profilePPIDFindById(context: Context) { export default async function handler(request: Request) {
try { const url = new URL(request.url);
const id = context?.params?.slugs?.[0]; const pathSegments = url.pathname.split('/');
const id = pathSegments[pathSegments.length - 1];
// If no ID provided, get the first profile
if (!id) { if (!id) {
const data = await prisma.profilePPID.findFirst(); return Response.json({
return { success: false,
success: true, message: "ID tidak boleh kosong",
data, }, { status: 400 });
};
} }
const data = await prisma.profilePPID.findUniqueOrThrow({ try {
if (typeof id !== 'string') {
return Response.json({
success: false,
message: "ID tidak valid",
}, { status: 400 });
}
const data = await prisma.profilePPID.findUnique({
where: { id }, where: { id },
include: {
image: true,
}
}); });
return { if (!data) {
success: true, return Response.json({
data,
};
} catch (error) {
console.error("Error fetching profilePPID:", error);
return {
success: false, success: false,
message: error instanceof Error ? error.message : "Unknown error", message: "Data tidak ditemukan",
}; }, { status: 404 });
}
return Response.json({
success: true,
message: "Berhasil mengambil data berdasarkan ID",
data,
}, { status: 200 });
} catch (e) {
console.error("Find by ID error:", e);
return Response.json({
success: false,
message: "Gagal mengambil data: " + (e instanceof Error ? e.message : 'Unknown error'),
}, {
status: 500,
});
} }
} }

View File

@@ -1,24 +1,30 @@
import Elysia, { t } from "elysia"; import Elysia, { t } from "elysia";
import profilePPIDFindById from "./find-by-id"; import profilePPIDFindById from "./find-by-id";
import profilePPIDUpdate from "./update"; import profilePPIDUpdate from "./update";
import editImageProfilePPID from "./edit-img";
const ProfilePPID = new Elysia({ const ProfilePPID = new Elysia({
prefix: "/profileppid", prefix: "/profileppid",
tags: ["PPID/Profile PPID"] tags: ["PPID/Profile PPID"]
}) })
.get("/find-by-id", profilePPIDFindById) .get("/:id", async (context) => {
.post("/update", profilePPIDUpdate, { const response = await profilePPIDFindById(new Request(context.request))
return response
})
.put("/:id", async (context) => {
const response = await profilePPIDUpdate(context)
return response
},
{
body: t.Object({ body: t.Object({
id: t.String(),
name: t.String(), name: t.String(),
biodata: t.String(), biodata: t.String(),
riwayat: t.String(), riwayat: t.String(),
pengalaman: t.String(), pengalaman: t.String(),
unggulan: t.String(), unggulan: t.String(),
imageId: t.String(),
}) })
}) }
.post("/edit-img", editImageProfilePPID) )
export default ProfilePPID; export default ProfilePPID;

View File

@@ -1,8 +1,10 @@
import prisma from "@/lib/prisma"; import prisma from "@/lib/prisma";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { Context } from "elysia"; import { Context } from "elysia";
import fs from "fs/promises";
import path from "path";
type FormCreate = Prisma.ProfilePPIDGetPayload<{ type FormUpdate = Prisma.ProfilePPIDGetPayload<{
select: { select: {
id: true; id: true;
name: true; name: true;
@@ -10,29 +12,110 @@ type FormCreate = Prisma.ProfilePPIDGetPayload<{
riwayat: true; riwayat: true;
pengalaman: true; pengalaman: true;
unggulan: true; unggulan: true;
} imageId: true;
}> };
}>;
export default async function profilePPIDUpdate(context: Context) { export default async function profilePPIDUpdate(context: Context) {
const body = context.body as FormCreate; try {
const id = context.params?.id as string;
const body = (await context.body) as Omit<FormUpdate, "id">;
await prisma.profilePPID.update({ const { name, biodata, riwayat, pengalaman, unggulan, imageId } = body;
if (!id) {
return new Response(
JSON.stringify({
success: false,
message: "ID tidak boleh kosong",
}),
{
status: 400,
headers: {
"Content-Type": "application/json",
},
}
);
}
const existing = await prisma.profilePPID.findUnique({
where: { where: {
id: body.id id,
},
include: {
image: true,
},
});
if (!existing) {
return new Response(
JSON.stringify({
success: false,
message: "Data tidak ditemukan",
}),
{
status: 404,
headers: {
"Content-Type": "application/json",
},
}
);
}
if (existing.imageId !== imageId) {
const oldImage = existing.image;
if (oldImage) {
try {
const filePath = path.join(oldImage.path, oldImage.name);
await fs.unlink(filePath);
await prisma.fileStorage.delete({
where: { id: oldImage.id },
});
} catch (error) {
console.error("Gagal hapus gambar lama:", error);
}
}
}
const updated = await prisma.profilePPID.update({
where: {
id,
}, },
data: { data: {
name: body.name, name,
biodata: body.biodata, biodata,
riwayat: body.riwayat, riwayat,
pengalaman: body.pengalaman, pengalaman,
unggulan: body.unggulan, imageId,
} unggulan,
}) },
});
return { return new Response(
JSON.stringify({
success: true, success: true,
message: "Profile PPID Berhasil Dibuat", message: "Profile PPID Berhasil Dibuat",
data: { data: updated,
...body, }),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
} }
);
} catch (error) {
console.error("Error updating profile PPID:", error);
return new Response(
JSON.stringify({
success: false,
message: "Terjadi kesalahan saat mengupdate profile PPID",
}),
{
status: 500,
headers: {
"Content-Type": "application/json",
},
}
);
} }
} }

View File

@@ -9,10 +9,10 @@ import BackButton from '../../desa/layanan/_com/BackButto';
function Page() { function Page() {
const allList = useProxy(stateProfilePPID) const allList = useProxy(stateProfilePPID)
useShallowEffect(() => { useShallowEffect(() => {
allList.findById.load("1") // Assuming "1" is your default ID, adjust as needed allList.profile.load("1") // Assuming "1" is your default ID, adjust as needed
}, []) }, [])
if (!allList.findById.data) return <Stack bg={colors.Bg} py={"xl"} gap={"22"}> if (!allList.profile.data) return <Stack bg={colors.Bg} py={"xl"} gap={"22"}>
<Box px={{ base: 'md', md: 100 }}> <Box px={{ base: 'md', md: 100 }}>
<Skeleton style={{backgroundColor: colors.Bg}} h={40} /> <Skeleton style={{backgroundColor: colors.Bg}} h={40} />
</Box> </Box>
@@ -28,9 +28,9 @@ function Page() {
</Box> </Box>
</Stack> </Stack>
const dataArray = Array.isArray(allList.findById.data) const dataArray = Array.isArray(allList.profile.data)
? allList.findById.data ? allList.profile.data
: [allList.findById.data]; : [allList.profile.data];
return ( return (
<Stack pos={"relative"} bg={colors.Bg} py={"xl"} gap={"22"}> <Stack pos={"relative"} bg={colors.Bg} py={"xl"} gap={"22"}>