fix forum

deskripsi:
- fix postingan dan komentar
This commit is contained in:
2025-02-18 16:25:23 +08:00
parent c9f766314c
commit 4318ea4890
16 changed files with 397 additions and 191 deletions

View File

@@ -1 +0,0 @@
nice -n 19 bun --env-file=.env.build run --bun build

1
run.env.build.dev Normal file
View File

@@ -0,0 +1 @@
nice -n 19 bun --env-file=.env run --bun build

1
run.env.start.dev Normal file
View File

@@ -0,0 +1 @@
nice -n 19 bun --env-file=.env run --bun start

0
run.env.strat.local Normal file
View File

View File

@@ -0,0 +1,93 @@
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export { GET };
async function GET(request: Request, { params }: { params: { id: string } }) {
try {
let fixData;
const { id } = params;
const { searchParams } = new URL(request.url);
const page = searchParams.get("page");
const takeData = 5;
const skipData = Number(page) * takeData - takeData;
if (!page) {
fixData = await prisma.forum_Komentar.findMany({
orderBy: {
createdAt: "desc",
},
where: {
forum_PostingId: id,
isActive: true,
},
select: {
id: true,
isActive: true,
komentar: true,
createdAt: true,
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
name: true,
imageId: true,
},
},
},
},
authorId: true,
},
});
} else {
fixData = await prisma.forum_Komentar.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
forum_PostingId: id,
isActive: true,
},
select: {
id: true,
isActive: true,
komentar: true,
createdAt: true,
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
name: true,
imageId: true,
},
},
},
},
authorId: true,
},
});
}
return NextResponse.json({
success: true,
message: "Berhasil mendapatkan data",
data: fixData,
});
} catch (error) {
backendLogger.error("Error Get Forum Komentar >>", error);
return NextResponse.json(
{
success: false,
message: "API Error Get Data",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -10,21 +10,19 @@ export default async function Page({ params }: { params: { id: string } }) {
let postingId = params.id; let postingId = params.id;
const userLoginId = await funGetUserIdByToken(); const userLoginId = await funGetUserIdByToken();
const dataPosting = await forum_getOnePostingById(postingId); // const dataPosting = await forum_getOnePostingById(postingId);
const listKomentar = await forum_funGetAllKomentarById({ const listKomentar = await forum_funGetAllKomentarById({
postingId: postingId, postingId: postingId,
page: 1, page: 1,
}); });
// dataPosting?.isActive === false && redirect(RouterForum.beranda);
const countKomentar = await forum_countTotalKomenById(postingId); const countKomentar = await forum_countTotalKomenById(postingId);
return ( return (
<> <>
<Forum_MainDetail <Forum_MainDetail
dataPosting={dataPosting as any} // dataPosting={dataPosting as any}
listKomentar={listKomentar as any} // listKomentar={listKomentar as any}
userLoginId={userLoginId as string} userLoginId={userLoginId as string}
countKomentar={countKomentar} countKomentar={countKomentar}
/> />

View File

@@ -16,24 +16,24 @@ export default function Voting_ComponentSkeletonViewPuh() {
header={<UIGlobal_LayoutHeaderTamplate title="Skeleton Maker" />} header={<UIGlobal_LayoutHeaderTamplate title="Skeleton Maker" />}
> >
<Stack> <Stack>
<Center> <Grid align="center">
<CustomSkeleton height={100} width={100} circle /> <Grid.Col span={2}>
</Center> <CustomSkeleton height={40} width={40} circle />
<Grid grow>
<Grid.Col span={6}>
<Stack spacing={"xs"}>
<CustomSkeleton height={20} width={"80%"} />
<CustomSkeleton height={20} width={"80%"} />
</Stack>
</Grid.Col> </Grid.Col>
<Grid.Col span={4}>
<Grid.Col span={6}> <CustomSkeleton height={20} width={"100%"} />
</Grid.Col>
<Grid.Col span={3} offset={3}>
<Group position="right"> <Group position="right">
<CustomSkeleton height={50} width={"80%"} radius={"xl"} /> <CustomSkeleton height={20} width={"50%"} />
</Group> </Group>
</Grid.Col> </Grid.Col>
</Grid> </Grid>
<Stack>
<CustomSkeleton height={20} width={"100%"} radius={"xl"} />
<CustomSkeleton height={20} width={"100%"} radius={"xl"} />
</Stack>
</Stack> </Stack>
{/* <Stack spacing={"xl"} p={"sm"}> {/* <Stack spacing={"xl"} p={"sm"}>

View File

@@ -1,4 +1,9 @@
export { apiGetAllForum, apiGetOneForumById, apiGetForumkuById }; export {
apiGetAllForum,
apiGetOneForumById,
apiGetForumkuByUserId as apiGetForumkuById,
apiGetKomentarForumById,
};
const apiGetAllForum = async ({ const apiGetAllForum = async ({
page, page,
@@ -72,7 +77,7 @@ const apiGetOneForumById = async ({ id }: { id: string }) => {
} }
}; };
const apiGetForumkuById = async ({ const apiGetForumkuByUserId = async ({
id, id,
page, page,
}: { }: {
@@ -111,3 +116,37 @@ const apiGetForumkuById = async ({
throw error; // Re-throw the error to handle it in the calling function throw error; // Re-throw the error to handle it in the calling function
} }
}; };
const apiGetKomentarForumById = 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 nextPage = `?page=${page}`;
const response = await fetch(`/api/forum/${id}/komentar${nextPage}`, {
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

@@ -19,16 +19,20 @@ import { MODEL_FORUM_POSTING } from "../../model/interface";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { MainColor } from "@/app_modules/_global/color/color_pallet"; import { MainColor } from "@/app_modules/_global/color/color_pallet";
import mqtt_client from "@/util/mqtt_client"; import mqtt_client from "@/util/mqtt_client";
import backendLogger from "@/util/backendLogger";
import { clientLogger } from "@/util/clientLogger";
export default function ComponentForum_DetailCreateKomentar({ export default function ComponentForum_DetailCreateKomentar({
postingId, postingId,
onSetKomentar, onSetKomentar,
data, data,
userLoginId, userLoginId,
onSetNewKomentar,
}: { }: {
postingId: string; postingId: string;
onSetKomentar: (val: any) => void; onSetKomentar: (val: any) => void;
data: MODEL_FORUM_POSTING; data: MODEL_FORUM_POSTING;
userLoginId: string; userLoginId: string;
onSetNewKomentar: (val: boolean) => void;
}) { }) {
const router = useRouter(); const router = useRouter();
const [value, setValue] = useState(""); const [value, setValue] = useState("");
@@ -40,45 +44,52 @@ export default function ComponentForum_DetailCreateKomentar({
return null; return null;
} }
const createComment = await forum_funCreateKomentar(postingId, value); try {
if (createComment.status === 201) { setLoading(true);
// const loadKomentar = await forum_funGetAllKomentarById(data.id); const createComment = await forum_funCreateKomentar(postingId, value);
if (createComment.status === 201) {
// const loadData = await forum_funGetAllKomentarById({
// postingId: data.id,
// page: 1,
// });
// onSetKomentar(loadData);
const loadData = await forum_funGetAllKomentarById({ onSetNewKomentar(true);
postingId: data.id, setValue("");
page: 1, setIsEmpty(true);
}); ComponentGlobal_NotifikasiBerhasil(createComment.message, 2000);
onSetKomentar(loadData);
setValue(""); if (userLoginId !== data.Author.id) {
setIsEmpty(true); const dataNotif = {
ComponentGlobal_NotifikasiBerhasil(createComment.message, 2000); appId: data.id,
userId: data.authorId,
pesan: value,
kategoriApp: "FORUM",
title: "Komentar baru",
};
if (userLoginId !== data.Author.id) { const createNotifikasi = await notifikasiToUser_funCreate({
const dataNotif = { data: dataNotif as any,
appId: data.id, });
userId: data.authorId,
pesan: value,
kategoriApp: "FORUM",
title: "Komentar baru",
};
const createNotifikasi = await notifikasiToUser_funCreate({ if (createNotifikasi.status === 201) {
data: dataNotif as any, mqtt_client.publish(
}); "USER",
JSON.stringify({
if (createNotifikasi.status === 201) { userId: dataNotif.userId,
mqtt_client.publish( count: 1,
"USER", })
JSON.stringify({ );
userId: dataNotif.userId, }
count: 1,
})
);
} }
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(createComment.message);
} }
} else { } catch (error) {
ComponentGlobal_NotifikasiGagal(createComment.message); setLoading(false);
clientLogger.error("Error create komentar forum", error);
} }
} }
@@ -117,8 +128,9 @@ export default function ComponentForum_DetailCreateKomentar({
} }
bg={MainColor.yellow} bg={MainColor.yellow}
color={"yellow"} color={"yellow"}
c="black"
loaderPosition="center" loaderPosition="center"
loading={loading ? true : false} loading={loading}
radius={"xl"} radius={"xl"}
onClick={() => onComment()} onClick={() => onComment()}
> >

View File

@@ -1,14 +1,9 @@
"use client"; "use client";
import { import { Card, Divider, Spoiler, Stack, Text } from "@mantine/core";
Card,
Divider,
Spoiler,
Stack,
Text
} from "@mantine/core";
import { MODEL_FORUM_KOMENTAR } from "../../model/interface"; import { MODEL_FORUM_KOMENTAR } from "../../model/interface";
import ComponentForum_KomentarAuthorNameOnHeader from "../komentar_component/komentar_author_header_name"; import ComponentForum_KomentarAuthorNameOnHeader from "../komentar_component/komentar_author_header_name";
import { ComponentGlobal_CardStyles } from "@/app_modules/_global/component";
export default function ComponentForum_KomentarView({ export default function ComponentForum_KomentarView({
data, data,
@@ -23,65 +18,34 @@ export default function ComponentForum_KomentarView({
}) { }) {
return ( return (
<> <>
<Card mb={"xs"} bg={"transparent"}> <ComponentGlobal_CardStyles>
<Card.Section> <ComponentForum_KomentarAuthorNameOnHeader
<ComponentForum_KomentarAuthorNameOnHeader tglPublish={data?.createdAt}
tglPublish={data?.createdAt} userId={data?.Author?.id}
userId={data?.Author?.id} komentarId={data?.id}
komentarId={data?.id} isMoreButton={true}
isMoreButton={true} setKomentar={setKomentar}
setKomentar={setKomentar} postingId={postingId}
postingId={postingId} userLoginId={userLoginId}
userLoginId={userLoginId} profile={data.Author.Profile}
profile={data.Author.Profile} />
/>
</Card.Section>
<Card.Section sx={{ zIndex: 0 }} p={"sm"}>
<Stack spacing={"xs"}>
<Text fz={"sm"} lineClamp={4} c={"white"}>
{data.komentar ? (
<Spoiler
hideLabel="sembunyikan"
maxHeight={100}
showLabel="tampilkan"
>
<div dangerouslySetInnerHTML={{ __html: data.komentar }} />
</Spoiler>
) : (
""
)}
</Text>
</Stack>
</Card.Section>
<Card.Section> <Stack spacing={"xs"} sx={{ zIndex: 0 }} p={"sm"}>
<Stack> <Text fz={"sm"} lineClamp={4} c={"white"}>
<Divider /> {data.komentar ? (
</Stack> <Spoiler
</Card.Section> hideLabel="sembunyikan"
</Card> maxHeight={100}
showLabel="tampilkan"
{/* <Stack> >
{_.isEmpty(data) ? ( <div dangerouslySetInnerHTML={{ __html: data.komentar }} />
<Center> </Spoiler>
<Text fw={"bold"} fz={"xs"} c={"white"}> ) : (
Belum ada komentar ""
</Text> )}
</Center> </Text>
) : ( </Stack>
<Box> </ComponentGlobal_CardStyles>
<Center>
<Text fw={"bold"} fz={"xs"} c={"white"}>
{" "}
Komentar
</Text>
</Center>
{data.map((e, i) => (
))}
</Box>
)}
</Stack> */}
</> </>
); );
} }

View File

@@ -12,6 +12,7 @@ import { ComponentGlobal_LoaderAvatar } from "@/app_modules/_global/component";
import ComponentGlobal_Loader from "@/app_modules/_global/component/loader"; import ComponentGlobal_Loader from "@/app_modules/_global/component/loader";
import { data } from "autoprefixer"; import { data } from "autoprefixer";
import { MODEL_PROFILE } from "@/app_modules/katalog/profile/model/interface"; import { MODEL_PROFILE } from "@/app_modules/katalog/profile/model/interface";
import moment from "moment";
export default function ComponentForum_KomentarAuthorNameOnHeader({ export default function ComponentForum_KomentarAuthorNameOnHeader({
userId, userId,
@@ -84,10 +85,11 @@ export default function ComponentForum_KomentarAuthorNameOnHeader({
<Group spacing={3}> <Group spacing={3}>
<Text c={"white"} fz={"sm"}> <Text c={"white"} fz={"sm"}>
{tglPublish {tglPublish
? tglPublish.toLocaleDateString(["id-ID"], { ? new Intl.DateTimeFormat("id-ID", {
day: "numeric", day: "numeric",
month: "short", month: "short",
}) year: "numeric",
}).format(new Date(tglPublish))
: new Date().toLocaleDateString(["id-ID"], { : new Date().toLocaleDateString(["id-ID"], {
day: "numeric", day: "numeric",
month: "short", month: "short",

View File

@@ -1,7 +1,12 @@
import CustomSkeleton from "@/app_modules/components/CustomSkeleton"; import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { Center, Grid, Group, Stack } from "@mantine/core"; import { Center, Grid, Group, Stack } from "@mantine/core";
export { Forum_SkeletonCard, Forum_SkeletonForumku }; export {
Forum_SkeletonCard,
Forum_SkeletonForumku,
Forum_SkeletonKomentar,
Forum_SkeletonListKomentar,
};
function Forum_SkeletonCard() { function Forum_SkeletonCard() {
return ( return (
@@ -14,7 +19,7 @@ function Forum_SkeletonCard() {
); );
} }
function Forum_SkeletonForumku(){ function Forum_SkeletonForumku() {
return ( return (
<> <>
<Stack spacing={"xl"}> <Stack spacing={"xl"}>
@@ -40,3 +45,29 @@ function Forum_SkeletonForumku(){
</> </>
); );
} }
function Forum_SkeletonKomentar() {
return (
<>
<Stack mt={"lg"}>
<CustomSkeleton height={50} />
<Group position="apart">
<CustomSkeleton height={15} width={"20%"} radius={"xl"} />
<CustomSkeleton height={40} width={"30%"} radius={"xl"} />
</Group>
</Stack>
</>
);
}
function Forum_SkeletonListKomentar() {
return (
<>
<Stack>
{Array.from(new Array(2)).map((e, i) => (
<CustomSkeleton key={i} height={100} />
))}
</Stack>
</>
);
}

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { Box, Center, Loader, Stack, TextInput } from "@mantine/core"; import { Box, Center, Group, Loader, Stack, TextInput } from "@mantine/core";
import _ from "lodash"; import _ from "lodash";
import { MODEL_FORUM_KOMENTAR, MODEL_FORUM_POSTING } from "../model/interface"; import { MODEL_FORUM_KOMENTAR, MODEL_FORUM_POSTING } from "../model/interface";
import mqtt_client from "@/util/mqtt_client"; import mqtt_client from "@/util/mqtt_client";
@@ -12,41 +12,99 @@ import ComponentForum_KomentarView from "../component/detail_component/detail_li
import ComponentForum_DetailForumView from "../component/detail_component/detail_view"; import ComponentForum_DetailForumView from "../component/detail_component/detail_view";
import { ScrollOnly } from "next-scroll-loader"; import { ScrollOnly } from "next-scroll-loader";
import { forum_funGetAllKomentarById } from "../fun/get/get_all_komentar_by_id"; import { forum_funGetAllKomentarById } from "../fun/get/get_all_komentar_by_id";
import {
apiGetKomentarForumById,
apiGetOneForumById,
} from "../component/api_fetch_forum";
import { useParams } from "next/navigation";
import { clientLogger } from "@/util/clientLogger";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import {
Forum_SkeletonKomentar,
Forum_SkeletonListKomentar,
} from "../component/skeleton_view";
import ComponentGlobal_IsEmptyData from "@/app_modules/_global/component/is_empty_data";
export default function Forum_MainDetail({ export default function Forum_MainDetail({
dataPosting,
listKomentar,
userLoginId, userLoginId,
countKomentar, countKomentar,
}: { }: {
dataPosting: MODEL_FORUM_POSTING;
listKomentar: MODEL_FORUM_KOMENTAR[];
userLoginId: string; userLoginId: string;
countKomentar: number; countKomentar: number;
}) { }) {
const [data, setData] = useState(dataPosting); const param = useParams<{ id: string }>();
const [lsKomentar, setLsKomentar] = useState(listKomentar); const [data, setData] = useState<MODEL_FORUM_POSTING | null>(null);
const [lsKomentar, setLsKomentar] = useState<MODEL_FORUM_KOMENTAR[]>([]);
const [activePage, setActivePage] = useState(1); const [activePage, setActivePage] = useState(1);
const [newKomentar, setNewKomentar] = useState(false);
// useShallowEffect(() => { useShallowEffect(() => {
// onLoadKomentar({ handleLoadData();
// onLoad(val) { }, []);
// setKomentar(val);
// },
// });
// }, [setKomentar]);
// async function onLoadKomentar({ onLoad }: { onLoad: (val: any) => void }) { const handleLoadData = async () => {
// const loadKomentar = await forum_getKomentarById(data.id); try {
// onLoad(loadKomentar); const response = await apiGetOneForumById({
// } id: param.id,
});
if (response) {
setData(response.data);
}
} catch (error) {
clientLogger.error("Error get data forum", error);
setData(null);
}
};
useShallowEffect(() => {
handleLoadDataKomentar();
}, [newKomentar]);
const handleLoadDataKomentar = async () => {
try {
const response = await apiGetKomentarForumById({
id: param.id,
page: `${activePage}`,
});
if (response.success) {
setLsKomentar(response.data);
} else {
setLsKomentar([]);
}
} catch (error) {
clientLogger.error("Error get data komentar forum", error);
setLsKomentar([]);
}
};
const handleMoreDataKomentar = async () => {
try {
const nextPage = activePage + 1;
const response = await apiGetKomentarForumById({
id: param.id,
page: `${nextPage}`,
});
if (response.success) {
setActivePage(nextPage);
return response.data;
} else {
return null;
}
} catch (error) {
clientLogger.error("Error get data komentar forum", error);
return null;
}
};
useShallowEffect(() => { useShallowEffect(() => {
mqtt_client.subscribe("Forum_detail_ganti_status"); mqtt_client.subscribe("Forum_detail_ganti_status");
mqtt_client.on("message", (topic: any, message: any) => { mqtt_client.on("message", (topic: any, message: any) => {
const newData = JSON.parse(message.toString()); const newData = JSON.parse(message.toString());
if (newData.id === data.id) { if (newData.id === data?.id) {
const cloneData = _.clone(data); const cloneData = _.clone(data);
// console.log(newData.data); // console.log(newData.data);
@@ -66,58 +124,65 @@ export default function Forum_MainDetail({
return ( return (
<> <>
<Stack> <Stack>
<ComponentForum_DetailForumView {!data ? (
data={data} <CustomSkeleton height={200} width={"100%"} />
totalKomentar={countKomentar}
userLoginId={userLoginId}
onLoadData={(val) => {
setData(val);
}}
/>
{(data?.ForumMaster_StatusPosting?.id as any) === 1 ? (
<ComponentForum_DetailCreateKomentar
postingId={dataPosting?.id}
onSetKomentar={(val) => {
setLsKomentar(val);
}}
data={data}
userLoginId={userLoginId}
/>
) : ( ) : (
"" <ComponentForum_DetailForumView
data={data}
totalKomentar={countKomentar}
userLoginId={userLoginId}
onLoadData={(val) => {
setData(val);
}}
/>
)} )}
<Box> {!data ? (
<ScrollOnly <Forum_SkeletonKomentar />
height={"60vh"} ) : (
renderLoading={() => ( (data?.ForumMaster_StatusPosting?.id as any) === 1 && (
<Center mt={"lg"}> <ComponentForum_DetailCreateKomentar
<Loader color={"yellow"} /> postingId={data?.id}
</Center> onSetKomentar={(val) => {
)} setLsKomentar(val);
data={lsKomentar} }}
setData={setLsKomentar} data={data}
moreData={async () => { userLoginId={userLoginId}
const loadData = await forum_funGetAllKomentarById({ onSetNewKomentar={(val) => {
postingId: data.id, setNewKomentar(val);
page: activePage + 1, }}
}); />
setActivePage((val) => val + 1); )
)}
return loadData; {!lsKomentar.length ? (
}} <Forum_SkeletonListKomentar />
> ) : _.isEmpty(lsKomentar) ? (
{(item) => ( <ComponentGlobal_IsEmptyData />
<ComponentForum_KomentarView ) : (
data={item} <Box >
setKomentar={setLsKomentar} <ScrollOnly
postingId={data?.id} height={"60vh"}
userLoginId={userLoginId} renderLoading={() => (
/> <Center mt={"lg"}>
)} <Loader color={"yellow"} />
</ScrollOnly> </Center>
</Box> )}
data={lsKomentar}
setData={setLsKomentar}
moreData={handleMoreDataKomentar}
>
{(item) => (
<ComponentForum_KomentarView
data={item}
setKomentar={setLsKomentar}
postingId={data?.id as any}
userLoginId={userLoginId}
/>
)}
</ScrollOnly>
</Box>
)}
</Stack> </Stack>
</> </>
); );

View File

@@ -31,6 +31,7 @@ const middlewareConfig: MiddlewareConfig = {
"/api/auth/*", "/api/auth/*",
"/api/origin-url", "/api/origin-url",
"/api/event/*", "/api/event/*",
"/api/forum/*",
// ADMIN API // ADMIN API
// >> buat dibawah sini << // >> buat dibawah sini <<