fix: collaboration

deskripsi:
- fix use server menjadi API
- di terapkan pada main detail , room chat
This commit is contained in:
2025-05-27 17:12:38 +08:00
parent e4b55fd201
commit bdff760f70
10 changed files with 981 additions and 44 deletions

View File

@@ -0,0 +1,69 @@
import _ from "lodash";
import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import backendLogger from "@/util/backendLogger";
export { GET };
async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const roomId = params.id;
const { searchParams } = new URL(request.url);
const page = searchParams.get("page");
const takeData = 10;
const dataSkip = Number(page) * takeData - takeData;
const getList = await prisma.projectCollaboration_Message.findMany({
orderBy: {
createdAt: "desc",
},
skip: dataSkip,
take: takeData,
where: {
projectCollaboration_RoomChatId: roomId,
},
select: {
id: true,
createdAt: true,
isActive: true,
message: true,
isFile: true,
User: {
select: {
id: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
},
});
const dataReverse = _.reverse(getList);
return NextResponse.json(
{
success: true,
message: "Berhasil mendapatkan data",
data: dataReverse,
},
{ status: 200 }
);
} catch (error) {
console.error("Error get message by room id", error);
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan data",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,68 @@
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const roomId = params.id;
const getData = await prisma.projectCollaboration_RoomChat.findUnique({
where: {
id: roomId,
},
select: {
id: true,
name: true,
ProjectCollaboration: {
select: {
id: true,
isActive: true,
title: true,
lokasi: true,
purpose: true,
benefit: true,
createdAt: true,
ProjectCollaborationMaster_Industri: true,
Author: true,
},
},
ProjectCollaboration_AnggotaRoomChat: {
select: {
User: {
select: {
username: true,
id: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
},
},
},
});
return NextResponse.json(
{
success: true,
message: "Berhasil mendapatkan data",
data: getData,
},
{ status: 200 }
);
} catch (error) {
console.error("Error get room by id", error);
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan data",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,198 @@
// components/ChatWindow.tsx
import {
Box,
Button,
Flex,
ScrollArea,
Text,
TextInput
} from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import React, { useRef, useState } from "react";
interface Message {
id: string;
content: string;
senderId: string;
createdAt: Date;
}
// components/ChatWindow.tsx
type Props = {
initialMessages: Message[];
currentUserId: string;
loadMoreMessages: () => Promise<Message[]>;
sendMessage: (content: string) => Promise<void>;
};
const ChatWindow: React.FC<Props> = ({
initialMessages,
currentUserId,
loadMoreMessages,
sendMessage,
}) => {
const [messages, setMessages] = useState<Message[]>(initialMessages);
const [newMessage, setNewMessage] = useState("");
const scrollAreaRef = useRef<HTMLDivElement>(null);
const messageContainerRef = useRef<HTMLDivElement>(null);
const [showNewMessageIndicator, setShowNewMessageIndicator] = useState(false);
const [isAtBottom, setIsAtBottom] = useState(true);
// Cek apakah scroll berada di bawah
const checkIfAtBottom = () => {
if (!scrollAreaRef.current || !messageContainerRef.current) return true;
const container = scrollAreaRef.current;
const offsetBottom =
messageContainerRef.current.clientHeight -
container.clientHeight -
container.scrollTop;
return offsetBottom < 50; // toleransi 50px
};
// Scroll ke bawah
const scrollToBottom = () => {
if (messageContainerRef.current && scrollAreaRef.current) {
scrollAreaRef.current.scrollTop =
messageContainerRef.current.clientHeight -
scrollAreaRef.current.clientHeight;
}
};
// Handle infinite scroll up
const handleScroll = async () => {
if (!scrollAreaRef.current) return;
const { scrollTop } = scrollAreaRef.current;
if (scrollTop === 0) {
const newMessages = await loadMoreMessages();
setMessages((prev) => [...newMessages, ...prev]);
}
// Cek apakah user di bottom
const atBottom = checkIfAtBottom();
setIsAtBottom(atBottom);
setShowNewMessageIndicator(!atBottom);
};
// Kirim pesan
const handleSendMessage = async () => {
if (!newMessage.trim()) return;
// Simpan pesan baru ke state
const tempMessage: Message = {
id: Math.random().toString(36).substr(2, 9),
content: newMessage,
senderId: currentUserId,
createdAt: new Date(),
};
setMessages((prev) => [...prev, tempMessage]);
// Reset input
setNewMessage("");
// Kirim ke server
await sendMessage(newMessage);
// Jika user di bawah, scroll otomatis
if (checkIfAtBottom()) {
scrollToBottom();
}
};
// Scroll otomatis saat komponen pertama kali di-render
useShallowEffect(() => {
scrollToBottom();
}, []);
// Tambah event listener scroll
useShallowEffect(() => {
const scrollArea = scrollAreaRef.current;
if (!scrollArea) return;
scrollArea.addEventListener("scroll", handleScroll);
return () => {
scrollArea.removeEventListener("scroll", handleScroll);
};
}, []);
// Scroll otomatis jika user di bottom dan ada pesan baru
useShallowEffect(() => {
if (isAtBottom) {
scrollToBottom();
}
}, [messages.length]);
return (
<Box h="100%" display="flex" style={{ flexDirection: "column" }}>
{/* Area Chat */}
<ScrollArea
ref={scrollAreaRef}
style={{ flex: 1, position: "relative" }}
onScrollPositionChange={() => {}}
>
<div ref={messageContainerRef}>
{messages.map((msg) => (
<Box
key={msg.id}
p="sm"
style={{
textAlign: msg.senderId === currentUserId ? "right" : "left",
}}
>
<Text
bg={msg.senderId === currentUserId ? "blue" : "gray"}
c="white"
px="md"
py="xs"
// radius="lg"
display="inline-block"
>
{msg.content}
</Text>
</Box>
))}
</div>
</ScrollArea>
{/* Notifikasi Pesan Baru */}
{!isAtBottom && showNewMessageIndicator && (
<Button
onClick={() => {
scrollToBottom();
setShowNewMessageIndicator(false);
}}
color="blue"
style={{
position: "absolute",
bottom: 80,
left: "50%",
transform: "translateX(-50%)",
}}
>
Ada pesan baru
</Button>
)}
{/* Input Pengiriman */}
<Flex gap="sm" p="md" align="center">
<TextInput
value={newMessage}
onChange={(e) => setNewMessage(e.currentTarget.value)}
placeholder="Ketik pesan..."
onKeyDown={(e) => e.key === "Enter" && handleSendMessage()}
// flex={1}
style={{
flex: 1,
}}
/>
<Button onClick={handleSendMessage}>Kirim</Button>
</Flex>
</Box>
);
};
export default ChatWindow;

View File

@@ -0,0 +1,83 @@
// app/chat/[id]/page.tsx
"use client";
import React, { useState, useCallback } from "react";
import ChatWindow from "./chat_window";
import { useShallowEffect } from "@mantine/hooks";
interface Message {
id: string;
content: string;
senderId: string;
createdAt: Date;
}
type Props = {
params: {
id: string;
};
};
export default function ChatPage({ params }: Props) {
const chatId = params.id;
const currentUserId = "user_123"; // Ganti dengan dynamic user ID dari auth
const [messages, setMessages] = useState<Message[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(true);
// Load initial messages
const loadInitialMessages = useCallback(async () => {
const res = await fetch(`/api/messages?chatId=${chatId}`);
const data = await res.json();
if (data.length > 0) {
setCursor(data[0]?.id); // Simpan cursor dari pesan pertama
} else {
setHasMore(false);
}
setMessages(data);
}, [chatId]);
// Load more messages (scroll up)
const loadMoreMessages = useCallback(async () => {
if (!hasMore || !cursor) return [];
const res = await fetch(`/api/messages?chatId=${chatId}&cursor=${cursor}`);
const data = await res.json();
if (data.length < 20) setHasMore(false);
if (data.length > 0) setCursor(data[0]?.id);
setMessages((prev) => [...data, ...prev]);
return data;
}, [chatId, cursor, hasMore]);
// Send message
const sendMessage = useCallback(
async (content: string) => {
await fetch("/api/messages", {
method: "POST",
body: JSON.stringify({
content,
senderId: currentUserId,
chatId,
}),
});
},
[chatId, currentUserId]
);
// Load pesan saat pertama kali
useShallowEffect(() => {
loadInitialMessages();
}, [loadInitialMessages]);
return (
<ChatWindow
initialMessages={messages}
currentUserId={currentUserId}
loadMoreMessages={loadMoreMessages}
sendMessage={sendMessage}
/>
);
}

View File

@@ -1,15 +1,16 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import adminColab_getOneRoomChatById from "@/app_modules/admin/colab/fun/get/get_one_room_chat_by_id";
import { Colab_GroupChatView } from "@/app_modules/colab";
import Colab_NewGroupChatView from "@/app_modules/colab/detail/group/new_detail_group";
import colab_getMessageByRoomId from "@/app_modules/colab/fun/get/room_chat/get_message_by_room_id";
import { user_getOneByUserId } from "@/app_modules/home/fun/get/get_one_user_by_id";
import _ from "lodash";
export const dynamic = "force-dynamic";
export default async function Page({ params }: { params: { id: string } }) {
const roomId = params.id;
const userLoginId = await funGetUserIdByToken();
// const userLoginId = await funGetUserIdByToken();
// const dataUserLogin = await user_getOneByUserId(userLoginId as string);
const getData = (await adminColab_getOneRoomChatById({ roomId: roomId }))
.data;
@@ -18,26 +19,18 @@ export default async function Page({ params }: { params: { id: string } }) {
"ProjectCollaboration_AnggotaRoomChat",
]);
let listMsg = await colab_getMessageByRoomId({ roomId: roomId, page: 1 });
const dataUserLogin = await user_getOneByUserId(userLoginId as string);
return (
<>
{/* <Colab_DetailGrupDiskusi
userLoginId={userLoginId}
listMsg={listMsg}
selectRoom={dataRoom as any}
dataUserLogin={dataUserLogin as any}
roomId={roomId}
/> */}
<Colab_GroupChatView
{/* <Colab_GroupChatView
userLoginId={userLoginId as string}
listMsg={listMsg}
selectRoom={dataRoom as any}
dataUserLogin={dataUserLogin as any}
/>
/> */}
<Colab_NewGroupChatView selectRoom={dataRoom as any} listMsg={listMsg} />
</>
);
}

View File

@@ -1,14 +1,9 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { Colab_MainDetail } from "@/app_modules/colab";
export default async function Page() {
const userLoginId = await funGetUserIdByToken();
return (
<>
<Colab_MainDetail
userLoginId={userLoginId as string}
/>
<Colab_MainDetail />
</>
);
}

View File

@@ -110,3 +110,80 @@ export const apiGetMasterIndustri = async () => {
throw error;
}
};
export const apiCollaborationGetMessageByRoomId = 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 response = await fetch(
`/api/collaboration/${id}/message?page=${page}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Error get message by room id:",
response.statusText,
errorData
);
throw new Error(errorData?.message || "Failed to get message by room id");
}
return await response.json();
} catch (error) {
console.error("Error get message by room id:", error);
throw error;
}
};
export const apiCollaborationGetRoomById = async ({
id,
}: {
id: 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 response = await fetch(`/api/collaboration/${id}/room`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Error get room by id:",
response.statusText,
errorData
);
throw new Error(errorData?.message || "Failed to get room by id");
}
return await response.json();
} catch (error) {
console.error("Error get room by id:", error);
throw error;
}
};

View File

@@ -0,0 +1,442 @@
"use client";
import { RouterColab } from "@/lib/router_hipmi/router_colab";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { MODEL_USER } from "@/app_modules/home/model/interface";
import mqtt_client from "@/util/mqtt_client";
import {
ActionIcon,
Box,
Center,
Container,
Grid,
Group,
Loader,
Paper,
rem,
Stack,
Text,
Textarea,
Title,
} from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import {
IconChevronLeft,
IconCircle,
IconInfoSquareRounded,
IconSend,
} from "@tabler/icons-react";
import _ from "lodash";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import useInfiniteScroll, {
ScrollDirection,
} from "react-easy-infinite-scroll-hook";
import ComponentColab_IsEmptyData from "../../component/is_empty_data";
import colab_funCreateMessageByUserId from "../../fun/create/room/fun_create_message_by_user_id";
import colab_getMessageByRoomId from "../../fun/get/room_chat/get_message_by_room_id";
import {
MODEL_COLLABORATION_MESSAGE,
MODEL_COLLABORATION_ROOM_CHAT,
} from "../../model/interface";
import {
AccentColor,
MainColor,
} from "@/app_modules/_global/color/color_pallet";
import ComponentGlobal_Loader from "@/app_modules/_global/component/loader";
import { apiGetDataGroupById } from "../../_lib/api_collaboration";
import { clientLogger } from "@/util/clientLogger";
import { apiNewGetUserIdByToken } from "@/app_modules/_global/lib/api_fetch_global";
import { apiGetUserById } from "@/app_modules/_global/lib/api_user";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import moment from "moment";
import "moment/locale/id";
export default function Colab_NewGroupChatView({
listMsg,
selectRoom,
}: {
listMsg: any;
selectRoom: MODEL_COLLABORATION_ROOM_CHAT;
}) {
const params = useParams<{ id: string }>();
const router = useRouter();
const [loadingBack, setLoadingBack] = useState(false);
const [loadingInfo, setLoadingInfo] = useState(false);
const [msg, setMsg] = useState("");
const [newMessage, setNewMessage] = useState<any>();
const [data, setData] = useState<any[]>(listMsg);
const [totalPage, setTotalPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [isGet, setIsGet] = useState(true);
const [newMessageId, setIdMessage] = useState("");
const [dataGroup, setDataGroup] =
useState<MODEL_COLLABORATION_ROOM_CHAT | null>(null);
const [userLoginId, setUserLoginId] = useState<string | null>();
const [dataUserLogin, setDataUserLogin] = useState<MODEL_USER | null>(null);
async function handleDataUserLogin() {
try {
const response = await apiNewGetUserIdByToken();
if (response.success) {
setUserLoginId(response.userId);
const respone = await apiGetUserById({ id: response.userId });
if (respone) {
setDataUserLogin(respone.data);
}
} else {
setUserLoginId(null);
setDataUserLogin(null);
}
} catch (error) {
clientLogger.error("Error get data user login", error);
}
}
useShallowEffect(() => {
onLoadDataGroup();
handleDataUserLogin();
}, []);
async function onLoadDataGroup() {
try {
const respone = await apiGetDataGroupById({
id: params.id,
kategori: "detail",
});
if (respone) {
setDataGroup(respone.data);
}
} catch (error) {
clientLogger.error("Error get data group", error);
}
}
const next = async (direction: ScrollDirection) => {
try {
setIsLoading(true);
await new Promise((a) => setTimeout(a, 500));
const newData = await colab_getMessageByRoomId({
roomId: selectRoom?.id,
page: totalPage + 1,
});
setTotalPage(totalPage + 1);
// console.log(newData, "loading baru");
if (_.isEmpty(newData)) {
setIsGet(false);
} else {
const d =
direction === "down" ? [...data, ...newData] : [...newData, ...data];
setData(d);
}
} finally {
setIsLoading(false);
}
};
const ref = useInfiniteScroll({
next,
rowCount: data.length,
hasMore: { up: isGet },
scrollThreshold: 0.5,
});
async function onSend() {
await colab_funCreateMessageByUserId(msg, selectRoom.id).then(
async (res) => {
if (res.status === 200) {
setIdMessage(res.data?.id as any);
setMsg("");
const kiriman: MODEL_COLLABORATION_MESSAGE = {
createdAt: new Date(),
id: newMessageId,
isActive: true,
message: msg,
isFile: false,
updatedAt: new Date(),
userId: dataUserLogin?.id as string,
User: {
id: dataUserLogin?.id as string,
Profile: {
id: dataUserLogin?.Profile?.id as any,
name: dataUserLogin?.Profile?.name as any,
},
},
};
mqtt_client.publish(selectRoom.id, JSON.stringify(kiriman));
} else {
ComponentGlobal_NotifikasiGagal(res.message);
}
}
);
}
useShallowEffect(() => {
mqtt_client.subscribe(selectRoom.id);
// mqtt_client.on("message", (topic: any, message: any) => {
// onList(message.toString());
// });
mqtt_client.on("message", (topic: any, message: any) => {
let dd = _.clone(data);
const a = [...dd, JSON.parse(message)];
// console.log(dd.length);
setData(a);
});
}, [data]);
async function onList(message: any) {
const kiriman: MODEL_COLLABORATION_MESSAGE = {
createdAt: new Date(),
id: newMessageId,
isActive: true,
message: message,
isFile: false,
updatedAt: new Date(),
userId: dataUserLogin?.id as string,
User: {
id: dataUserLogin?.id as string,
Profile: {
id: dataUserLogin?.Profile?.id as any,
name: dataUserLogin?.Profile?.name as any,
},
},
};
const dataLama = _.clone(data);
setData([...dataLama, { ...kiriman }]);
}
return (
<>
<Box
w={"100%"}
h={"100%"}
style={{
overflowY: "auto",
overflowX: "auto",
backgroundColor: MainColor.black,
position: "fixed",
}}
>
<Container mih={"100vh"} p={0} size={rem(500)} bg={MainColor.darkblue}>
{/* Header */}
<Box
h={"8vh"}
style={{
zIndex: 10,
borderBottom: `2px solid ${MainColor.soft_darkblue}`,
borderBottomLeftRadius: "20px",
borderBottomRightRadius: "20px",
}}
w={"100%"}
pos={"sticky"}
top={0}
bg={MainColor.darkblue}
>
<Stack h={"100%"} justify="center" px={"sm"}>
<Grid grow gutter={"lg"} align="center">
<Grid.Col span={2}>
<ActionIcon
variant="transparent"
radius={"xl"}
onClick={() => {
setLoadingBack(true);
router.back();
}}
>
{loadingBack ? (
<ComponentGlobal_Loader />
) : (
<IconChevronLeft color={MainColor.white} />
)}
</ActionIcon>
</Grid.Col>
<Grid.Col span={8}>
<Center>
<Title color={MainColor.white} order={5} lineClamp={1}>
{selectRoom?.name}
</Title>
</Center>
</Grid.Col>
<Grid.Col span={2}>
<Group position="right">
<ActionIcon
variant="transparent"
radius={"xl"}
onClick={() => {
setLoadingInfo(true);
router.push(RouterColab.info_grup + selectRoom.id, {
scroll: false,
});
}}
>
{loadingInfo ? (
<ComponentGlobal_Loader />
) : (
<IconInfoSquareRounded color={MainColor.white} />
)}
</ActionIcon>
</Group>
</Grid.Col>
</Grid>
</Stack>
</Box>
{/* Main View */}
<Box
py={"xs"}
px={"xs"}
pos={"static"}
style={{ zIndex: 0 }}
h={"82vh"}
>
{/* Chat View */}
<Box h={"100%"}>
<Stack justify="flex-end" h={"100%"}>
<div
ref={ref as any}
style={{
overflowY: "auto",
}}
>
{_.isEmpty(data) ? (
<ComponentColab_IsEmptyData text="Belum ada pesan" />
) : isLoading || !dataUserLogin ? (
<Center>
<Loader size={20} color="yellow" />
</Center>
) : (
data.map((e, i) => (
<Box key={i}>
{userLoginId === e?.User?.id ? (
<Group position="right" ml={"lg"}>
<Paper key={e?.id} bg={"blue.3"} p={5} mt={"sm"}>
<Stack spacing={"xs"}>
<Text lineClamp={1} fw={"bold"} fz={"xs"}>
{e?.User?.Profile?.name}
</Text>
<Paper p={5} bg={"blue.2"}>
<div
dangerouslySetInnerHTML={{
__html: e?.message,
}}
/>
</Paper>
<Group spacing={"xs"}>
<Text fz={7}>
{moment(e.createdAt).format("ll")}
</Text>
<IconCircle size={3} />
<Text fz={7}>
{moment(e.createdAt).format("LT")}
</Text>
</Group>
</Stack>
</Paper>
</Group>
) : (
<Group mr={"lg"}>
<Paper key={e?.id} bg={"cyan.3"} p={5} mt={"sm"}>
<Stack spacing={"xs"}>
<Text lineClamp={1} fw={"bold"} fz={"xs"}>
{e?.User?.Profile?.name}
</Text>
<Paper p={5} bg={"cyan.2"}>
<div
dangerouslySetInnerHTML={{
__html: e?.message,
}}
/>
</Paper>
<Group spacing={"xs"}>
<Text fz={7}>
{moment(e.createdAt).format("ll")}
</Text>
<IconCircle size={3} />
<Text fz={7}>
{moment(e.createdAt).format("LT")}
</Text>
</Group>
</Stack>
</Paper>
</Group>
)}
</Box>
))
)}
</div>
</Stack>
</Box>
</Box>
{/* Footer */}
<Box
style={{
position: "relative",
bottom: 0,
height: "10vh",
zIndex: 10,
// borderRadius: "20px 20px 0px 0px",
borderTop: `2px solid ${AccentColor.blue}`,
borderRight: `1px solid ${AccentColor.blue}`,
borderLeft: `1px solid ${AccentColor.blue}`,
}}
bg={AccentColor.darkblue}
>
{/* <Button
onClick={() => {
const d: { [key: string]: any } = _.clone(data[0]);
setData([...data, d]);
}}
>
KIzRIM PESAN
</Button> */}
<Stack justify="center" h={"100%"} px={"sm"}>
<Grid align="center">
<Grid.Col span={"auto"}>
<Textarea
styles={{ input: { backgroundColor: MainColor.white } }}
minRows={1}
radius={"md"}
placeholder="Ketik pesan anda..."
value={msg}
onChange={(val) => setMsg(val.currentTarget.value)}
/>
</Grid.Col>
<Grid.Col span={"content"}>
<ActionIcon
disabled={msg === "" ? true : false}
variant="filled"
styles={{
root: {
backgroundColor: MainColor.white,
},
}}
color={MainColor.darkblue}
radius={"xl"}
size={"xl"}
onClick={() => {
onSend();
}}
style={{
transition: "0.5s",
}}
>
<IconSend size={20} />
</ActionIcon>
</Grid.Col>
</Grid>
</Stack>
</Box>
</Container>
</Box>
</>
);
}

View File

@@ -1,6 +1,9 @@
"use client";
import { ComponentGlobal_CardStyles } from "@/app_modules/_global/component";
import {
ComponentGlobal_BoxInformation,
ComponentGlobal_CardStyles,
} from "@/app_modules/_global/component";
import { clientLogger } from "@/util/clientLogger";
import { Stack } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
@@ -13,14 +16,13 @@ import ComponentColab_DetailListPartisipasiUser from "../../component/detail/lis
import ComponentColab_AuthorNameOnHeader from "../../component/header_author_name";
import { Collaboration_SkeletonDetail } from "../../component/skeleton_view";
import { MODEL_COLLABORATION } from "../../model/interface";
import { apiNewGetUserIdByToken } from "@/app_modules/_global/lib/api_fetch_global";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Colab_MainDetail({
userLoginId,
}: {
userLoginId?: string;
}) {
export default function Colab_MainDetail() {
const params = useParams<{ id: string }>();
const [data, setData] = useState<MODEL_COLLABORATION | null>(null);
const [userLoginId, setUserLoginId] = useState<string | null>();
useShallowEffect(() => {
onLoadData();
@@ -28,25 +30,35 @@ export default function Colab_MainDetail({
async function onLoadData() {
try {
const respone = await apiGetOneCollaborationById({
id: params.id,
kategori: "detail",
});
const response = await apiNewGetUserIdByToken();
if (respone) {
setData(respone.data);
if (response.success) {
setUserLoginId(response.userId);
const respone = await apiGetOneCollaborationById({
id: params.id,
kategori: "detail",
});
if (respone) {
setData(respone.data);
}
} else {
setUserLoginId(null);
}
} catch (error) {
clientLogger.error("Error get all collaboration", error);
}
}
if (userLoginId === undefined || data === null)
return <Collaboration_SkeletonDetail />;
return (
<>
<Stack>
{_.isNull(data) ? (
<Collaboration_SkeletonDetail />
) : (
{userLoginId === null ? (
<ComponentGlobal_BoxInformation informasi="Anda tidak memiliki akses untuk melihat detail proyek ini" />
) : (
<Stack>
<ComponentGlobal_CardStyles>
<Stack>
<ComponentColab_AuthorNameOnHeader
@@ -56,13 +68,13 @@ export default function Colab_MainDetail({
<ComponentColab_DetailData data={data as any} />
</Stack>
</ComponentGlobal_CardStyles>
)}
<ComponentColab_DetailListPartisipasiUser
userLoginId={userLoginId}
authorId={data?.Author.id}
/>
</Stack>
<ComponentColab_DetailListPartisipasiUser
userLoginId={userLoginId as string}
authorId={data?.Author.id}
/>
</Stack>
)}
</>
);
}

View File

@@ -12,8 +12,8 @@ export default async function colab_getMessageByRoomId({
roomId: string;
page: number;
}) {
const lewat = page * 6 - 6;
const ambil = 6;
const ambil = 10;
const lewat = page * ambil - ambil;
const getList = await prisma.projectCollaboration_Message.findMany({
orderBy: {