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,16 +44,17 @@ export default function ComponentForum_DetailCreateKomentar({
return null; return null;
} }
try {
setLoading(true);
const createComment = await forum_funCreateKomentar(postingId, value); const createComment = await forum_funCreateKomentar(postingId, value);
if (createComment.status === 201) { if (createComment.status === 201) {
// const loadKomentar = await forum_funGetAllKomentarById(data.id); // const loadData = await forum_funGetAllKomentarById({
// postingId: data.id,
const loadData = await forum_funGetAllKomentarById({ // page: 1,
postingId: data.id, // });
page: 1, // onSetKomentar(loadData);
});
onSetKomentar(loadData);
onSetNewKomentar(true);
setValue(""); setValue("");
setIsEmpty(true); setIsEmpty(true);
ComponentGlobal_NotifikasiBerhasil(createComment.message, 2000); ComponentGlobal_NotifikasiBerhasil(createComment.message, 2000);
@@ -78,8 +83,14 @@ export default function ComponentForum_DetailCreateKomentar({
} }
} }
} else { } else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(createComment.message); ComponentGlobal_NotifikasiGagal(createComment.message);
} }
} catch (error) {
setLoading(false);
clientLogger.error("Error create komentar forum", error);
}
} }
return ( return (
@@ -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,8 +18,7 @@ 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}
@@ -35,9 +29,8 @@ export default function ComponentForum_KomentarView({
userLoginId={userLoginId} userLoginId={userLoginId}
profile={data.Author.Profile} profile={data.Author.Profile}
/> />
</Card.Section>
<Card.Section sx={{ zIndex: 0 }} p={"sm"}> <Stack spacing={"xs"} sx={{ zIndex: 0 }} p={"sm"}>
<Stack spacing={"xs"}>
<Text fz={"sm"} lineClamp={4} c={"white"}> <Text fz={"sm"} lineClamp={4} c={"white"}>
{data.komentar ? ( {data.komentar ? (
<Spoiler <Spoiler
@@ -52,36 +45,7 @@ export default function ComponentForum_KomentarView({
)} )}
</Text> </Text>
</Stack> </Stack>
</Card.Section> </ComponentGlobal_CardStyles>
<Card.Section>
<Stack>
<Divider />
</Stack>
</Card.Section>
</Card>
{/* <Stack>
{_.isEmpty(data) ? (
<Center>
<Text fw={"bold"} fz={"xs"} c={"white"}>
Belum ada komentar
</Text>
</Center>
) : (
<Box>
<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 (
@@ -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,6 +124,9 @@ export default function Forum_MainDetail({
return ( return (
<> <>
<Stack> <Stack>
{!data ? (
<CustomSkeleton height={200} width={"100%"} />
) : (
<ComponentForum_DetailForumView <ComponentForum_DetailForumView
data={data} data={data}
totalKomentar={countKomentar} totalKomentar={countKomentar}
@@ -74,20 +135,31 @@ export default function Forum_MainDetail({
setData(val); setData(val);
}} }}
/> />
)}
{(data?.ForumMaster_StatusPosting?.id as any) === 1 ? ( {!data ? (
<Forum_SkeletonKomentar />
) : (
(data?.ForumMaster_StatusPosting?.id as any) === 1 && (
<ComponentForum_DetailCreateKomentar <ComponentForum_DetailCreateKomentar
postingId={dataPosting?.id} postingId={data?.id}
onSetKomentar={(val) => { onSetKomentar={(val) => {
setLsKomentar(val); setLsKomentar(val);
}} }}
data={data} data={data}
userLoginId={userLoginId} userLoginId={userLoginId}
onSetNewKomentar={(val) => {
setNewKomentar(val);
}}
/> />
) : ( )
""
)} )}
{!lsKomentar.length ? (
<Forum_SkeletonListKomentar />
) : _.isEmpty(lsKomentar) ? (
<ComponentGlobal_IsEmptyData />
) : (
<Box > <Box >
<ScrollOnly <ScrollOnly
height={"60vh"} height={"60vh"}
@@ -98,26 +170,19 @@ export default function Forum_MainDetail({
)} )}
data={lsKomentar} data={lsKomentar}
setData={setLsKomentar} setData={setLsKomentar}
moreData={async () => { moreData={handleMoreDataKomentar}
const loadData = await forum_funGetAllKomentarById({
postingId: data.id,
page: activePage + 1,
});
setActivePage((val) => val + 1);
return loadData;
}}
> >
{(item) => ( {(item) => (
<ComponentForum_KomentarView <ComponentForum_KomentarView
data={item} data={item}
setKomentar={setLsKomentar} setKomentar={setLsKomentar}
postingId={data?.id} postingId={data?.id as any}
userLoginId={userLoginId} userLoginId={userLoginId}
/> />
)} )}
</ScrollOnly> </ScrollOnly>
</Box> </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 <<