This commit is contained in:
everythingonblack
2025-05-29 03:11:22 +07:00
parent 6afcbd8847
commit 6f9e68f431

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import styles from './ChatBot.module.css'; import styles from './ChatBot.module.css';
const ChatBot = () => { const ChatBot = () => {
@@ -17,6 +17,23 @@ const ChatBot = () => {
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!localStorage.getItem('session')) {
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const sessionId = generateUUID();
const dateNow = new Date().toISOString();
localStorage.setItem('session', JSON.stringify({ sessionId: sessionId, lastSeen: dateNow}))
}
}, []);
const sendMessage = async (textOverride = null) => { const sendMessage = async (textOverride = null) => {
const message = textOverride || input.trim(); const message = textOverride || input.trim();
if (message === '') return; if (message === '') return;
@@ -26,16 +43,17 @@ const ChatBot = () => {
{ sender: 'user', text: message, time: getTime() }, { sender: 'user', text: message, time: getTime() },
...messages, ...messages,
]; ];
setMessages(newMessages); setMessages(newMessages);
setInput(''); setInput('');
setIsLoading(true); setIsLoading(true);
try { try {
// Send to backend // Send to backend
const response = await fetch('https://n8n.kediritechnopark.my.id/webhook/master-agent/ask' , { const response = await fetch('https://n8n.kediritechnopark.my.id/webhook/master-agent/ask', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pertanyaan: newMessages }), body: JSON.stringify({ pertanyaan: newMessages, sessionId: JSON.parse(localStorage.getItem('session')).sessionId, lastSeen: new Date().toISOString() }),
}); });
if (!response.ok) throw new Error('Network response was not ok'); if (!response.ok) throw new Error('Network response was not ok');
@@ -101,7 +119,6 @@ const ChatBot = () => {
)} )}
<div className={`${styles.message} ${styles[msg.sender]}`}> <div className={`${styles.message} ${styles[msg.sender]}`}>
{msg.text} {msg.text}
<div className={styles.timestamp}>{msg.time}</div>
{msg.quickReplies && ( {msg.quickReplies && (
<div className={styles.quickReplies}> <div className={styles.quickReplies}>
{msg.quickReplies.map((reply, i) => ( {msg.quickReplies.map((reply, i) => (
@@ -115,6 +132,7 @@ const ChatBot = () => {
))} ))}
</div> </div>
)} )}
<div className={styles.timestamp}>{msg.time}</div>
</div> </div>
{msg.sender === 'user' && ( {msg.sender === 'user' && (
<img <img