mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 07:52:10 +01:00
feat: initialize project with Next.js, Prisma, and Tailwind CSS
- Add package.json with dependencies and scripts for Next.js and Prisma - Implement API routes for session management, user authentication, and company configuration - Create database schema for Company, User, and Session models in Prisma - Set up authentication with NextAuth and JWT - Add password reset functionality and user registration endpoint - Configure Tailwind CSS and PostCSS for styling - Implement metrics and dashboard settings API endpoints
This commit is contained in:
165
app/dashboard/page.tsx
Normal file
165
app/dashboard/page.tsx
Normal file
@ -0,0 +1,165 @@
|
||||
// Main dashboard page: metrics, refresh, config
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { signOut, useSession } from 'next-auth/react';
|
||||
import { SessionsLineChart, CategoriesBarChart } from '../../components/Charts';
|
||||
import DashboardSettings from './settings';
|
||||
import UserManagement from './users';
|
||||
|
||||
interface MetricsCardProps {
|
||||
label: string;
|
||||
value: string | number | null | undefined;
|
||||
}
|
||||
|
||||
function MetricsCard({ label, value }: MetricsCardProps) {
|
||||
return (
|
||||
<div className="bg-white rounded-xl p-4 shadow-md flex flex-col items-center">
|
||||
<span className="text-2xl font-bold">{value ?? '-'}</span>
|
||||
<span className="text-gray-500">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { data: session } = useSession();
|
||||
const [metrics, setMetrics] = useState<Record<string, unknown> | null>(null);
|
||||
const [company, setCompany] = useState<Record<string, unknown> | null>(null);
|
||||
// Loading state used in the fetchData function
|
||||
const [, setLoading] = useState<boolean>(false);
|
||||
const [csvUrl, setCsvUrl] = useState<string>('');
|
||||
const [refreshing, setRefreshing] = useState<boolean>(false);
|
||||
|
||||
const isAdmin = session?.user?.role === 'admin';
|
||||
const isAuditor = session?.user?.role === 'auditor';
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch metrics, company, and CSV URL on mount
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
const res = await fetch('/api/dashboard/metrics');
|
||||
const data = await res.json();
|
||||
setMetrics(data.metrics);
|
||||
setCompany(data.company);
|
||||
setCsvUrl(data.csvUrl);
|
||||
setLoading(false);
|
||||
};
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
async function handleRefresh() {
|
||||
if (isAuditor) return; // Prevent auditors from refreshing
|
||||
|
||||
setRefreshing(true);
|
||||
await fetch('/api/admin/refresh-sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ companyId: company?.id }),
|
||||
});
|
||||
setRefreshing(false);
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
async function handleSaveConfig() {
|
||||
if (isAuditor) return; // Prevent auditors from changing config
|
||||
|
||||
await fetch('/api/dashboard/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ csvUrl }),
|
||||
});
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-3xl font-bold">Analytics Dashboard</h1>
|
||||
<button className="text-sm underline" onClick={() => signOut()}>
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Admin-only settings and user management */}
|
||||
{company && isAdmin && (
|
||||
<>
|
||||
<DashboardSettings company={company} session={session} />
|
||||
<UserManagement session={session} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="bg-white p-4 rounded-xl shadow mb-6 flex items-center gap-4">
|
||||
<input
|
||||
className="flex-1 px-3 py-2 rounded border"
|
||||
value={csvUrl}
|
||||
onChange={(e) => setCsvUrl(e.target.value)}
|
||||
placeholder="CSV feed URL (with basic auth if set in backend)"
|
||||
readOnly={isAuditor}
|
||||
/>
|
||||
{!isAuditor && (
|
||||
<>
|
||||
<button
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded"
|
||||
onClick={handleSaveConfig}
|
||||
>
|
||||
Save Config
|
||||
</button>
|
||||
<button
|
||||
className="px-4 py-2 bg-green-600 text-white rounded"
|
||||
onClick={handleRefresh}
|
||||
disabled={refreshing}
|
||||
>
|
||||
{refreshing ? 'Refreshing...' : 'Manual Refresh'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-10">
|
||||
<MetricsCard label="Total Sessions" value={metrics?.totalSessions} />
|
||||
<MetricsCard label="Escalated" value={metrics?.escalatedCount} />
|
||||
<MetricsCard
|
||||
label="Avg. Sentiment"
|
||||
value={metrics?.avgSentiment?.toFixed(2)}
|
||||
/>
|
||||
<MetricsCard
|
||||
label="Total Tokens (€)"
|
||||
value={metrics?.totalTokensEur?.toFixed(2)}
|
||||
/>
|
||||
<MetricsCard
|
||||
label="Below Sentiment Threshold"
|
||||
value={metrics?.belowSentimentThreshold}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div>
|
||||
<h2 className="font-bold mb-2">Sessions Per Day</h2>
|
||||
{(
|
||||
metrics?.sessionsPerDay &&
|
||||
Object.keys(metrics.sessionsPerDay).length > 0
|
||||
) ?
|
||||
<SessionsLineChart sessionsPerDay={metrics.sessionsPerDay} />
|
||||
: <span>No data</span>}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="font-bold mb-2">Top Categories</h2>
|
||||
{metrics?.categories && Object.keys(metrics.categories).length > 0 ?
|
||||
<CategoriesBarChart categories={metrics.categories} />
|
||||
: <span>No data</span>}
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="font-bold mb-2">Languages</h2>
|
||||
{metrics?.languages ?
|
||||
Object.entries(metrics.languages).map(([lang, n]) => (
|
||||
<div key={lang} className="flex justify-between">
|
||||
<span>{lang}</span>
|
||||
<span>{String(n)}</span>
|
||||
</div>
|
||||
))
|
||||
: <span>No data</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
82
app/dashboard/settings.tsx
Normal file
82
app/dashboard/settings.tsx
Normal file
@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { Company } from '../../lib/types';
|
||||
import { Session } from 'next-auth';
|
||||
|
||||
interface DashboardSettingsProps {
|
||||
company: Company;
|
||||
session: Session;
|
||||
}
|
||||
|
||||
export default function DashboardSettings({
|
||||
company,
|
||||
session,
|
||||
}: DashboardSettingsProps) {
|
||||
const [csvUrl, setCsvUrl] = useState<string>(company.csvUrl);
|
||||
const [csvUsername, setCsvUsername] = useState<string>(
|
||||
company.csvUsername || ''
|
||||
);
|
||||
const [csvPassword, setCsvPassword] = useState<string>('');
|
||||
const [sentimentThreshold, setSentimentThreshold] = useState<string>(
|
||||
company.sentimentAlert?.toString() || ''
|
||||
);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
|
||||
async function handleSave() {
|
||||
const res = await fetch('/api/dashboard/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
csvUrl,
|
||||
csvUsername,
|
||||
csvPassword,
|
||||
sentimentThreshold,
|
||||
}),
|
||||
});
|
||||
if (res.ok) setMessage('Settings saved!');
|
||||
else setMessage('Failed.');
|
||||
}
|
||||
|
||||
if (session.user.role !== 'admin') return null;
|
||||
|
||||
return (
|
||||
<div className="bg-white p-6 rounded-xl shadow mb-6">
|
||||
<h2 className="font-bold text-lg mb-4">Company Config</h2>
|
||||
<div className="grid gap-4">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
placeholder="CSV URL"
|
||||
value={csvUrl}
|
||||
onChange={(e) => setCsvUrl(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
placeholder="CSV Username"
|
||||
value={csvUsername}
|
||||
onChange={(e) => setCsvUsername(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="password"
|
||||
placeholder="CSV Password"
|
||||
value={csvPassword}
|
||||
onChange={(e) => setCsvPassword(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
placeholder="Sentiment Alert Threshold"
|
||||
type="number"
|
||||
value={sentimentThreshold}
|
||||
onChange={(e) => setSentimentThreshold(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
className="bg-blue-600 text-white rounded py-2"
|
||||
onClick={handleSave}
|
||||
>
|
||||
Save Settings
|
||||
</button>
|
||||
<div>{message}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
76
app/dashboard/users.tsx
Normal file
76
app/dashboard/users.tsx
Normal file
@ -0,0 +1,76 @@
|
||||
'use client';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { UserSession } from '../../lib/types';
|
||||
|
||||
interface UserItem {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
interface UserManagementProps {
|
||||
session: UserSession;
|
||||
}
|
||||
|
||||
export default function UserManagement({ session }: UserManagementProps) {
|
||||
const [users, setUsers] = useState<UserItem[]>([]);
|
||||
const [email, setEmail] = useState<string>('');
|
||||
const [role, setRole] = useState<string>('user');
|
||||
const [msg, setMsg] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/dashboard/users')
|
||||
.then((r) => r.json())
|
||||
.then((data) => setUsers(data.users));
|
||||
}, []);
|
||||
|
||||
async function inviteUser() {
|
||||
const res = await fetch('/api/dashboard/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, role }),
|
||||
});
|
||||
if (res.ok) setMsg('User invited.');
|
||||
else setMsg('Failed.');
|
||||
}
|
||||
|
||||
if (session.user.role !== 'admin') return null;
|
||||
|
||||
return (
|
||||
<div className="bg-white p-6 rounded-xl shadow mb-6">
|
||||
<h2 className="font-bold text-lg mb-4">User Management</h2>
|
||||
<div className="flex gap-2 mb-3">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="border px-3 py-2 rounded"
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
>
|
||||
<option value="user">User</option>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="auditor">Auditor</option>
|
||||
</select>
|
||||
<button
|
||||
className="bg-blue-600 text-white rounded px-4"
|
||||
onClick={inviteUser}
|
||||
>
|
||||
Invite
|
||||
</button>
|
||||
</div>
|
||||
<div>{msg}</div>
|
||||
<ul className="mt-4">
|
||||
{users.map((u) => (
|
||||
<li key={u.id} className="flex justify-between border-b py-1">
|
||||
{u.email}{' '}
|
||||
<span className="text-xs bg-gray-200 px-2 rounded">{u.role}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
app/forgot-password/page.tsx
Normal file
38
app/forgot-password/page.tsx
Normal file
@ -0,0 +1,38 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const [email, setEmail] = useState<string>('');
|
||||
const [message, setMessage] = useState<string>('');
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const res = await fetch('/api/forgot-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
if (res.ok) setMessage('If that email exists, a reset link has been sent.');
|
||||
else setMessage('Failed. Try again.');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
|
||||
<h1 className="text-2xl font-bold mb-6">Forgot Password</h1>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<button className="bg-blue-600 text-white rounded py-2" type="submit">
|
||||
Send Reset Link
|
||||
</button>
|
||||
</form>
|
||||
<div className="mt-4 text-green-700">{message}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
app/globals.css
Normal file
9
app/globals.css
Normal file
@ -0,0 +1,9 @@
|
||||
body {
|
||||
font-family: system-ui, sans-serif;
|
||||
background: #f3f4f6;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
font-family: inherit;
|
||||
}
|
||||
19
app/layout.tsx
Normal file
19
app/layout.tsx
Normal file
@ -0,0 +1,19 @@
|
||||
// Main app layout with basic global style
|
||||
import './globals.css';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
export const metadata = {
|
||||
title: 'LiveDash-Node',
|
||||
description:
|
||||
'Multi-tenant dashboard system for tracking chat session metrics',
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="bg-gray-100 min-h-screen font-sans">
|
||||
<div className="max-w-5xl mx-auto py-8">{children}</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
60
app/login/page.tsx
Normal file
60
app/login/page.tsx
Normal file
@ -0,0 +1,60 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { signIn } from 'next-auth/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const router = useRouter();
|
||||
|
||||
async function handleLogin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const res = await signIn('credentials', {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
});
|
||||
if (res?.ok) router.push('/dashboard');
|
||||
else setError('Invalid credentials.');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
|
||||
<h1 className="text-2xl font-bold mb-6">Login</h1>
|
||||
{error && <div className="text-red-600 mb-3">{error}</div>}
|
||||
<form onSubmit={handleLogin} className="flex flex-col gap-4">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="email"
|
||||
placeholder="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<button className="bg-blue-600 text-white rounded py-2" type="submit">
|
||||
Login
|
||||
</button>
|
||||
</form>
|
||||
<div className="mt-4 text-center">
|
||||
<a href="/register" className="text-blue-600 underline">
|
||||
Register company
|
||||
</a>
|
||||
</div>
|
||||
<div className="mt-2 text-center">
|
||||
<a href="/forgot-password" className="text-blue-600 underline">
|
||||
Forgot password?
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
app/page.tsx
Normal file
9
app/page.tsx
Normal file
@ -0,0 +1,9 @@
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { authOptions } from '../pages/api/auth/[...nextauth]';
|
||||
|
||||
export default async function HomePage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (session?.user) redirect('/dashboard');
|
||||
else redirect('/login');
|
||||
}
|
||||
77
app/register/page.tsx
Normal file
77
app/register/page.tsx
Normal file
@ -0,0 +1,77 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const [email, setEmail] = useState<string>('');
|
||||
const [company, setCompany] = useState<string>('');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [csvUrl, setCsvUrl] = useState<string>('');
|
||||
const [role, setRole] = useState<string>('admin'); // Default to admin for company registration
|
||||
const [error, setError] = useState<string>('');
|
||||
const router = useRouter();
|
||||
|
||||
async function handleRegister(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const res = await fetch('/api/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, company, csvUrl, role }),
|
||||
});
|
||||
if (res.ok) router.push('/login');
|
||||
else setError('Registration failed.');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
|
||||
<h1 className="text-2xl font-bold mb-6">Register Company</h1>
|
||||
{error && <div className="text-red-600 mb-3">{error}</div>}
|
||||
<form onSubmit={handleRegister} className="flex flex-col gap-4">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="text"
|
||||
placeholder="Company Name"
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="email"
|
||||
placeholder="Admin Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="text"
|
||||
placeholder="CSV URL"
|
||||
value={csvUrl}
|
||||
onChange={(e) => setCsvUrl(e.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="border px-3 py-2 rounded"
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
required
|
||||
>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="user">User</option>
|
||||
<option value="auditor">Auditor</option>
|
||||
</select>
|
||||
<button className="bg-blue-600 text-white rounded py-2" type="submit">
|
||||
Register & Continue
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
app/reset-password/page.tsx
Normal file
44
app/reset-password/page.tsx
Normal file
@ -0,0 +1,44 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get('token');
|
||||
const [password, setPassword] = useState<string>('');
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const router = useRouter();
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const res = await fetch('/api/reset-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, password }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setMessage('Password reset! Redirecting to login...');
|
||||
setTimeout(() => router.push('/login'), 2000);
|
||||
} else setMessage('Invalid or expired link.');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
|
||||
<h1 className="text-2xl font-bold mb-6">Reset Password</h1>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<input
|
||||
className="border px-3 py-2 rounded"
|
||||
type="password"
|
||||
placeholder="New Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<button className="bg-blue-600 text-white rounded py-2" type="submit">
|
||||
Reset Password
|
||||
</button>
|
||||
</form>
|
||||
<div className="mt-4 text-green-700">{message}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user