+ );
+}
+
+export default React.memo(UserMenu);
diff --git a/next/pages/chatbot.js b/next/pages/chatbot.js
index 0bc16fdc..971d0853 100644
--- a/next/pages/chatbot.js
+++ b/next/pages/chatbot.js
@@ -8,6 +8,8 @@ import {
import { useState, useEffect, useRef, useCallback } from "react";
import Head from "next/head";
import { useRouter } from "next/router";
+import { useTranslation } from "next-i18next";
+import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import cookies from "js-cookie";
import Sidebar from "../components/organisms/chatbot/Sidebar";
import Search from "../components/organisms/chatbot/Search";
@@ -17,9 +19,10 @@ import Display from "../components/atoms/Text/Display";
import SidebarIcon from "../public/img/icons/sidebarIcon";
import CrossIcon from "../public/img/icons/crossIcon";
import BDLogoImage from "../public/img/logos/bd_logo";
+import HelpContent from "../components/organisms/chatbot/HelpContent";
import useChatbot from "../hooks/useChatbot";
import { ChatbotProvider } from "../context/ChatbotContext";
-import { redirectToChatbotCheckout, clearClientSession } from "../utils";
+import ChatbotAccessGate from "../components/organisms/chatbot/ChatbotAccessGate";
function getGreetingFirstNameFromCookie() {
try {
@@ -33,71 +36,9 @@ function getGreetingFirstNameFromCookie() {
}
}
-async function clearAuthCookiesAndRedirectLogin(router) {
- if (typeof window !== "undefined") {
- localStorage.setItem("previousPath", window.location.href);
- }
- await clearClientSession();
- router.replace("/user/login");
-}
-
-function hasUserCookie() {
- const userRaw = cookies.get("userBD");
- if (!userRaw || userRaw === "undefined") return false;
- try {
- JSON.parse(userRaw);
- return true;
- } catch {
- return false;
- }
-}
-
-function ChatbotAccessGate({ children }) {
- const router = useRouter();
- const [canEnter, setCanEnter] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
-
- async function checkAccess() {
- if (typeof window === "undefined") return;
- if (!hasUserCookie()) {
- await clearAuthCookiesAndRedirectLogin(router);
- return;
- }
- try {
- const res = await fetch("/api/user/validateToken", {
- method: "GET",
- credentials: "same-origin"
- });
- const data = await res.json();
- if (cancelled) return;
- if (!res.ok || !data.success) {
- await clearAuthCookiesAndRedirectLogin(router);
- return;
- }
- if (!data.has_chatbot_access) {
- await redirectToChatbotCheckout(router);
- return;
- }
- setCanEnter(true);
- } catch {
- if (!cancelled) await clearAuthCookiesAndRedirectLogin(router);
- }
- }
-
- checkAccess();
- return () => {
- cancelled = true;
- };
- }, [router]);
-
- if (!canEnter) return null;
- return children;
-}
-
function ChatbotContent() {
const router = useRouter();
+ const { t } = useTranslation("chatbot");
const { t: threadIdFromUrl } = router.query;
const normalizedThreadId = Array.isArray(threadIdFromUrl)
? threadIdFromUrl[0]
@@ -110,6 +51,7 @@ function ChatbotContent() {
const searchRef = useRef(null);
const [greetingFirstName, setGreetingFirstName] = useState(null);
+ const [showHelp, setShowHelp] = useState(false);
useEffect(() => {
setGreetingFirstName(getGreetingFirstNameFromCookie());
@@ -191,6 +133,7 @@ function ChatbotContent() {
const handleNewChat = useCallback(() => {
skipFetchRef.current = true;
resetChat();
+ setShowHelp(false);
setIsMobileSidebarOpen(false);
router.push({
pathname: router.pathname,
@@ -198,6 +141,14 @@ function ChatbotContent() {
}, undefined, { shallow: true });
}, [resetChat, router]);
+ const handleSelectThread = useCallback(() => {
+ setShowHelp(false);
+ }, []);
+
+ const handleHelp = useCallback(() => {
+ setShowHelp(true);
+ }, []);
+
const showNewChatGreeting =
router.isReady && !normalizedThreadId && messages.length === 0;
@@ -276,15 +227,15 @@ function ChatbotContent() {
return (
- Chatbot - Basedosdados
+ {showHelp ? t("help.head.pageTitle") : "Chatbot - Basedosdados"}
@@ -301,6 +252,8 @@ function ChatbotContent() {
>
- {showNewChatGreeting ? (
+ {showHelp ? (
+
+ ) : showNewChatGreeting ? (
diff --git a/next/public/locales/en/chatbot.json b/next/public/locales/en/chatbot.json
index b70164c9..78623433 100644
--- a/next/public/locales/en/chatbot.json
+++ b/next/public/locales/en/chatbot.json
@@ -41,5 +41,44 @@
"banner": {
"title": "Create analyses in seconds with the power of AI and Base dos Dados' Datalake",
"button": "Try the BD chatbot now"
+ },
+ "ui": {
+ "newChat": "New chat",
+ "openMenu": "Open menu",
+ "signOut": "Sign out",
+ "help": "Help",
+ "userMenu": "Account menu"
+ },
+ "help": {
+ "head": {
+ "pageTitle": "Help - Chatbot"
+ },
+ "title": "DB Chatbot",
+ "subtitle": "To analyze public data using natural language",
+ "welcomeTitle": "Welcome! 👋",
+ "welcomeP1": "Welcome to the Data Basis chatbot. It helps you talk to your data so you can understand it better and extract valuable insights.",
+ "welcomeP2": "To get started, go to the chat page in the left menu and start a new conversation.",
+ "welcomeP3": "Why not ask it what data is available on your research topic?",
+ "welcomeP4": "The chatbot can also help you with:",
+ "capabilities": [
+ "Exploratory analyses",
+ "Understanding how tables are organized",
+ "Querying and downloading data from our public datalake"
+ ],
+ "welcomeP5": "All you need is a good question!",
+ "contact": "Have questions or need help? You can reach us by email at suporte.bdpro@basedosdados.org or through our community on Discord and WhatsApp.",
+ "featuresTitle": "Features 🛠️",
+ "dataSources": "Data Sources: Click the items in the \"Data Sources\" field to see the datasets used in each response.",
+ "suggestedQuestions": "Suggested Questions: Click the items in \"Suggested Questions\" to deepen your analysis with prompts suggested by the chatbot itself.",
+ "download": "Download data: Click the icon () and choose the table you would like to download as a .csv file.",
+ "copyResults": "Copy results: Click the icon () to copy the chatbot's response to your clipboard.",
+ "feedback": "Feedback ( or ): Click the feedback buttons to rate the responses, with optional comments.",
+ "promptGuideTitle": "Prompt Tips 📋",
+ "promptGuideIntro": "How you talk to the chatbot can affect the quality of the answers! Below are some tips to help you write your questions. They can be useful if the answers are incorrect or not good enough.",
+ "promptTips": [
+ "Try asking one question at a time. If your question is too complex, or is actually several questions, try splitting it into smaller, simpler questions.",
+ "When in doubt, ask the chatbot itself for help. It can help you understand which data is available, which lines of analysis you can follow, or you can ask it to explain a response better.",
+ "If the chatbot cannot find an answer to your question and you know which table has the data needed to answer it, you can explicitly ask it to look in that specific table."
+ ]
}
}
diff --git a/next/public/locales/es/chatbot.json b/next/public/locales/es/chatbot.json
index 8e39e105..470498a0 100644
--- a/next/public/locales/es/chatbot.json
+++ b/next/public/locales/es/chatbot.json
@@ -41,5 +41,44 @@
"banner": {
"title": "Crea análisis en segundos con el poder de la IA y el Datalake de Base de los Datos",
"button": "Prueba ya el chatbot de BD"
+ },
+ "ui": {
+ "newChat": "Nueva conversación",
+ "openMenu": "Abrir menú",
+ "signOut": "Cerrar sesión",
+ "help": "Ayuda",
+ "userMenu": "Menú de la cuenta"
+ },
+ "help": {
+ "head": {
+ "pageTitle": "Ayuda - Chatbot"
+ },
+ "title": "Chatbot BD",
+ "subtitle": "Para analizar datos públicos utilizando lenguaje natural",
+ "welcomeTitle": "¡Bienvenido(a)! 👋",
+ "welcomeP1": "Bienvenido(a) al chatbot de BD, te ayudará a conversar con tus datos para entenderlos mejor y extraer insights valiosos.",
+ "welcomeP2": "Para empezar, entra en la página de chat en el menú de la izquierda y comienza una nueva conversación.",
+ "welcomeP3": "¿Qué tal preguntarle qué datos hay disponibles sobre el tema de tu investigación?",
+ "welcomeP4": "El chatbot también puede ayudarte con:",
+ "capabilities": [
+ "Análisis exploratorios",
+ "Entendimiento de la organización de las tablas",
+ "Consultas y descarga de datos de nuestro datalake público"
+ ],
+ "welcomeP5": "¡Todo lo que necesitas es una buena pregunta!",
+ "contact": "¿Tienes dudas o necesitas ayuda? Puedes escribirnos al correo suporte.bdpro@basedosdados.org o a través de nuestra comunidad en Discord y WhatsApp.",
+ "featuresTitle": "Funcionalidades 🛠️",
+ "dataSources": "Fuentes de Datos: Haz clic en los elementos del campo \"Fuentes de Datos\" para ver los conjuntos de datos utilizados en cada respuesta.",
+ "suggestedQuestions": "Preguntas Sugeridas: Haz clic en los elementos de \"Preguntas Sugeridas\" para profundizar tu análisis con prompts sugeridos por el propio chatbot.",
+ "download": "Descargar datos: Haz clic en el icono () y elige la tabla que te gustaría descargar en .csv.",
+ "copyResults": "Copiar resultados: Haz clic en el icono () para copiar la respuesta del chatbot en tu Portapapeles.",
+ "feedback": "Comentarios ( o ): Haz clic en los botones de comentarios para evaluar las respuestas, con comentarios opcionales.",
+ "promptGuideTitle": "Consejos de Prompt 📋",
+ "promptGuideIntro": "¡La forma en que conversas con el chatbot puede influir en la calidad de las respuestas! Por eso, a continuación hay algunos consejos para ayudarte a elaborar tus preguntas. Pueden ser útiles si las respuestas son incorrectas o no son lo suficientemente buenas.",
+ "promptTips": [
+ "Intenta hacer una pregunta a la vez. Si tu pregunta es muy compleja, o es un conjunto de varias preguntas, intenta separarla en preguntas más pequeñas y simples.",
+ "En caso de duda, pide ayuda al propio chatbot. Te ayuda a entender mejor qué datos están disponibles, qué líneas de análisis puedes seguir o pídele que explique mejor alguna respuesta.",
+ "Si el chatbot no encuentra una respuesta a tu pregunta y sabes en qué tabla están los datos necesarios para responderla, puedes pedirle explícitamente que busque en esa tabla específica."
+ ]
}
}
diff --git a/next/public/locales/pt/chatbot.json b/next/public/locales/pt/chatbot.json
index a047a4f0..505e1a07 100644
--- a/next/public/locales/pt/chatbot.json
+++ b/next/public/locales/pt/chatbot.json
@@ -41,5 +41,44 @@
"banner": {
"title": "Crie análises em segundos com o poder da IA e o Datalake da Base dos Dados",
"button": "Teste já o chatbot da BD"
+ },
+ "ui": {
+ "newChat": "Nova conversa",
+ "openMenu": "Abrir menu",
+ "signOut": "Sair",
+ "help": "Ajuda",
+ "userMenu": "Menu da conta"
+ },
+ "help": {
+ "head": {
+ "pageTitle": "Ajuda - Chatbot"
+ },
+ "title": "Chatbot BD",
+ "subtitle": "Para analisar dados públicos utilizando linguagem natural",
+ "welcomeTitle": "Bem-vindo(a)! 👋",
+ "welcomeP1": "Bem-vindo(a) ao chatbot da BD, ele vai te ajudar a conversar com seus dados para você entendê-los melhor e extrair insights valiosos.",
+ "welcomeP2": "Para começar, basta entrar na página de chat no menu à esquerda e começar uma nova conversa.",
+ "welcomeP3": "Que tal perguntar para ele quais são os dados disponíveis sobre o tema da sua pesquisa?",
+ "welcomeP4": "O chatbot também pode te ajudar com:",
+ "capabilities": [
+ "Análises exploratórias",
+ "Entendimento da organização das tabelas",
+ "Consultas e download de dados do nosso datalake público"
+ ],
+ "welcomeP5": "Tudo que você precisa é de uma boa pergunta!",
+ "contact": "Teve dúvidas ou precisa de ajuda? Você pode falar conosco pelo email suporte.bdpro@basedosdados.org ou pela nossa comunidade no Discord e WhatsApp.",
+ "featuresTitle": "Funcionalidades 🛠️",
+ "dataSources": "Fontes de Dados: Clique nos itens do campo \"Fontes dos Dados\" para conferir os conjuntos de dados utilizados em cada resposta.",
+ "suggestedQuestions": "Perguntas Sugeridas: Clique nos itens em \"Perguntas Sugeridas\" para aprofundar sua análise com prompts sugeridos pelo próprio chatbot.",
+ "download": "Baixar dados: Clique no ícone () e escolha a tabela que você gostaria de fazer download em .csv.",
+ "copyResults": "Copiar resultados: Clique no ícone () para copiar a resposta do chatbot na sua Área de Transferência.",
+ "feedback": "Feedback ( ou ): Clique nos botões de feedback para avaliar as respostas, com comentários opcionais.",
+ "promptGuideTitle": "Dicas de Prompt 📋",
+ "promptGuideIntro": "A forma como você conversa com o chatbot pode influenciar na qualidade das respostas! Por isso, abaixo estão listadas algumas dicas para te ajudar a elaborar suas perguntas. Elas podem ser úteis caso as respostas fornecidas estejam incorretas ou não sejam boas o suficiente!",
+ "promptTips": [
+ "Tente fazer uma pergunta por vez. Caso sua pergunta seja muito complexa, ou talvez seja um conjunto de várias perguntas, tente separá-la em perguntas menores e mais simples.",
+ "Na dúvida, peça uma ajuda para o próprio chatbot. Ele te ajuda a entender melhor quais dados estão disponíveis, quais linhas de análises possíveis você pode seguir ou peça para ele explicar melhor alguma resposta.",
+ "Caso o chatbot não esteja encontrando uma resposta para a sua pergunta e você saiba em qual tabela estão os dados necessários para respondê-la, você pode tentar pedir explicitamente para procurar nesta tabela específica."
+ ]
}
}