mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 09:12:08 +01:00
Improves transcript viewer with Markdown support
Adds Markdown rendering to the transcript viewer for enhanced formatting. This change integrates `react-markdown` to parse and render transcript content, allowing for richer text formatting, including links and other Markdown elements. It also adds a toggle to switch between raw and formatted text, and displays a message when transcript content is unavailable. The UI of the transcript viewer has been improved to be more user-friendly with titles and descriptions.
This commit is contained in:
144
app/dashboard/sessions/[id]/page.tsx
Normal file
144
app/dashboard/sessions/[id]/page.tsx
Normal file
@ -0,0 +1,144 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import SessionDetails from "../../../../components/SessionDetails";
|
||||
import TranscriptViewer from "../../../../components/TranscriptViewer";
|
||||
import { ChatSession } from "../../../../lib/types";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function SessionViewPage() {
|
||||
const params = useParams();
|
||||
const id = params?.id as string;
|
||||
const [session, setSession] = useState<ChatSession | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (id) {
|
||||
const fetchSession = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/dashboard/session/${id}`);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(
|
||||
errorData.error ||
|
||||
`Failed to fetch session: ${response.statusText}`
|
||||
);
|
||||
}
|
||||
const data = await response.json();
|
||||
setSession(data.session);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "An unknown error occurred"
|
||||
);
|
||||
setSession(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchSession();
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
|
||||
<p className="text-gray-600 text-lg">Loading session details...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="p-4 md:p-6 min-h-screen">
|
||||
<p className="text-red-500 text-lg mb-4">Error: {error}</p>
|
||||
<Link
|
||||
href="/dashboard/sessions"
|
||||
className="text-sky-600 hover:underline"
|
||||
>
|
||||
Back to Sessions List
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="p-4 md:p-6 min-h-screen">
|
||||
<p className="text-gray-600 text-lg mb-4">Session not found.</p>
|
||||
<Link
|
||||
href="/dashboard/sessions"
|
||||
className="text-sky-600 hover:underline"
|
||||
>
|
||||
Back to Sessions List
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-100 p-4 md:p-6">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="mb-6">
|
||||
<Link
|
||||
href="/dashboard/sessions"
|
||||
className="text-sky-700 hover:text-sky-900 hover:underline flex items-center"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-5 w-5 mr-1"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
Back to Sessions List
|
||||
</Link>
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-6">
|
||||
Session: {session.sessionId || session.id}
|
||||
</h1>
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
<div>
|
||||
<SessionDetails session={session} />
|
||||
</div>
|
||||
{session.transcriptContent &&
|
||||
session.transcriptContent.trim() !== "" ? (
|
||||
<div className="mt-0">
|
||||
{" "}
|
||||
{/* Adjusted margin, TranscriptViewer has its own top margin */}
|
||||
<TranscriptViewer
|
||||
transcriptContent={session.transcriptContent}
|
||||
transcriptUrl={session.fullTranscriptUrl}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white p-4 rounded-lg shadow">
|
||||
<h3 className="font-bold text-lg mb-3">Transcript</h3>
|
||||
<p className="text-gray-600">
|
||||
No transcript content available for this session.
|
||||
</p>
|
||||
{session.fullTranscriptUrl && (
|
||||
<a
|
||||
href={session.fullTranscriptUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sky-600 hover:underline mt-2 inline-block"
|
||||
>
|
||||
View Source Transcript URL
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
128
app/dashboard/sessions/page.tsx
Normal file
128
app/dashboard/sessions/page.tsx
Normal file
@ -0,0 +1,128 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"; // Added useCallback
|
||||
import { ChatSession } from "../../../lib/types";
|
||||
import Link from "next/link";
|
||||
|
||||
// Placeholder for a SessionListItem component to be created later
|
||||
// For now, we'll display some basic info directly.
|
||||
// import SessionListItem from "../../../components/SessionListItem";
|
||||
|
||||
export default function SessionsPage() {
|
||||
const [sessions, setSessions] = useState<ChatSession[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
// Debounce search term to avoid excessive API calls
|
||||
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(searchTerm);
|
||||
|
||||
useEffect(() => {
|
||||
const timerId = setTimeout(() => {
|
||||
setDebouncedSearchTerm(searchTerm);
|
||||
}, 500); // 500ms delay
|
||||
return () => {
|
||||
clearTimeout(timerId);
|
||||
};
|
||||
}, [searchTerm]);
|
||||
|
||||
const fetchSessions = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const query = debouncedSearchTerm
|
||||
? `?searchTerm=${encodeURIComponent(debouncedSearchTerm)}`
|
||||
: "";
|
||||
const response = await fetch(`/api/dashboard/sessions${query}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch sessions: ${response.statusText}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
setSessions(data.sessions || []);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "An unknown error occurred"
|
||||
);
|
||||
setSessions([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [debouncedSearchTerm]); // Depend on debouncedSearchTerm
|
||||
|
||||
useEffect(() => {
|
||||
fetchSessions();
|
||||
}, [fetchSessions]); // fetchSessions is now stable due to useCallback and its dependency
|
||||
|
||||
return (
|
||||
<div className="p-4 md:p-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-800 mb-6">
|
||||
Chat Sessions
|
||||
</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search sessions (ID, category, initial message...)"
|
||||
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{loading && <p className="text-gray-600">Loading sessions...</p>}
|
||||
{error && <p className="text-red-500">Error: {error}</p>}
|
||||
|
||||
{!loading && !error && sessions.length === 0 && (
|
||||
<p className="text-gray-600">
|
||||
{debouncedSearchTerm
|
||||
? `No sessions found for "${debouncedSearchTerm}".`
|
||||
: "No sessions found."}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!loading && !error && sessions.length > 0 && (
|
||||
<div className="space-y-4">
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
key={session.id}
|
||||
className="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow"
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-sky-700 mb-1">
|
||||
Session ID: {session.sessionId || session.id}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 mb-1">
|
||||
Start Time: {new Date(session.startTime).toLocaleString()}
|
||||
</p>
|
||||
{session.category && (
|
||||
<p className="text-sm text-gray-700">
|
||||
Category:{" "}
|
||||
<span className="font-medium">{session.category}</span>
|
||||
</p>
|
||||
)}
|
||||
{session.language && (
|
||||
<p className="text-sm text-gray-700">
|
||||
Language:{" "}
|
||||
<span className="font-medium">
|
||||
{session.language.toUpperCase()}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
{session.initialMsg && (
|
||||
<p className="text-sm text-gray-600 mt-1 truncate">
|
||||
Initial Message: {session.initialMsg}
|
||||
</p>
|
||||
)}
|
||||
<Link
|
||||
href={`/dashboard/sessions/${session.id}`}
|
||||
className="mt-2 text-sm text-sky-600 hover:text-sky-800 hover:underline inline-block"
|
||||
>
|
||||
View Details
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* TODO: Add pagination controls */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import ReactMarkdown from "react-markdown"; // Import ReactMarkdown
|
||||
|
||||
interface TranscriptViewerProps {
|
||||
transcriptContent: string;
|
||||
@ -47,7 +48,22 @@ function formatTranscript(content: string): React.ReactNode[] {
|
||||
}`}
|
||||
>
|
||||
{currentMessages.map((msg, i) => (
|
||||
<p key={i}>{msg}</p>
|
||||
// Use ReactMarkdown to render each message part
|
||||
<ReactMarkdown
|
||||
key={i}
|
||||
components={{
|
||||
p: "span",
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
a: ({ node: _node, ...props }) => (
|
||||
<a
|
||||
className="text-sky-600 hover:text-sky-800 underline"
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{msg}
|
||||
</ReactMarkdown>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@ -83,7 +99,22 @@ function formatTranscript(content: string): React.ReactNode[] {
|
||||
}`}
|
||||
>
|
||||
{currentMessages.map((msg, i) => (
|
||||
<p key={i}>{msg}</p>
|
||||
// Use ReactMarkdown to render each message part
|
||||
<ReactMarkdown
|
||||
key={i}
|
||||
components={{
|
||||
p: "span",
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
a: ({ node: _node, ...props }) => (
|
||||
<a
|
||||
className="text-sky-600 hover:text-sky-800 underline"
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{msg}
|
||||
</ReactMarkdown>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@ -100,36 +131,51 @@ export default function TranscriptViewer({
|
||||
transcriptContent,
|
||||
transcriptUrl,
|
||||
}: TranscriptViewerProps) {
|
||||
const [showTranscript, setShowTranscript] = useState(false);
|
||||
const [showRaw, setShowRaw] = useState(false);
|
||||
|
||||
const formattedElements = formatTranscript(transcriptContent);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between pt-2">
|
||||
<span className="text-gray-600">Transcript:</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setShowTranscript(!showTranscript)}
|
||||
className="text-blue-500 hover:text-blue-700 underline"
|
||||
>
|
||||
{showTranscript ? "Hide Transcript" : "Show Transcript"}
|
||||
</button>
|
||||
<div className="bg-white shadow-lg rounded-lg p-4 md:p-6 mt-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-semibold text-gray-800">
|
||||
Session Transcript
|
||||
</h2>
|
||||
<div className="flex items-center space-x-3">
|
||||
{transcriptUrl && (
|
||||
<a
|
||||
href={transcriptUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-700 underline"
|
||||
className="text-sm text-sky-600 hover:text-sky-800 hover:underline"
|
||||
title="View full raw transcript"
|
||||
>
|
||||
View Source
|
||||
View Full Raw
|
||||
</a>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setShowRaw(!showRaw)}
|
||||
className="text-sm text-sky-600 hover:text-sky-800 hover:underline"
|
||||
title={
|
||||
showRaw ? "Show formatted transcript" : "Show raw transcript"
|
||||
}
|
||||
>
|
||||
{showRaw ? "Formatted" : "Raw Text"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Display transcript content if expanded */}
|
||||
{showTranscript && (
|
||||
<div className="mt-4 p-4 bg-gray-50 rounded-lg max-h-96 overflow-auto">
|
||||
<div className="space-y-2">{formatTranscript(transcriptContent)}</div>
|
||||
{showRaw ? (
|
||||
<pre className="whitespace-pre-wrap text-sm text-gray-700 bg-gray-50 p-3 rounded-md overflow-x-auto">
|
||||
{transcriptContent}
|
||||
</pre>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{formattedElements.length > 0 ? (
|
||||
formattedElements
|
||||
) : (
|
||||
<p className="text-gray-500">No transcript content available.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
1182
package-lock.json
generated
1182
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -36,7 +36,8 @@
|
||||
"react": "^19.1.0",
|
||||
"react-chartjs-2": "^5.0.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-leaflet": "^5.0.0"
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-markdown": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.3.1",
|
||||
|
||||
62
pages/api/dashboard/session/[id].ts
Normal file
62
pages/api/dashboard/session/[id].ts
Normal file
@ -0,0 +1,62 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { prisma } from "../../../../lib/prisma";
|
||||
import { ChatSession } from "../../../../lib/types";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(405).json({ error: "Method not allowed" });
|
||||
}
|
||||
|
||||
const { id } = req.query;
|
||||
|
||||
if (!id || typeof id !== "string") {
|
||||
return res.status(400).json({ error: "Session ID is required" });
|
||||
}
|
||||
|
||||
try {
|
||||
const prismaSession = await prisma.session.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!prismaSession) {
|
||||
return res.status(404).json({ error: "Session not found" });
|
||||
}
|
||||
|
||||
// Map Prisma session object to ChatSession type
|
||||
const session: ChatSession = {
|
||||
...prismaSession,
|
||||
sessionId: prismaSession.id, // Assuming ChatSession's sessionId is Prisma's id
|
||||
startTime: new Date(prismaSession.startTime),
|
||||
endTime: prismaSession.endTime ? new Date(prismaSession.endTime) : null,
|
||||
createdAt: new Date(prismaSession.createdAt),
|
||||
updatedAt: new Date(prismaSession.updatedAt),
|
||||
userId: prismaSession.userId === undefined ? null : prismaSession.userId,
|
||||
category: prismaSession.category === undefined ? null : prismaSession.category,
|
||||
language: prismaSession.language === undefined ? null : prismaSession.language,
|
||||
country: prismaSession.country === undefined ? null : prismaSession.country,
|
||||
ipAddress: prismaSession.ipAddress === undefined ? null : prismaSession.ipAddress,
|
||||
sentiment: prismaSession.sentiment === undefined ? null : prismaSession.sentiment,
|
||||
messagesSent: prismaSession.messagesSent === undefined ? undefined : prismaSession.messagesSent,
|
||||
avgResponseTime: prismaSession.avgResponseTime === undefined ? null : prismaSession.avgResponseTime,
|
||||
escalated: prismaSession.escalated === undefined ? undefined : prismaSession.escalated,
|
||||
forwardedHr: prismaSession.forwardedHr === undefined ? undefined : prismaSession.forwardedHr,
|
||||
tokens: prismaSession.tokens === undefined ? undefined : prismaSession.tokens,
|
||||
tokensEur: prismaSession.tokensEur === undefined ? undefined : prismaSession.tokensEur,
|
||||
initialMsg: prismaSession.initialMsg === undefined ? null : prismaSession.initialMsg,
|
||||
fullTranscriptUrl: prismaSession.fullTranscriptUrl === undefined ? null : prismaSession.fullTranscriptUrl,
|
||||
transcriptContent: prismaSession.transcriptContent === undefined ? null : prismaSession.transcriptContent,
|
||||
};
|
||||
|
||||
return res.status(200).json({ session });
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch session ${id}:`, error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "An unknown error occurred";
|
||||
return res
|
||||
.status(500)
|
||||
.json({ error: "Failed to fetch session", details: errorMessage });
|
||||
}
|
||||
}
|
||||
73
pages/api/dashboard/sessions.ts
Normal file
73
pages/api/dashboard/sessions.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { prisma } from "../../../lib/prisma";
|
||||
import { ChatSession } from "../../../lib/types";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(405).json({ error: "Method not allowed" });
|
||||
}
|
||||
|
||||
const { searchTerm } = req.query;
|
||||
|
||||
try {
|
||||
let prismaSessions;
|
||||
|
||||
if (searchTerm && typeof searchTerm === "string" && searchTerm.trim() !== "") {
|
||||
const searchConditions = [
|
||||
{ id: { contains: searchTerm, mode: "insensitive" } },
|
||||
{ category: { contains: searchTerm, mode: "insensitive" } },
|
||||
{ initialMsg: { contains: searchTerm, mode: "insensitive" } },
|
||||
{ transcriptContent: { contains: searchTerm, mode: "insensitive" } },
|
||||
];
|
||||
|
||||
prismaSessions = await prisma.session.findMany({
|
||||
where: {
|
||||
OR: searchConditions,
|
||||
},
|
||||
orderBy: {
|
||||
startTime: "desc",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
prismaSessions = await prisma.session.findMany({
|
||||
orderBy: {
|
||||
startTime: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const sessions: ChatSession[] = prismaSessions.map(ps => ({
|
||||
...ps,
|
||||
sessionId: ps.id,
|
||||
startTime: new Date(ps.startTime),
|
||||
endTime: ps.endTime ? new Date(ps.endTime) : null,
|
||||
createdAt: new Date(ps.createdAt),
|
||||
updatedAt: new Date(ps.updatedAt),
|
||||
userId: ps.userId === undefined ? null : ps.userId,
|
||||
category: ps.category === undefined ? null : ps.category,
|
||||
language: ps.language === undefined ? null : ps.language,
|
||||
country: ps.country === undefined ? null : ps.country,
|
||||
ipAddress: ps.ipAddress === undefined ? null : ps.ipAddress,
|
||||
sentiment: ps.sentiment === undefined ? null : ps.sentiment,
|
||||
messagesSent: ps.messagesSent === undefined ? undefined : ps.messagesSent,
|
||||
avgResponseTime: ps.avgResponseTime === undefined ? null : ps.avgResponseTime,
|
||||
escalated: ps.escalated === undefined ? undefined : ps.escalated,
|
||||
forwardedHr: ps.forwardedHr === undefined ? undefined : ps.forwardedHr,
|
||||
tokens: ps.tokens === undefined ? undefined : ps.tokens,
|
||||
tokensEur: ps.tokensEur === undefined ? undefined : ps.tokensEur,
|
||||
initialMsg: ps.initialMsg === undefined ? null : ps.initialMsg,
|
||||
fullTranscriptUrl: ps.fullTranscriptUrl === undefined ? null : ps.fullTranscriptUrl,
|
||||
transcriptContent: ps.transcriptContent === undefined ? null : ps.transcriptContent,
|
||||
}));
|
||||
|
||||
return res.status(200).json({ sessions });
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch sessions:", error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "An unknown error occurred";
|
||||
return res.status(500).json({ error: "Failed to fetch sessions", details: errorMessage });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user