Merge pull request #316 from bipproduction/bagas/17-feb-25

fix api forum
This commit is contained in:
Bagasbanuna02
2025-02-17 22:25:30 +08:00
committed by GitHub
23 changed files with 793 additions and 408 deletions

View File

@@ -2,11 +2,13 @@
import { MainColor } from "@/app_modules/_global/color";
import { UIGlobal_LayoutDefault } from "@/app_modules/_global/ui";
import { Button, Stack, Text, Title } from "@mantine/core";
import { Button, Stack, Title } from "@mantine/core";
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function InvalidUser() {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const deleteCookie = async () => {
const sessionKey = process.env.NEXT_PUBLIC_BASE_SESSION_KEY!;
if (!sessionKey) {
@@ -14,12 +16,15 @@ export default function InvalidUser() {
}
try {
setIsLoading(true);
await fetch("/api/auth/logout", {
method: "GET",
});
router.push("/login");
} catch (error) {
console.error("Gagal menghapus cookie:", error);
} finally {
setIsLoading(false);
}
};
@@ -32,6 +37,8 @@ export default function InvalidUser() {
Invalid User
</Title>
<Button
loading={isLoading}
loaderPosition="center"
radius={"xl"}
onClick={() => {
deleteCookie();

View File

@@ -1,4 +1,4 @@
export { apiGetAllForum };
export { apiGetAllForum, apiGetOneForumById, apiGetForumkuById };
const apiGetAllForum = async ({
page,
@@ -39,3 +39,75 @@ const apiGetAllForum = async ({
throw error; // Re-throw the error to handle it in the calling function
}
};
const apiGetOneForumById = async ({ id }: { id: string }) => {
try {
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) {
console.error("No token found");
return null;
}
const response = await fetch(`/api/forum/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error("Failed to get all forum:", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to get all forum");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error get all forum", error);
throw error; // Re-throw the error to handle it in the calling function
}
};
const apiGetForumkuById = async ({
id,
page,
}: {
id: string;
page: string;
}) => {
try {
// Fetch token from cookie
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) {
console.error("No token found");
return null;
}
const isPage = `?page=${page}`;
const response = await fetch(`/api/forum/forumku/${id}${isPage}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error("Failed to get all forum:", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to get all forum");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error get all forum", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -0,0 +1,63 @@
import { AccentColor } from "@/app_modules/_global/color";
import { clientLogger } from "@/util/clientLogger";
import { Center, Button } from "@mantine/core";
import { useState } from "react";
import { apiGetAllForum } from "../api_fetch_forum";
export function ButtonUpdateBeranda({
countNewPost,
onSetData,
onSetIsNewPost,
onSetCountNewPosting,
}: {
countNewPost: number;
onSetData: (val: any) => void;
onSetIsNewPost: (val: any) => void;
onSetCountNewPosting: (val: any) => void;
}) {
const [isLoading, setIsLoading] = useState(false);
const handleLoadData = async (isSearch: string) => {
try {
setIsLoading(true);
const response = await apiGetAllForum({
page: `1`,
search: isSearch,
});
if (response) {
onSetData(response.data);
onSetIsNewPost(false);
setIsLoading(false);
onSetCountNewPosting(0);
}
} catch (error) {
setIsLoading(false);
clientLogger.error("Error get data forum", error);
} finally {
setIsLoading(false);
}
};
return (
<>
<Center>
<Button
style={{
transition: "0.5s",
border: `1px solid ${AccentColor.skyblue}`,
}}
bg={AccentColor.blue}
loaderPosition="center"
loading={isLoading ? true : false}
radius={"xl"}
opacity={0.5}
onClick={() => handleLoadData("")}
>
Update beranda + {countNewPost}
</Button>
</Center>
</>
);
}

View File

@@ -1,25 +0,0 @@
"use client";
import { Overlay, Center, Loader } from "@mantine/core";
export default function ComponentForum_CardLoadingOverlay({
size,
variant,
}: {
size?: number;
variant?: any;
}) {
return (
<>
<Overlay h={"100%"} opacity={0.1} >
<Center h={"100%"}>
<Loader
variant={variant ? variant : "oval"}
size={size ? size : 20}
color="gray"
/>
</Center>
</Overlay>
</>
);
}

View File

@@ -1,22 +0,0 @@
"use client";
import { Center, Group, LoadingOverlay, Skeleton } from "@mantine/core";
export default function ComponentForum_LoadingDrawer() {
const customLoad = (
<Center h={"100vh"}>
<Group>
{Array(3)
.fill(0)
.map((e, i) => (
<Skeleton key={i} height={50} circle mb="xl" />
))}
</Group>
</Center>
);
return (
<>
{customLoad}
</>
);
}

View File

@@ -37,6 +37,7 @@ import {
AccentColor,
MainColor,
} from "@/app_modules/_global/color/color_pallet";
import { clientLogger } from "@/util/clientLogger";
export default function ComponentForum_BerandaMoreButton({
authorId,
@@ -255,11 +256,11 @@ function ButtonDelete({
const [loading, setLoading] = useState(false);
async function onDelete() {
setOpenDel(false);
await forum_funDeletePostingById(postingId as any).then(async (res) => {
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(`Postingan Terhapus`, 2000);
setLoading(true);
try {
setLoading(true);
const deleteData = await forum_funDeletePostingById(postingId as any);
if (deleteData.status === 200) {
setOpenDel(false);
const cloneData = _.clone(allData);
const hapusData = cloneData.filter((e) => e.id !== postingId);
@@ -272,10 +273,16 @@ function ButtonDelete({
data: hapusData,
})
);
ComponentGlobal_NotifikasiBerhasil(`Postingan Terhapus`, 2000);
} else {
ComponentGlobal_NotifikasiGagal(res.message);
setLoading(false);
ComponentGlobal_NotifikasiGagal(deleteData.message);
}
});
} catch (error) {
setLoading(false);
clientLogger.error("Error get data forum", error);
}
}
return (
<>
@@ -324,120 +331,132 @@ function ButtonStatus({
const [loading, setLoading] = useState(false);
async function onTutupForum() {
setOpenStatus(false);
const upateStatusClose = await forum_funEditStatusPostingById(
postingId as any,
2
);
if (upateStatusClose.status === 200) {
ComponentGlobal_NotifikasiBerhasil(`Forum Ditutup`, 2000);
try {
setLoading(true);
const cloneData = _.clone(allData);
const loadData = cloneData.map(
(e) => (
e.id === postingId,
{
...e,
ForumMaster_StatusPosting: {
id: e.id === postingId ? 2 : e.ForumMaster_StatusPosting.id,
status:
e.id === postingId
? "Close"
: e.ForumMaster_StatusPosting.status,
},
}
)
);
onLoadData(loadData);
//
mqtt_client.publish(
"Forum_ganti_status",
JSON.stringify({
id: postingId,
data: loadData,
})
const upateStatusClose = await forum_funEditStatusPostingById(
postingId as any,
2
);
const findData = cloneData.find((val) => val.id === postingId);
const updateDetail = {
...findData,
ForumMaster_StatusPosting: {
id: 2,
status: "Close",
},
};
if (upateStatusClose.status === 200) {
setOpenStatus(false);
ComponentGlobal_NotifikasiBerhasil(`Forum Ditutup`, 2000);
mqtt_client.publish(
"Forum_detail_ganti_status",
JSON.stringify({
id: postingId,
data: updateDetail.ForumMaster_StatusPosting,
})
);
} else {
ComponentGlobal_NotifikasiGagal(upateStatusClose.message);
const cloneData = _.clone(allData);
const loadData = cloneData.map(
(e) => (
e.id === postingId,
{
...e,
ForumMaster_StatusPosting: {
id: e.id === postingId ? 2 : e.ForumMaster_StatusPosting.id,
status:
e.id === postingId
? "Close"
: e.ForumMaster_StatusPosting.status,
},
}
)
);
onLoadData(loadData);
//
mqtt_client.publish(
"Forum_ganti_status",
JSON.stringify({
id: postingId,
data: loadData,
})
);
const findData = cloneData.find((val) => val.id === postingId);
const updateDetail = {
...findData,
ForumMaster_StatusPosting: {
id: 2,
status: "Close",
},
};
mqtt_client.publish(
"Forum_detail_ganti_status",
JSON.stringify({
id: postingId,
data: updateDetail.ForumMaster_StatusPosting,
})
);
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(upateStatusClose.message);
}
} catch (error) {
setLoading(false);
clientLogger.error("Error get data forum", error);
}
}
async function onBukaForum() {
setOpenStatus(false);
const updateStatusOpen = await forum_funEditStatusPostingById(
postingId as any,
1
);
if (updateStatusOpen.status === 200) {
ComponentGlobal_NotifikasiBerhasil(`Forum Dibuka`, 2000);
try {
setLoading(true);
const cloneData = _.clone(allData);
const loadData = cloneData.map(
(e) => (
e.id === postingId,
{
...e,
ForumMaster_StatusPosting: {
id: e.id === postingId ? 1 : e.ForumMaster_StatusPosting.id,
status:
e.id === postingId
? "Open"
: e.ForumMaster_StatusPosting.status,
},
}
)
const updateStatusOpen = await forum_funEditStatusPostingById(
postingId as any,
1
);
mqtt_client.publish(
"Forum_ganti_status",
JSON.stringify({
id: postingId,
data: loadData,
})
);
if (updateStatusOpen.status === 200) {
setOpenStatus(false);
ComponentGlobal_NotifikasiBerhasil(`Forum Dibuka`, 2000);
onLoadData(loadData);
const cloneData = _.clone(allData);
const loadData = cloneData.map(
(e) => (
e.id === postingId,
{
...e,
ForumMaster_StatusPosting: {
id: e.id === postingId ? 1 : e.ForumMaster_StatusPosting.id,
status:
e.id === postingId
? "Open"
: e.ForumMaster_StatusPosting.status,
},
}
)
);
const findData = cloneData.find((val) => val.id === postingId);
const updateDetail = {
...findData,
ForumMaster_StatusPosting: {
id: 1,
status: "Open",
},
};
mqtt_client.publish(
"Forum_ganti_status",
JSON.stringify({
id: postingId,
data: loadData,
})
);
mqtt_client.publish(
"Forum_detail_ganti_status",
JSON.stringify({
id: postingId,
data: updateDetail.ForumMaster_StatusPosting,
})
);
} else {
ComponentGlobal_NotifikasiGagal(updateStatusOpen.message);
onLoadData(loadData);
const findData = cloneData.find((val) => val.id === postingId);
const updateDetail = {
...findData,
ForumMaster_StatusPosting: {
id: 1,
status: "Open",
},
};
mqtt_client.publish(
"Forum_detail_ganti_status",
JSON.stringify({
id: postingId,
data: updateDetail.ForumMaster_StatusPosting,
})
);
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(updateStatusOpen.message);
}
} catch (error) {
setLoading(false);
clientLogger.error("Error get data forum", error);
}
}
@@ -461,7 +480,7 @@ function ButtonStatus({
{statusId === 1 ? (
<Button
loaderPosition="center"
loading={loading ? true : false}
loading={loading}
color="orange"
radius={"xl"}
onClick={() => {
@@ -473,7 +492,7 @@ function ButtonStatus({
) : (
<Button
loaderPosition="center"
loading={loading ? true : false}
loading={loading}
color="green"
radius={"xl"}
onClick={() => {

View File

@@ -0,0 +1,19 @@
import { Stack, Text } from "@mantine/core";
import { IconSearchOff } from "@tabler/icons-react";
export { Forum_ComponentIsDataEmpty };
function Forum_ComponentIsDataEmpty() {
return (
<>
<Stack align="center" justify="center" h={"80vh"}>
<IconSearchOff size={80} color="white" />
<Stack spacing={0} align="center">
<Text color="white" fw={"bold"} fz={"xs"}>
Tidak ada data
</Text>
</Stack>
</Stack>
</>
);
}

View File

@@ -0,0 +1,42 @@
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { Center, Grid, Group, Stack } from "@mantine/core";
export { Forum_SkeletonCard, Forum_SkeletonForumku };
function Forum_SkeletonCard() {
return (
<>
<Stack>
<CustomSkeleton height={230} width={"100%"} />
<CustomSkeleton height={230} width={"100%"} />
</Stack>
</>
);
}
function Forum_SkeletonForumku(){
return (
<>
<Stack spacing={"xl"}>
<Center>
<CustomSkeleton height={100} width={100} circle />
</Center>
<Grid grow>
<Grid.Col span={6}>
<Stack spacing={"xs"}>
<CustomSkeleton height={15} width={"80%"} />
<CustomSkeleton height={15} width={"80%"} />
</Stack>
</Grid.Col>
<Grid.Col span={6}>
<Group position="right">
<CustomSkeleton height={40} width={"80%"} radius={"xl"} />
</Group>
</Grid.Col>
</Grid>
</Stack>
</>
);
}

View File

@@ -1,6 +1,5 @@
"use client";
import ComponentGlobal_V2_LoadingPage from "@/app_modules/_global/loading_page_v2";
import { Button, Group, Paper, Stack } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { useRouter } from "next/navigation";
@@ -21,11 +20,10 @@ const ReactQuill = dynamic(
);
import {
AccentColor,
MainColor,
MainColor
} from "@/app_modules/_global/color/color_pallet";
import mqtt_client from "@/util/mqtt_client";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import mqtt_client from "@/util/mqtt_client";
const maxLength = 500;
export default function Forum_Create() {

View File

@@ -1,35 +1,23 @@
"use client";
import {
ActionIcon,
Button,
Center,
Group,
Loader,
Paper,
Stack,
} from "@mantine/core";
import "react-quill/dist/quill.snow.css";
import "react-quill/dist/quill.bubble.css";
import { IconPhotoUp } from "@tabler/icons-react";
import { Button, Group, Paper, Stack } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { useRouter } from "next/navigation";
import ComponentGlobal_V2_LoadingPage from "@/app_modules/_global/loading_page_v2";
import { useParams, useRouter } from "next/navigation";
import "react-quill/dist/quill.bubble.css";
import "react-quill/dist/quill.snow.css";
import dynamic from "next/dynamic";
import React, { useState } from "react";
import { useAtom } from "jotai";
import { gs_forum_loading_edit_posting } from "../../global_state";
import { MODEL_FORUM_POSTING } from "../../model/interface";
import { forum_funEditPostingById } from "../../fun/edit/fun_edit_posting_by_id";
import { MainColor } from "@/app_modules/_global/color/color_pallet";
import ComponentGlobal_InputCountDown from "@/app_modules/_global/component/input_countdown";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global/notifikasi_peringatan";
import ComponentGlobal_InputCountDown from "@/app_modules/_global/component/input_countdown";
import {
AccentColor,
MainColor,
} from "@/app_modules/_global/color/color_pallet";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { clientLogger } from "@/util/clientLogger";
import dynamic from "next/dynamic";
import { useState } from "react";
import { apiGetOneForumById } from "../../component/api_fetch_forum";
import { forum_funEditPostingById } from "../../fun/edit/fun_edit_posting_by_id";
import { MODEL_FORUM_POSTING } from "../../model/interface";
const ReactQuill = dynamic(
() => {
return import("react-quill");
@@ -37,23 +25,35 @@ const ReactQuill = dynamic(
{ ssr: false }
);
export default function Forum_EditPosting({
dataPosting,
}: {
dataPosting: MODEL_FORUM_POSTING;
}) {
const [value, setValue] = useState(dataPosting);
const maxLength = 500;
export default function Forum_EditPosting() {
const param = useParams<{ id: string }>();
const [data, setData] = useState<MODEL_FORUM_POSTING | null>(null);
const [reload, setReload] = useState(false);
useShallowEffect(() => {
if (window && window.document) setReload(true);
}, []);
if (!reload)
return (
<>
<ComponentGlobal_V2_LoadingPage />
</>
);
useShallowEffect(() => {
handleLoadData();
}, []);
const handleLoadData = async () => {
try {
const response = await apiGetOneForumById({
id: param.id,
});
if (response.success) {
setData(response.data);
}
} catch (error) {
clientLogger.error("Error get data forum", error);
}
};
if (!reload || !data) return <CustomSkeleton height={200} />;
return (
<>
@@ -63,10 +63,21 @@ export default function Forum_EditPosting({
theme="bubble"
placeholder="Apa yang sedang ingin dibahas ?"
style={{ height: 150 }}
value={value.diskusi}
value={data.diskusi}
onChange={(val) => {
setValue({
...value,
const input = val;
const text = input.replace(/<[^>]+>/g, "").trim(); // Remove HTML tags and trim whitespace
if (text.length === 0) {
setData({
...data,
diskusi: "",
});
return;
}
setData({
...data,
diskusi: val,
});
}}
@@ -74,15 +85,12 @@ export default function Forum_EditPosting({
</Paper>
<Group position="right">
<ComponentGlobal_InputCountDown
maxInput={500}
lengthInput={value.diskusi.length}
maxInput={maxLength}
lengthInput={data.diskusi.length}
/>
</Group>
<Group position="right">
{/* <ActionIcon>
<IconPhotoUp />
</ActionIcon> */}
<ButtonAction diskusi={value.diskusi as any} postingId={value.id} />
<ButtonAction diskusi={data.diskusi as any} postingId={data.id} />
</Group>
</Stack>
{/* <div dangerouslySetInnerHTML={{ __html: value.diskusi }} /> */}
@@ -104,15 +112,21 @@ function ButtonAction({
if (diskusi === "<p><br></p>" || diskusi === "")
return ComponentGlobal_NotifikasiPeringatan("Masukan postingan anda");
await forum_funEditPostingById(postingId, diskusi).then((res) => {
if (res.status === 200) {
setLoading(true);
ComponentGlobal_NotifikasiBerhasil(res.message);
setTimeout(() => router.back(), 1000);
try {
setLoading(true);
const update = await forum_funEditPostingById(postingId, diskusi);
if (update.status === 200) {
ComponentGlobal_NotifikasiBerhasil(update.message);
router.back();
} else {
ComponentGlobal_NotifikasiGagal(res.message);
ComponentGlobal_NotifikasiGagal(update.message);
}
});
} catch (error) {
clientLogger.error("Error update forum", error);
} finally {
setLoading(false);
}
}
return (
@@ -120,23 +134,24 @@ function ButtonAction({
<Button
style={{
transition: "0.5s",
border:
diskusi === "<p><br></p>" || diskusi === "" || diskusi.length > 500
? ""
: `1px solid ${AccentColor.yellow}`,
backgroundColor:
diskusi === "<p><br></p>" || diskusi === "" || diskusi.length > 500
diskusi === "<p><br></p>" ||
diskusi === "" ||
diskusi.length >= maxLength
? ""
: MainColor.yellow,
}}
disabled={
diskusi === "<p><br></p>" || diskusi === "" || diskusi.length > 500
diskusi === "<p><br></p>" ||
diskusi === "" ||
diskusi.length >= maxLength
? true
: false
}
loaderPosition="center"
loading={loading ? true : false}
loading={loading}
radius={"xl"}
c={"black"}
onClick={() => {
onUpdate();
}}

View File

@@ -1,9 +1,7 @@
"use client";
import { RouterForum } from "@/lib/router_hipmi/router_forum";
import {
AccentColor
} from "@/app_modules/_global/color/color_pallet";
import { AccentColor } from "@/app_modules/_global/color/color_pallet";
import { MODEL_USER } from "@/app_modules/home/model/interface";
import {
ActionIcon,
@@ -14,91 +12,149 @@ import {
Text,
rem,
} from "@mantine/core";
import { useWindowScroll } from "@mantine/hooks";
import { useShallowEffect, useWindowScroll } from "@mantine/hooks";
import { IconPencilPlus, IconSearchOff } from "@tabler/icons-react";
import _ from "lodash";
import { ScrollOnly } from "next-scroll-loader";
import { useRouter } from "next/navigation";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import ComponentForum_ForumkuMainCardView from "../component/forumku_component/forumku_view";
import { forum_getAllPostingByAuhtorId } from "../fun/get/get_list_posting_by_author_id";
import { MODEL_FORUM_POSTING } from "../model/interface";
import ComponentForum_ViewForumProfile from "./forum_profile";
import ComponentGlobal_CreateButton from "@/app_modules/_global/component/button_create";
import { apiGetUserById } from "@/app_modules/_global/lib/api_user";
import backendLogger from "@/util/backendLogger";
import { clientLogger } from "@/util/clientLogger";
import { apiGetForumkuById } from "../component/api_fetch_forum";
import {
Forum_SkeletonCard,
Forum_SkeletonForumku,
} from "../component/skeleton_view";
import { data } from "autoprefixer";
import { Forum_ComponentIsDataEmpty } from "../component/other_component";
export default function Forum_Forumku({
auhtorSelectedData,
dataPosting,
totalPosting,
userLoginId,
}: {
auhtorSelectedData: MODEL_USER;
dataPosting: MODEL_FORUM_POSTING[];
totalPosting: number;
userLoginId: string;
}) {
const router = useRouter();
const [data, setData] = useState(dataPosting);
const params = useParams<{ id: string }>();
const userId = params.id;
const [dataUser, setDataUser] = useState<MODEL_USER | null>(null);
const [dataPosting, setDataPosting] = useState<MODEL_FORUM_POSTING[]>([]);
const [activePage, setActivePage] = useState(1);
const [scroll, scrollTo] = useWindowScroll();
const [loadingCreate, setLoadingCreate] = useState(false);
useShallowEffect(() => {
const handleLoadDataUser = async () => {
try {
const response = await apiGetUserById({
id: userId,
});
if (response) {
console.log("response", response);
setDataUser(response.data);
}
} catch (error) {
clientLogger.error("Error get user", error);
}
};
handleLoadDataUser();
}, []);
useShallowEffect(() => {
handleLoadDataForum();
}, []);
const handleLoadDataForum = async () => {
try {
const response = await apiGetForumkuById({
id: userId,
page: "1",
});
if (response.success) {
setDataPosting(response.data);
setActivePage(1);
}
} catch (error) {
clientLogger.error("Error get data forum");
setDataPosting([]);
}
};
const handleMoreData = async () => {
try {
const nextPage = activePage + 1;
const response = await apiGetForumkuById({
id: userId,
page: `${nextPage}`,
});
if (response.success) {
setActivePage(nextPage);
return response.data;
} else {
return null;
}
} catch (error) {
clientLogger.error("Error get data forum");
return null;
}
};
return (
<>
{userLoginId === auhtorSelectedData.id && (
<ComponentGlobal_CreateButton path={RouterForum.create} />
)}
<Stack spacing={"xl"}>
<ComponentForum_ViewForumProfile
auhtorSelectedData={auhtorSelectedData}
totalPosting={totalPosting}
/>
{!dataUser ? (
<Forum_SkeletonForumku />
) : (
<ComponentForum_ViewForumProfile
auhtorSelectedData={dataUser}
totalPosting={totalPosting}
/>
)}
{_.isEmpty(data) ? (
<Stack align="center" justify="center" h={"80vh"}>
<IconSearchOff size={80} color="white" />
<Stack spacing={0} align="center">
<Text c={"white"} fw={"bold"} fz={"xs"}>
Tidak ada data
</Text>
</Stack>
</Stack>
{!dataPosting.length ? (
<Forum_SkeletonCard />
) : _.isEmpty(dataPosting) ? (
<Forum_ComponentIsDataEmpty />
) : (
// --- Main component --- //
<ScrollOnly
height={data.length < 5 ? "75vh" : "100vh"}
height={dataPosting.length < 5 ? "75vh" : "100vh"}
renderLoading={() => (
<Center mt={"lg"}>
<Loader color={"yellow"} />
</Center>
)}
data={data}
setData={setData}
moreData={async () => {
const loadData = await forum_getAllPostingByAuhtorId({
page: activePage + 1,
authorId: auhtorSelectedData.id,
});
setActivePage((val) => val + 1);
return loadData;
}}
data={dataPosting}
setData={setDataPosting}
moreData={handleMoreData}
>
{(item) => (
<ComponentForum_ForumkuMainCardView
data={item}
userLoginId={userLoginId}
onLoadData={(val) => {
setData(val);
setDataPosting(val);
}}
allData={data}
allData={dataPosting}
/>
)}
</ScrollOnly>
)}
</Stack>
{userLoginId === dataUser?.id && (
<ComponentGlobal_CreateButton path={RouterForum.create} />
)}
</>
);
}

View File

@@ -7,10 +7,8 @@ import React from "react";
export default function LayoutForum_Forumku({
children,
username,
}: {
children: React.ReactNode;
username: string;
}) {
return (
<>

View File

@@ -7,16 +7,22 @@ export async function forum_funEditPostingById(
postingId: string,
diskusi: string
) {
const updt = await prisma.forum_Posting.update({
where: {
id: postingId,
},
data: {
diskusi: diskusi,
},
});
try {
const updt = await prisma.forum_Posting.update({
where: {
id: postingId,
},
data: {
diskusi: diskusi,
},
});
if (!updt) return { status: 400, message: "Gagal update" };
revalidatePath("/dev/forum/main");
return { status: 200, message: "Berhasil update" };
if (!updt) {
return { success: false, message: "Update gagal", status: 400 }; // Plain object dengan status
}
revalidatePath("/dev/forum/main");
return { success: true, message: "Berhasil update", status: 200 }; // Plain object dengan status
} catch (error) {
return { success: false, message: "Update error", status: 500 }; // Plain object dengan status
}
}

View File

@@ -1,65 +1,92 @@
"use client";
import { RouterForum } from "@/lib/router_hipmi/router_forum";
import { AccentColor } from "@/app_modules/_global/color/color_pallet";
import ComponentGlobal_CreateButton from "@/app_modules/_global/component/button_create";
import mqtt_client from "@/util/mqtt_client";
import {
Affix,
Button,
Center,
Loader,
Stack,
Text,
TextInput,
rem,
} from "@mantine/core";
import { useShallowEffect, useWindowScroll } from "@mantine/hooks";
import { IconSearchOff } from "@tabler/icons-react";
import { RouterForum } from "@/lib/router_hipmi/router_forum";
import { clientLogger } from "@/util/clientLogger";
import { Affix, Center, Loader, Stack, TextInput, rem } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import _ from "lodash";
import { ScrollOnly } from "next-scroll-loader";
import { useRouter } from "next/navigation";
import { useState } from "react";
import ComponentForum_BerandaCardView from "../component/main_component/card_view";
import { forum_new_getAllPosting } from "../fun/get/new_get_all_posting";
import { MODEL_FORUM_POSTING } from "../model/interface";
import { apiGetAllForum } from "../component/api_fetch_forum";
import { clientLogger } from "@/util/clientLogger";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { ButtonUpdateBeranda } from "../component/button/button_update_beranda";
import ComponentForum_BerandaCardView from "../component/main_component/card_view";
import { Forum_ComponentIsDataEmpty } from "../component/other_component";
import { Forum_SkeletonCard } from "../component/skeleton_view";
import { MODEL_FORUM_POSTING } from "../model/interface";
import mqtt_client from "@/util/mqtt_client";
export default function Forum_Beranda({
userLoginId,
}: {
userLoginId: string;
}) {
const router = useRouter();
const [scroll, scrollTo] = useWindowScroll();
const [data, setData] = useState<MODEL_FORUM_POSTING[] | null>(null);
const [data, setData] = useState<MODEL_FORUM_POSTING[]>([]);
const [activePage, setActivePage] = useState(1);
const [isSearch, setIsSearch] = useState("");
const [isNewPost, setIsNewPost] = useState(false);
const [countNewPost, setCountNewPost] = useState(0);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(false);
useShallowEffect(() => {
handleLoadData(isSearch);
}, [isSearch]);
const handleLoadData = async (isSearch: string) => {
setIsLoading(true);
try {
const response = await apiGetAllForum({
page: `${activePage}`,
page: "1",
search: isSearch,
});
if (response) {
setData(response.data);
setActivePage(1);
setHasMore(response.data.length > 0);
}
} catch (error) {
clientLogger.error("Error get data forum", error);
setData([]);
setHasMore(false);
} finally {
setIsLoading(false);
}
};
const handleMoreData = async () => {
if (!hasMore || isLoading) return null;
try {
const nextPage = activePage + 1;
const response = await apiGetAllForum({
page: `${nextPage}`,
search: isSearch,
});
if (response?.data && response.data.length > 0) {
setActivePage(nextPage);
setHasMore(response.data.length > 0);
return response.data;
} else {
setHasMore(false);
return null;
}
} catch (error) {
clientLogger.error("Error get data forum", error);
setHasMore(false);
return null;
}
};
const hanldeSearch = async (text: string) => {
setIsSearch(text);
setActivePage(1);
setHasMore(true);
};
useShallowEffect(() => {
mqtt_client.subscribe("Forum_create_new");
mqtt_client.subscribe("Forum_ganti_status");
@@ -109,12 +136,6 @@ export default function Forum_Beranda({
});
}, [countNewPost, data]);
async function onSearch(text: string) {
setIsSearch(text);
setActivePage(1);
}
return (
<>
{isNewPost && (
@@ -140,24 +161,14 @@ export default function Forum_Beranda({
radius={"xl"}
placeholder="Topik forum apa yang anda cari hari ini ?"
onChange={(val) => {
onSearch(val.currentTarget.value);
hanldeSearch(val.currentTarget.value);
}}
/>
{!data ? (
<Stack>
<CustomSkeleton height={230} width={"100%"} />
<CustomSkeleton height={230} width={"100%"} />
</Stack>
{!data.length && isLoading ? (
<Forum_SkeletonCard />
) : _.isEmpty(data) ? (
<Stack align="center" justify="center" h={"80vh"}>
<IconSearchOff size={80} color="white" />
<Stack spacing={0} align="center">
<Text color="white" fw={"bold"} fz={"xs"}>
Tidak ada data
</Text>
</Stack>
</Stack>
<Forum_ComponentIsDataEmpty />
) : (
// --- Main component --- //
<ScrollOnly
@@ -169,22 +180,7 @@ export default function Forum_Beranda({
)}
data={data}
setData={setData as any}
moreData={async () => {
try {
const nextPage = activePage + 1;
const response = await apiGetAllForum({
page: `${nextPage}`,
search: isSearch,
});
if (response) {
setActivePage((val) => val + 1);
return response.data;
}
} catch (error) {
clientLogger.error("Error get data forum", error);
}
}}
moreData={handleMoreData}
>
{(item) => (
<ComponentForum_BerandaCardView
@@ -202,51 +198,3 @@ export default function Forum_Beranda({
</>
);
}
function ButtonUpdateBeranda({
countNewPost,
onSetData,
onSetIsNewPost,
onSetCountNewPosting,
}: {
countNewPost: number;
onSetData: (val: any) => void;
onSetIsNewPost: (val: any) => void;
onSetCountNewPosting: (val: any) => void;
}) {
const [scroll, scrollTo] = useWindowScroll();
const [isLoading, setIsLoading] = useState(false);
async function onLoadData() {
setIsLoading(true);
const loadData = await forum_new_getAllPosting({ page: 1 });
if (loadData) {
onSetData(loadData);
onSetIsNewPost(false);
setIsLoading(false);
onSetCountNewPosting(0);
}
}
return (
<>
<Center>
<Button
style={{
transition: "0.5s",
border: `1px solid ${AccentColor.skyblue}`,
}}
bg={AccentColor.blue}
loaderPosition="center"
loading={isLoading ? true : false}
radius={"xl"}
opacity={scroll.y > 0 ? 0.5 : 0.8}
onClick={() => onLoadData()}
>
Update beranda + {countNewPost}
</Button>
</Center>
</>
);
}