Bagian Berita Di Admin Sudah Bisa Upload Di Bun Dev atau Bun Start

This commit is contained in:
2025-05-23 16:30:46 +08:00
parent ee9368e911
commit cf6a5422ec
13 changed files with 327 additions and 83 deletions

View File

@@ -242,17 +242,18 @@ model Berita {
id String @id @default(cuid())
judul String
deskripsi String
image String
image FileStorage @relation(fields: [imageId], references: [id])
imageId String
content String @db.Text
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime @default(now())
isActive Boolean @default(true)
KatagoryBerita KatagoryBerita? @relation(fields: [katagoryBeritaId], references: [id])
katagoryBeritaId String?
kategoriBerita KategoriBerita? @relation(fields: [kategoriBeritaId], references: [id])
kategoriBeritaId String?
}
model KatagoryBerita {
model KategoriBerita {
id String @id @default(cuid())
name String @unique
beritas Berita[]
@@ -596,4 +597,5 @@ model FileStorage {
deletedAt DateTime?
isActive Boolean @default(true)
link String
Berita Berita[]
}

View File

@@ -1,6 +1,6 @@
import prisma from "@/lib/prisma";
import categoryPengumuman from "./data/category-pengumuman.json";
import katagoryBerita from "./data/katagory-berita.json";
import kategoriBerita from "./data/kategori-berita.json";
import caraMemperolehInformasi from "./data/list-caraMemperolehInformasi.json";
import caraMemperolehSalinanInformasi from "./data/list-caraMemperolehSalinanInformasi.json";
import jenisInformasiDiminta from "./data/list-jenisInfromasi.json";
@@ -49,8 +49,8 @@ import { v4 as uuid } from "uuid";
console.log("potensi success ...");
for (const k of katagoryBerita) {
await prisma.katagoryBerita.upsert({
for (const k of kategoriBerita) {
await prisma.kategoriBerita.upsert({
where: {
name: k.name,
},
@@ -63,7 +63,7 @@ import { v4 as uuid } from "uuid";
});
}
console.log("katagory berita success ...");
console.log("kategori berita success ...");
for (const c of categoryPengumuman) {
await prisma.categoryPengumuman.upsert({

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

View File

@@ -8,16 +8,16 @@ import { z } from "zod";
const templateForm = z.object({
judul: z.string().min(3, "Judul minimal 3 karakter"),
deskripsi: z.string().min(3, "Deskripsi minimal 3 karakter"),
image: z.string().url().min(3, "Image minimal 3 karakter"),
content: z.string().min(3, "Content minimal 3 karakter"),
katagoryBeritaId: z.string().nonempty(),
kategoriBeritaId: z.string().nonempty(),
imageId: z.string().nonempty(),
});
const category = proxy({
findMany: {
data: null as
| null
| Prisma.KatagoryBeritaGetPayload<{ omit: { isActive: true } }>[],
| Prisma.KategoriBeritaGetPayload<{ omit: { isActive: true } }>[],
async load() {
const res = await ApiFetch.api.desa.berita.category["find-many"].get();
if (res.status === 200) {
@@ -31,9 +31,9 @@ type BeritaForm = Prisma.BeritaGetPayload<{
select: {
judul: true;
deskripsi: true;
image: true;
imageId: true;
content: true;
katagoryBeritaId: true;
kategoriBeritaId: true;
};
}>;
@@ -42,8 +42,6 @@ const berita = proxy({
form: {} as BeritaForm,
loading: false,
async create() {
berita.create.form.image =
"https://www.shutterstock.com/image-vector/lower-news-live-streaming-breaking-600nw-2535984111.jpg";
const cek = templateForm.safeParse(berita.create.form);
if (!cek.success) {
const err = `[${cek.error.issues
@@ -71,7 +69,12 @@ const berita = proxy({
},
findMany: {
data: null as
| Prisma.BeritaGetPayload<{ omit: { isActive: true } }>[]
| Prisma.BeritaGetPayload<{
include: {
image: true,
kategoriBerita: true
}
}>[]
| null,
async load() {
const res = await ApiFetch.api.desa.berita["find-many"].get();

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'
import { RichTextEditor, Link } from '@mantine/tiptap';
import { useEditor } from '@tiptap/react';
@@ -8,28 +9,38 @@ import TextAlign from '@tiptap/extension-text-align';
import Superscript from '@tiptap/extension-superscript';
import SubScript from '@tiptap/extension-subscript';
import { Button, Stack } from '@mantine/core';
import { useEffect } from 'react';
const content =
'<h2 style="text-align: center;">Welcome to Mantine rich text editor</h2><p><code>RichTextEditor</code> component focuses on usability and is designed to be as simple as possible to bring a familiar editing experience to regular users. <code>RichTextEditor</code> is based on <a href="https://tiptap.dev/" rel="noopener noreferrer" target="_blank">Tiptap.dev</a> and supports all of its features:</p><ul><li>General text formatting: <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strike-through</s> </li><li>Headings (h1-h6)</li><li>Sub and super scripts (<sup>&lt;sup /&gt;</sup> and <sub>&lt;sub /&gt;</sub> tags)</li><li>Ordered and bullet lists</li><li>Text align&nbsp;</li><li>And all <a href="https://tiptap.dev/extensions" target="_blank" rel="noopener noreferrer">other extensions</a></li></ul>';
// const content =
// '<h2 style="text-align: center;">Welcome to Mantine rich text editor</h2><p><code>RichTextEditor</code> component focuses on usability and is designed to be as simple as possible to bring a familiar editing experience to regular users. <code>RichTextEditor</code> is based on <a href="https://tiptap.dev/" rel="noopener noreferrer" target="_blank">Tiptap.dev</a> and supports all of its features:</p><ul><li>General text formatting: <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strike-through</s> </li><li>Headings (h1-h6)</li><li>Sub and super scripts (<sup>&lt;sup /&gt;</sup> and <sub>&lt;sub /&gt;</sub> tags)</li><li>Ordered and bullet lists</li><li>Text align&nbsp;</li><li>And all <a href="https://tiptap.dev/extensions" target="_blank" rel="noopener noreferrer">other extensions</a></li></ul>';
export function BeritaEditor({ onSubmit }: { onSubmit: (val: string) => void }) {
const editor = useEditor({
extensions: [
StarterKit,
Underline,
Link,
Superscript,
SubScript,
Highlight,
TextAlign.configure({ types: ['heading', 'paragraph'] }),
],
content,
immediatelyRender: false
});
if (!editor) {
return null;
}
export function BeritaEditor({
onEditorReady,
showSubmit = true,
onSubmit,
}: {
onEditorReady?: (editor: any | null) => void;
onSubmit?: (val: string) => void;
showSubmit?: boolean;
}) {
const editor = useEditor({
extensions: [
StarterKit,
Underline,
Link,
Superscript,
SubScript,
Highlight,
TextAlign.configure({ types: ['heading', 'paragraph'] }),
],
content: '',
});
useEffect(() => {
onEditorReady?.(editor);
}, [editor, onEditorReady] );
if (!editor) return null;
return (
@@ -82,10 +93,12 @@ export function BeritaEditor({ onSubmit }: { onSubmit: (val: string) => void })
<RichTextEditor.Content />
</RichTextEditor>
<Button onClick={() => {
if (!editor) return
onSubmit(editor?.getHTML())
}}>Submit</Button>
{showSubmit && (
<Button onClick={() => {
if (!editor) return
onSubmit?.(editor?.getHTML())
}}>Submit</Button>
)}
</Stack>
);
}

View File

@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client'
import { Box, Center, Group, Paper, Select, SimpleGrid, Skeleton, Stack, Text, TextInput, Title } from '@mantine/core';
import { Box, Button, Center, FileInput, Group, Image, Paper, Select, SimpleGrid, Skeleton, Stack, Text, TextInput, Title } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import { Prisma } from '@prisma/client';
import { IconImageInPicture } from '@tabler/icons-react';
@@ -7,48 +8,232 @@ import { useProxy } from 'valtio/utils';
import stateDashboardBerita from '../../_state/desa/berita';
import { BeritaEditor } from './_com/BeritaEditor';
import colors from '@/con/colors';
import { useState } from 'react';
import { toast } from 'react-toastify';
import ApiFetch from '@/lib/api-fetch';
function Page() {
return (
<Box>
<Title order={3}>Berita</Title>
<SimpleGrid cols={{ base: 1, md: 2 }}>
<BeritaCreate />
<BeritaList />
</SimpleGrid>
<BeritaCreate />
<BeritaList />
</Box>
);
}
// function BeritaCreate() {
// const beritaState = useProxy(stateDashboardBerita);
// const [previewImage, setPreviewImage] = useState<string | null>(null);
// const [file, setFile] = useState<File | null>(null);
// const [editorInstance, setEditorInstance] = useState<any>(null);
// const handleSubmit = async () => {
// if (!file) {
// return toast.warn("Pilih file gambar terlebih dahulu");
// }
// if (!editorInstance) return toast.error("Editor belum siap");
// const htmlContent = editorInstance.getHTML();
// if (!htmlContent || htmlContent === '<p></p>') return toast.warn("Konten tidak boleh kosong");
// beritaState.berita.create.form.content = htmlContent;
// console.log(beritaState.berita.create.form)
// // Upload gambar dulu
// const res = await ApiFetch.api.fileStorage.create.post({
// file,
// name: file.name,
// });
// const uploaded = res.data?.data;
// if (!uploaded?.id) {
// return toast.error("Gagal upload gambar");
// }
// // Simpan ID gambar ke form
// beritaState.berita.create.form.imageId = uploaded.id;
// // Submit data berita
// await beritaState.berita.create.create();
// };
// return (
// <Box py={10}>
// <Paper bg={colors["white-1"]} p={"md"}>
// <Stack gap={"xs"}>
// <SelectCategory
// onChange={(val) => {
// beritaState.berita.create.form.kategoriBeritaId = val.id;
// }}
// />
// <TextInput
// onChange={(val) => {
// beritaState.berita.create.form.judul = val.target.value;
// }}
// label={"Judul"}
// placeholder="masukkan judul"
// />
// <TextInput
// onChange={(val) => {
// beritaState.berita.create.form.deskripsi = val.target.value;
// }}
// label={"Deskripsi"}
// placeholder="masukkan deskripsi"
// />
// <FileInput
// label="Upload Gambar"
// onChange={async (e) => {
// if (!e) return;
// setFile(e);
// const base64 = await e.arrayBuffer().then((buf) =>
// "data:image/png;base64," + Buffer.from(buf).toString("base64")
// );
// setPreviewImage(base64);
// }}
// />
// {previewImage ? (
// <Image alt="" src={previewImage} w={200} h={200} />
// ) : (
// <Center w={200} h={200} bg={"gray"}>
// <IconImageInPicture />
// </Center>
// )}
// <BeritaEditor
// showSubmit={false}
// onEditorReady={(ed) => setEditorInstance(ed)}
// />
// <Button onClick={handleSubmit}>Simpan Berita</Button>
// </Stack>
// </Paper>
// </Box>
// );
// }
function BeritaCreate() {
const beritaState = useProxy(stateDashboardBerita)
const beritaState = useProxy(stateDashboardBerita);
const [previewImage, setPreviewImage] = useState<string | null>(null);
const [file, setFile] = useState<File | null>(null);
const [editorInstance, setEditorInstance] = useState<any>(null);
const resetForm = () => {
// Reset state di valtio
beritaState.berita.create.form = {
judul: "",
deskripsi: "",
kategoriBeritaId: "",
imageId: "",
content: "",
};
// Reset state lokal
setPreviewImage(null);
setFile(null);
if (editorInstance) {
editorInstance.commands.setContent(""); // Kosongkan editor
}
};
const handleSubmit = async () => {
if (!file) {
return toast.warn("Pilih file gambar terlebih dahulu");
}
if (!editorInstance) return toast.error("Editor belum siap");
const htmlContent = editorInstance.getHTML();
if (!htmlContent || htmlContent === "<p></p>") return toast.warn("Konten tidak boleh kosong");
beritaState.berita.create.form.content = htmlContent;
// Upload gambar dulu
const res = await ApiFetch.api.fileStorage.create.post({
file,
name: file.name,
});
const uploaded = res.data?.data;
if (!uploaded?.id) {
return toast.error("Gagal upload gambar");
}
// Simpan ID gambar ke form
beritaState.berita.create.form.imageId = uploaded.id;
// Submit data berita
await beritaState.berita.create.create();
toast.success("Berita berhasil disimpan!");
// Reset form setelah submit
resetForm();
};
return (
<Box py={10}>
<Paper bg={colors['white-1']} p={'md'}>
<Paper bg={colors["white-1"]} p={"md"} w={{base: "100%", md: "50%"}}>
<Stack gap={"xs"}>
<SelectCategory onChange={(val) => {
beritaState.berita.create.form.katagoryBeritaId = val.id
}} />
<TextInput onChange={(val) => {
beritaState.berita.create.form.judul = val.target.value
}} label={"Judul"} placeholder='masukkan judul' />
<TextInput onChange={(val) => {
beritaState.berita.create.form.deskripsi = val.target.value
}} label={"Deskripsi"} placeholder='masukkan deskripsi' />
<Center w={200} h={200} bg={"gray"}>
<IconImageInPicture />
</Center>
<BeritaEditor onSubmit={(val) => {
<SelectCategory
onChange={(val) => {
beritaState.berita.create.form.kategoriBeritaId = val.id;
}}
/>
<TextInput
value={beritaState.berita.create.form.judul}
onChange={(val) => {
beritaState.berita.create.form.judul = val.target.value;
}}
label={"Judul"}
placeholder="masukkan judul"
/>
<TextInput
value={beritaState.berita.create.form.deskripsi}
onChange={(val) => {
beritaState.berita.create.form.deskripsi = val.target.value;
}}
label={"Deskripsi"}
placeholder="masukkan deskripsi"
/>
beritaState.berita.create.form.content = val
beritaState.berita.create.create()
}} />
<FileInput
label="Upload Gambar"
value={file}
onChange={async (e) => {
if (!e) return;
setFile(e);
const base64 = await e.arrayBuffer().then((buf) =>
"data:image/png;base64," + Buffer.from(buf).toString("base64")
);
setPreviewImage(base64);
}}
/>
{previewImage ? (
<Image alt="" src={previewImage} w={200} h={200} />
) : (
<Center w={200} h={200} bg={"gray"}>
<IconImageInPicture />
</Center>
)}
<BeritaEditor
showSubmit={false}
onEditorReady={(ed) => setEditorInstance(ed)}
/>
<Button onClick={handleSubmit}>Simpan Berita</Button>
</Stack>
</Paper>
</Box>
)
);
}
function BeritaList() {
const beritaState = useProxy(stateDashboardBerita)
useShallowEffect(() => {
@@ -63,9 +248,30 @@ function BeritaList() {
<Paper bg={colors['white-1']} p={'md'}>
<Stack>
<Text fz={"xl"} fw={"bold"}>List Berita</Text>
<SimpleGrid cols={{ base: 1, md: 4 }}>
{beritaState.berita.findMany.data?.map((item) => (
<Text key={item.id}>{item.judul}</Text>
<Paper key={item.id} bg={colors['BG-trans']} p={'md'}>
<Box >
<Text fw={"bold"} fz={"sm"}>
Kategori
</Text>
<Text>{item.kategoriBerita?.name}</Text>
<Text fw={"bold"} fz={"sm"}>
Judul
</Text>
<Text>{item.judul}</Text>
<Text lineClamp={1} fw={"bold"} fz={"sm"}>
Deskripsi
</Text>
<Text size='sm' lineClamp={2}>{item.deskripsi}</Text>
<Text fw={"bold"} fz={"sm"}>
Gambar
</Text>
<Image w={200} src={item.image?.link} alt="gambar" />
</Box>
</Paper>
))}
</SimpleGrid>
</Stack>
</Paper>
</Box>
@@ -73,7 +279,7 @@ function BeritaList() {
}
function SelectCategory({ onChange }: {
onChange: (value: Prisma.KatagoryBeritaGetPayload<{
onChange: (value: Prisma.KategoriBeritaGetPayload<{
select: {
name: true,
id: true
@@ -87,7 +293,7 @@ function SelectCategory({ onChange }: {
if (!beritaState.category.findMany.data) return <Skeleton h={40} />
return <Group>
<Select placeholder='pilih katagori' label={<Text fz={"sm"} fw={"bold"}>Pilih Kategori</Text>} data={beritaState.category.findMany.data.map((item) => ({
<Select placeholder='pilih kategori' label={<Text fz={"sm"} fw={"bold"}>Pilih Kategori</Text>} data={beritaState.category.findMany.data.map((item) => ({
value: item.id,
label: item.name
}))} onChange={(v) => {

View File

@@ -1,9 +1,9 @@
import prisma from "@/lib/prisma";
async function katagoryBeritaFindMany() {
const data = await prisma.katagoryBerita.findMany();
async function kategoriBeritaFindMany() {
const data = await prisma.kategoriBerita.findMany();
return { data };
}
export default katagoryBeritaFindMany
export default kategoriBeritaFindMany

View File

@@ -6,13 +6,14 @@ type FormCreate = Prisma.BeritaGetPayload<{
select: {
judul: true;
deskripsi: true;
image: true;
content: true;
katagoryBeritaId: true;
kategoriBeritaId: true;
imageId: true;
};
}>;
async function beritaCreate(context: Context) {
const body = context.body as FormCreate;
console.log(body)
// console.log(body)
@@ -20,9 +21,9 @@ async function beritaCreate(context: Context) {
data: {
content: body.content,
deskripsi: body.deskripsi,
image: body.image,
imageId: body.imageId,
judul: body.judul,
katagoryBeritaId: body.katagoryBeritaId,
kategoriBeritaId: body.kategoriBeritaId,
},
});

View File

@@ -1,8 +1,27 @@
import prisma from "@/lib/prisma";
export default async function beritaFindMany() {
const res = await prisma.berita.findMany();
return {
data: res,
};
async function beritaFindMany() {
try {
const data = await prisma.berita.findMany({
where: { isActive: true },
include: {
image: true,
kategoriBerita: true,
},
});
return {
success: true,
message: "Success fetch berita",
data,
};
} catch (e) {
console.error("Find many error:", e);
return {
success: false,
message: "Failed fetch berita",
};
}
}
export default beritaFindMany;

View File

@@ -1,18 +1,18 @@
import Elysia, { t } from "elysia";
import katagoryBeritaFindMany from "./category";
import kategoriBeritaFindMany from "./category";
import beritaFindMany from "./find-many";
import beritaCreate from "./create";
const Berita = new Elysia({ prefix: "/berita", tags: ["Desa/Berita"] })
.get("/category/find-many", katagoryBeritaFindMany)
.get("/category/find-many", kategoriBeritaFindMany)
.get("/find-many", beritaFindMany)
.post("/create", beritaCreate, {
body: t.Object({
judul: t.String(),
deskripsi: t.String(),
image: t.String(),
imageId: t.String(),
content: t.String(),
katagoryBeritaId: t.Union([t.String(), t.Null()]),
kategoriBeritaId: t.Union([t.String(), t.Null()]),
}),
});