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

@@ -1,4 +1,3 @@
import ApiFetch from "@/lib/api-fetch";
import { Prisma } from "@prisma/client";
import { toast } from "react-toastify";
import { proxy } from "valtio";
@@ -13,11 +12,18 @@ const templateForm = z.object({
riwayat: z.string().min(3, "Riwayat minimal 3 karakter"),
pengalaman: z.string().min(3, "Pengalaman minimal 3 karakter"),
unggulan: z.string().min(3, "Unggulan minimal 3 karakter"),
imageId: z.string().min(1, "Gambar wajib dipilih"),
});
/**
* Tipe data ProfilePPID yang digunakan dalam form dan API, berdasarkan Prisma schema.
*/
const defaultForm = {
name: "",
biodata: "",
riwayat: "",
pengalaman: "",
unggulan: "",
imageId: "",
};
type ProfilePPIDForm = Prisma.ProfilePPIDGetPayload<{
select: {
id: true;
@@ -26,147 +32,170 @@ type ProfilePPIDForm = Prisma.ProfilePPIDGetPayload<{
riwayat: true;
pengalaman: true;
unggulan: true;
imageUrl: true;
imageId: true;
image?: {
select: {
link: true;
};
};
};
}>;
/**
* State utama ProfilePPID yang mencakup fitur:
* - Ambil data berdasarkan ID
* - Update data
* - Upload gambar
* Improved State Management - Consolidated and more robust
*/
const stateProfilePPID = proxy({
/**
* Bagian untuk ambil data berdasarkan ID
*/
findById: {
// Consolidated data management
profile: {
data: null as ProfilePPIDForm | null,
loading: false,
error: null as string | null,
/**
* 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.
*/
// Single method to load profile data
async load(id: string) {
try {
stateProfilePPID.findById.loading = true;
const res = await ApiFetch.api.ppid.profileppid["find-by-id"].get({
query: { id },
});
if (!id) {
toast.warn("ID tidak valid");
return null;
}
if (res.status === 200) {
stateProfilePPID.findById.data = res.data?.data ?? null;
this.loading = true;
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 {
toast.error("Gagal mengambil data profile");
throw new Error(result.message || "Gagal mengambil data profile");
}
} 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");
return null;
} finally {
stateProfilePPID.findById.loading = false;
this.loading = false;
}
},
// Reset profile data
reset() {
this.data = null;
this.error = null;
this.loading = false;
}
},
/**
* Bagian untuk update data profile
*/
update: {
// Edit form management
editForm: {
id: "",
form: { ...defaultForm },
loading: false,
error: null as string | null,
isReadOnly: false, // Flag untuk data yang tidak bisa diedit
/**
* Melakukan validasi dan menyimpan perubahan data profile ke server.
* @param {ProfilePPIDForm} data - Data profil yang akan disimpan.
*/
async save(data: ProfilePPIDForm) {
const cek = templateForm.safeParse(data);
// Initialize form with profile data
initialize(profileData: ProfilePPIDForm) {
this.id = profileData.id;
this.isReadOnly = false; // Semua data bisa diedit
this.form = {
name: profileData.name || "",
biodata: profileData.biodata || "",
riwayat: profileData.riwayat || "",
pengalaman: profileData.pengalaman || "",
unggulan: profileData.unggulan || "",
imageId: profileData.imageId || "",
};
},
if (!cek.success) {
const errors = cek.error.issues
// Update form field
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}`)
.join(", ");
toast.error(`Form tidak valid: ${errors}`);
return;
return false;
}
try {
stateProfilePPID.update.loading = true;
const res = await ApiFetch.api.ppid.profileppid["update"].post(data);
this.loading = true;
this.error = null;
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");
await stateProfilePPID.findById.load(data.id);
// Refresh profile data
await stateProfilePPID.profile.load(this.id);
return true;
} else {
toast.error("Gagal update profile");
throw new Error(result.message || "Gagal update profile");
}
} 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");
return false;
} finally {
stateProfilePPID.update.loading = false;
this.loading = false;
}
},
// Reset form
reset() {
this.id = "";
this.form = { ...defaultForm };
this.error = null;
this.loading = false;
this.isReadOnly = false;
}
},
/**
* Bagian untuk upload gambar profil
*/
uploadImage: {
loading: 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]);
return (
<Stack>
<Stack >
<RichTextEditor editor={editor}>
<RichTextEditor.Toolbar sticky stickyOffset={60}>
<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'
import colors from '@/con/colors';
import { Box, Button, Group, Paper, SimpleGrid, Stack, Text, TextInput, Title } from '@mantine/core';
import Biodata from './biodata/page';
import PengalamanOrganisasi from './pengalaman_organisasi/page';
import RiwayatKarir from './riwayat_karir/page';
import ProgramKerjaUnggulan from './program_kerja_unggulan/page';
import { Box, Button, Center, Divider, Flex, Grid, GridCol, Image, List, Paper, Skeleton, Stack, Text, Title } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { IconEdit } from '@tabler/icons-react';
import { useRouter } from 'next/navigation';
import { useProxy } from 'valtio/utils';
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() {
return (
<Box>
<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
const router = useRouter()
const allList = useProxy(stateProfilePPID)
useShallowEffect(() => {
if (!allState.findById.data && isLoading) {
allState.findById.initialize()
setIsLoading(false)
}
}, [isLoading])
allList.profile.load("1") // Assuming "1" is your default ID, adjust as needed
}, [])
const submit = () => {
if (
allState.findById.data?.name &&
allState.findById.data?.biodata &&
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")
}
if (!allList.profile.data) {
return <Stack>
<Skeleton radius={10} h={800} />
</Stack>
}
const dataArray = Array.isArray(allList.profile.data)
? allList.profile.data
: [allList.profile.data];
return (
<Paper bg={colors['white-1']} p={'md'} radius={10}>
<Paper bg={colors['white-1']} p={'md'}>
<Stack gap={"xs"}>
<Title order={3}>Profile PPID</Title>
<TextInput
label={<Text fw={"bold"}>Nama Perbekel</Text>}
placeholder="masukkan nama perbekel"
value={allState.findById.data?.name || ''}
onChange={(val) => {
if (allState.findById.data) {
allState.findById.data.name = val.currentTarget.value
}
}}
/>
<Biodata />
<RiwayatKarir />
<PengalamanOrganisasi />
<ProgramKerjaUnggulan />
<Group>
<Button
bg={colors['blue-button']}
onClick={submit}
loading={allState.update.loading}
>
Submit
</Button>
</Group>
<Grid>
<GridCol span={{ base: 12, md: 11 }}>
<Title order={3}>List Profile PPID</Title>
</GridCol>
<GridCol span={{ base: 12, md: 1 }}>
<Button bg={colors['blue-button']} onClick={() => router.push(`/admin/ppid/profile-ppid/${allList.profile.data?.id}`)}>
<IconEdit size={16} />
</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";
}}
/>
</Center>
<Paper
bg={colors['blue-button']}
py={30}
className="glass3"
px={{ base: 20, md: 20 }}
>
<Text ta={"center"} c={colors['white-1']} fw={"bolder"} fz={{ base: "1.5rem", md: "1.5rem" }}>
{item.name}
</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>
</Paper>
)
}
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;