Update Versi 1.5.27 #32

Merged
bagasbanuna merged 1009 commits from staging into main 2025-12-17 12:22:28 +08:00
2042 changed files with 85058 additions and 21855 deletions
Showing only changes of commit 740ae44734 - Show all commits

View File

@@ -0,0 +1,70 @@
// /app/api/collaboration/[id]/chat/route.ts
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 cursor = searchParams.get("cursor"); // ini adalah `id` pesan terakhir dari client
const takeData =5
console.log("cursor", cursor);
// Query dengan cursor
const messages = await prisma.projectCollaboration_Message.findMany({
where: {
projectCollaboration_RoomChatId: roomId,
isActive: true,
id: cursor ? { lt: cursor } : undefined, // ambil yang lebih lama dari cursor
},
orderBy: {
createdAt: "desc", // urutkan dari paling baru
},
take: takeData,
select: {
id: true,
createdAt: true,
isActive: true,
message: true,
isFile: true,
User: {
select: {
id: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
},
});
return NextResponse.json({
success: true,
message: "Berhasil mendapatkan data",
data: messages,
nextCursor: messages.length > 0 ? messages[messages.length - 1]?.id : null,
});
} 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,224 @@
/* eslint-disable react-hooks/exhaustive-deps */
// components/ChatScrollArea.tsx
import React, { useEffect, useRef, useState } from "react";
import { ScrollArea, Box, Button, Text } from "@mantine/core";
import { ChatMessage } from "./interface";
import { apiGetMessageByRoomId } from "@/app_modules/colab/_lib/api_collaboration";
interface ChatScrollAreaProps {
initialMessages: ChatMessage[];
currentUserId: string;
chatRoomId: string;
}
export const ChatScrollArea: React.FC<ChatScrollAreaProps> = ({
initialMessages,
currentUserId,
chatRoomId,
}) => {
const [messages, setMessages] = useState<ChatMessage[]>(initialMessages);
const [hasMore, setHasMore] = useState(true);
const [showNewMessageIndicator, setShowNewMessageIndicator] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const loaderRef = useRef<HTMLDivElement>(null);
const lastMessageIdRef = useRef<string | null>(null);
// Auto scroll to bottom on first render
useEffect(() => {
scrollToBottom();
}, []);
// // Infinite Scroll Up - Load Older Messages
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && hasMore) {
loadMoreMessages();
}
},
{ root: scrollAreaRef.current }
);
if (loaderRef.current) observer.observe(loaderRef.current);
return () => observer.disconnect();
}, [hasMore]);
const scrollToBottom = () => {
setTimeout(() => {
if (messagesEndRef.current) {
messagesEndRef.current.scrollIntoView({ behavior: "auto" });
}
}, 100);
};
const [loadingMore, setLoadingMore] = useState(false);
const loadMoreMessages = async () => {
console.log("Triggered loadMoreMessages");
console.log("Current lastMessageId:", lastMessageIdRef.current);
if (!hasMore || loadingMore) return;
setLoadingMore(true);
try {
const result = await apiGetMessageByRoomId({
id: chatRoomId,
lastMessageId: lastMessageIdRef.current || undefined,
});
console.log("API Response:", result);
if (!result.success || !result.data || result.data.length === 0) {
console.log("No more data from API");
setHasMore(false);
return;
}
const olderMessages = result.data;
const existingIds = new Set(messages.map((m) => m.id));
const filtered = olderMessages.filter((msg: ChatMessage) => !existingIds.has(msg.id));
console.log("Filtered Messages:", filtered);
if (filtered.length === 0) {
console.log("All messages already loaded");
setHasMore(false);
return;
}
lastMessageIdRef.current = filtered[0]?.id;
setMessages((prev) => [...prev, ...filtered]);
} catch (error) {
console.error("Failed to load more messages", error);
setHasMore(false);
} finally {
setLoadingMore(false);
}
};;
// const sendMessage = async (content: string) => {
// try {
// const res = await fetch("/api/chat/send", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({
// content,
// chatRoomId,
// }),
// });
// const result = await res.json();
// if (result.success) {
// const newMessage = result.data;
// setMessages((prev) => [...prev, newMessage]);
// scrollToBottom();
// }
// } catch (error) {
// console.error("Error sending message", error);
// }
// };
// const handleScrollToBottomClick = () => {
// scrollToBottom();
// setShowNewMessageIndicator(false);
// };
// Simulasi menerima pesan baru (misalnya via WebSocket atau polling)
// const handleIncomingMessage = (newMessage: ChatMessage) => {
// if (newMessage.User?.id !== currentUserId) {
// const isScrolledToBottom =
// scrollAreaRef.current &&
// scrollAreaRef.current.scrollHeight -
// scrollAreaRef.current.clientHeight <=
// scrollAreaRef.current.scrollTop + 100;
// if (!isScrolledToBottom) {
// setShowNewMessageIndicator(true);
// } else {
// setMessages((prev) => [...prev, newMessage]);
// scrollToBottom();
// }
// } else {
// setMessages((prev) => [...prev, newMessage]);
// scrollToBottom();
// }
// };
return (
<Box style={{ height: "100%" }}>
{/* Scroll Area */}
<ScrollArea viewportRef={scrollAreaRef} h="30vh">
<Box style={{ display: "flex", flexDirection: "column-reverse" }}>
{hasMore && (
<Text align="center" ref={loaderRef}>
{loadingMore ? "Loading..." : "Load more"}
</Text>
)}
{messages.map((msg) => (
<Box
key={msg.id}
p="sm"
mb="xs"
bg={msg.User?.id === currentUserId ? "blue.1" : "gray.1"}
style={{
alignSelf:
msg.User?.id === currentUserId ? "flex-end" : "flex-start",
maxWidth: "70%",
borderRadius: 8,
padding: "8px 12px",
}}
>
<Text>{msg.message}</Text>
</Box>
))}
<div ref={messagesEndRef} />
</Box>
</ScrollArea>
{/* Tombol Scroll ke Bawah jika ada pesan baru */}
{showNewMessageIndicator && (
<Button
// onClick={handleScrollToBottomClick}
fullWidth
mt="md"
color="blue"
>
New Messages
</Button>
)}
{/* Form Kirim Pesan */}
<form
onSubmit={(e) => {
e.preventDefault();
const input = e.currentTarget.elements.namedItem(
"message"
) as HTMLInputElement;
if (input.value.trim()) {
// sendMessage(input.value);
input.value = "";
}
}}
>
<Box display="flex" p="sm" mt="md">
<input
name="message"
placeholder="Type a message..."
style={{ flex: 1 }}
/>
<button type="submit">Send</button>
</Box>
</form>
</Box>
);
};

View File

@@ -1,198 +0,0 @@
// 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,17 @@
// types/message.ts
export interface ChatUser {
id: string;
Profile: {
id: string;
name: string;
};
}
export interface ChatMessage {
id: string;
message: string;
isActive: boolean;
createdAt: Date;
isFile?: boolean | null;
User: ChatUser | null;
}

View File

@@ -1,83 +1,60 @@
// app/chat/[id]/page.tsx
"use client";
import React, { useState, useCallback } from "react";
import ChatWindow from "./chat_window";
import { apiGetMessageByRoomId } from "@/app_modules/colab/_lib/api_collaboration";
import { useShallowEffect } from "@mantine/hooks";
import { ChatMessage } from "./interface";
import { useState } from "react";
import { ChatScrollArea } from "./ChatScrollArea";
import { apiNewGetUserIdByToken } from "@/app_modules/_global/lib/api_fetch_global";
interface Message {
id: string;
content: string;
senderId: string;
createdAt: Date;
}
export default function ChatPage({ params }: { params: { id: string } }) {
const roomId = params.id;
const [initialMessages, setInitialMessages] = useState<ChatMessage[]>([]);
const [loading, setLoading] = useState(true);
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);
const [userLoginId, setUserLoginId] = useState<string | null>(null);
useShallowEffect(() => {
handleGetUserLoginId();
}, []);
async function handleGetUserLoginId() {
try {
const response = await apiNewGetUserIdByToken();
if (response.success) {
setUserLoginId(response.userId);
} else {
setUserLoginId(null);
}
} catch (error) {
setUserLoginId(null);
}
}
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
async function handleGetDataMessage() {
try {
const result = await apiGetMessageByRoomId({ id: roomId });
setInitialMessages(result.data || []);
} catch (error) {
console.error("Failed to load messages", error);
} finally {
setLoading(false);
}
}
useShallowEffect(() => {
loadInitialMessages();
}, [loadInitialMessages]);
handleGetDataMessage();
}, [roomId]);
if (loading || !userLoginId) {
return <div>Loading chat...</div>;
}
return (
<ChatWindow
initialMessages={messages}
currentUserId={currentUserId}
loadMoreMessages={loadMoreMessages}
sendMessage={sendMessage}
<ChatScrollArea
initialMessages={initialMessages}
currentUserId={userLoginId} // ganti dengan auth dinamis
chatRoomId={roomId}
/>
);
}

View File

@@ -1,9 +1,6 @@
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";
@@ -31,6 +28,7 @@ export default async function Page({ params }: { params: { id: string } }) {
/> */}
<Colab_NewGroupChatView selectRoom={dataRoom as any} listMsg={listMsg} />
{/* <ChatPage params={{ id: roomId }} /> */}
</>
);
}

View File

@@ -152,6 +152,51 @@ export const apiCollaborationGetMessageByRoomId = async ({
}
};
export const apiGetMessageByRoomId = async ({
id,
lastMessageId,
}: {
id: string;
lastMessageId?: 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;
}
console.log("lastMessageId", lastMessageId);
let url = `/api/collaboration/${id}/chat`;
if (lastMessageId) {
url += `?cursor=${lastMessageId}`;
}
const response = await fetch(url, {
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,
}: {