admin panel

This commit is contained in:
2024-02-14 16:23:15 +01:00
parent 9900c44195
commit 72313304fe
5 changed files with 458 additions and 0 deletions

118
pages/admin/index.tsx Normal file
View File

@@ -0,0 +1,118 @@
import { useState, useEffect } from 'react'
import type { NextPage } from 'next'
import Head from 'next/head'
interface DashboardStats {
total_sources: number
pending_sources: number
pending_reports: number
high_risk_sources: number
sources_added_week: number
reports_today: number
}
const AdminDashboard: NextPage = () => {
const [stats, setStats] = useState<DashboardStats | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchStats()
}, [])
const fetchStats = async () => {
try {
const response = await fetch('/api/admin/dashboard')
if (response.ok) {
const data = await response.json()
setStats(data)
}
} catch (error) {
console.error('Failed to fetch stats:', error)
} finally {
setLoading(false)
}
}
if (loading) {
return (
<div>
<Head>
<title>Admin Panel - Infohliadka</title>
</Head>
<div>Loading...</div>
</div>
)
}
return (
<div>
<Head>
<title>Admin Panel - Infohliadka</title>
</Head>
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<h1>Admin Dashboard</h1>
{stats && (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '20px', marginTop: '30px' }}>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Celkové zdroje</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold' }}>{stats.total_sources}</div>
</div>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Čakajúce schválenie</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#f59e0b' }}>{stats.pending_sources}</div>
</div>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Vysoké riziko</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#ef4444' }}>{stats.high_risk_sources}</div>
</div>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Nové hlásenia</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold', color: '#3b82f6' }}>{stats.pending_reports}</div>
</div>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Pridané tento týždeň</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold' }}>{stats.sources_added_week}</div>
</div>
<div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
<h3>Hlásenia dnes</h3>
<div style={{ fontSize: '24px', fontWeight: 'bold' }}>{stats.reports_today}</div>
</div>
</div>
)}
<div style={{ marginTop: '40px' }}>
<h2>Rýchle akcie</h2>
<div style={{ display: 'flex', gap: '15px', marginTop: '20px' }}>
<a href="/admin/sources" style={{
padding: '12px 24px',
backgroundColor: '#3b82f6',
color: 'white',
textDecoration: 'none',
borderRadius: '6px'
}}>
Správa zdrojov
</a>
<a href="/admin/reports" style={{
padding: '12px 24px',
backgroundColor: '#10b981',
color: 'white',
textDecoration: 'none',
borderRadius: '6px'
}}>
Hlásenia
</a>
</div>
</div>
</div>
</div>
)
}
export default AdminDashboard

176
pages/admin/sources.tsx Normal file
View File

@@ -0,0 +1,176 @@
import { useState, useEffect } from 'react'
import type { NextPage } from 'next'
import Head from 'next/head'
interface Source {
id: number
url: string
domain: string
title?: string
type: string
status: string
risk_level: number
created_at: string
}
const SourcesManagement: NextPage = () => {
const [sources, setSources] = useState<Source[]>([])
const [loading, setLoading] = useState(true)
const [filter, setFilter] = useState('pending')
useEffect(() => {
fetchSources()
}, [filter])
const fetchSources = async () => {
try {
const response = await fetch(`/api/admin/sources?status=${filter}`)
if (response.ok) {
const data = await response.json()
setSources(data)
}
} catch (error) {
console.error('Failed to fetch sources:', error)
} finally {
setLoading(false)
}
}
const updateSource = async (id: number, status: string, riskLevel: number) => {
try {
const response = await fetch(`/api/admin/sources/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
status,
risk_level: riskLevel,
}),
})
if (response.ok) {
fetchSources() // Refresh the list
}
} catch (error) {
console.error('Failed to update source:', error)
}
}
const getRiskColor = (level: number) => {
if (level >= 4) return '#ef4444'
if (level >= 3) return '#f59e0b'
return '#6b7280'
}
return (
<div>
<Head>
<title>Správa zdrojov - Infohliadka</title>
</Head>
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<h1>Správa zdrojov</h1>
<div style={{ marginBottom: '20px' }}>
<label>Filter: </label>
<select
value={filter}
onChange={(e) => setFilter(e.target.value)}
style={{ padding: '8px', marginLeft: '10px' }}
>
<option value="pending">Čakajúce</option>
<option value="verified">Schválené</option>
<option value="rejected">Zamietnuté</option>
</select>
</div>
{loading ? (
<div>Loading...</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ backgroundColor: '#f3f4f6' }}>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Doména</th>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Typ</th>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Riziko</th>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Status</th>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Dátum</th>
<th style={{ padding: '12px', textAlign: 'left', border: '1px solid #d1d5db' }}>Akcie</th>
</tr>
</thead>
<tbody>
{sources.map((source) => (
<tr key={source.id}>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
<a href={source.url} target="_blank" rel="noopener noreferrer">
{source.domain}
</a>
</td>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>{source.type}</td>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
<span style={{ color: getRiskColor(source.risk_level), fontWeight: 'bold' }}>
{source.risk_level}
</span>
</td>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>{source.status}</td>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
{new Date(source.created_at).toLocaleDateString('sk-SK')}
</td>
<td style={{ padding: '12px', border: '1px solid #d1d5db' }}>
{source.status === 'pending' && (
<div style={{ display: 'flex', gap: '5px' }}>
<button
onClick={() => updateSource(source.id, 'verified', source.risk_level)}
style={{
padding: '4px 8px',
backgroundColor: '#10b981',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Schváliť
</button>
<button
onClick={() => updateSource(source.id, 'rejected', 0)}
style={{
padding: '4px 8px',
backgroundColor: '#ef4444',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
Zamietnuť
</button>
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div style={{ marginTop: '30px' }}>
<a href="/admin" style={{
padding: '10px 20px',
backgroundColor: '#6b7280',
color: 'white',
textDecoration: 'none',
borderRadius: '6px'
}}>
Späť na dashboard
</a>
</div>
</div>
</div>
)
}
export default SourcesManagement

View File

@@ -0,0 +1,72 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import sqlite3 from 'sqlite3'
import path from 'path'
interface DashboardStats {
total_sources: number
pending_sources: number
pending_reports: number
high_risk_sources: number
sources_added_week: number
reports_today: number
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<DashboardStats | { error: string }>
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
const db = new sqlite3.Database(dbPath)
try {
const stats = await new Promise<DashboardStats>((resolve, reject) => {
const queries = [
"SELECT COUNT(*) as total_sources FROM sources WHERE status = 'verified'",
"SELECT COUNT(*) as pending_sources FROM sources WHERE status = 'pending'",
"SELECT COUNT(*) as pending_reports FROM reports WHERE status = 'pending'",
"SELECT COUNT(*) as high_risk_sources FROM sources WHERE status = 'verified' AND risk_level >= 4",
"SELECT COUNT(*) as sources_added_week FROM sources WHERE created_at > datetime('now', '-7 days')",
"SELECT COUNT(*) as reports_today FROM reports WHERE created_at > datetime('now', '-1 day')"
]
const results: any = {}
let completed = 0
queries.forEach((query, index) => {
db.get(query, (err, row: any) => {
if (err) {
reject(err)
return
}
const key = Object.keys(row)[0]
results[key] = row[key]
completed++
if (completed === queries.length) {
resolve({
total_sources: results.total_sources || 0,
pending_sources: results.pending_sources || 0,
pending_reports: results.pending_reports || 0,
high_risk_sources: results.high_risk_sources || 0,
sources_added_week: results.sources_added_week || 0,
reports_today: results.reports_today || 0
})
}
})
})
})
return res.status(200).json(stats)
} catch (error) {
console.error('Database error:', error)
return res.status(500).json({ error: 'Internal server error' })
} finally {
db.close()
}
}

View File

@@ -0,0 +1,49 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import sqlite3 from 'sqlite3'
import path from 'path'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'PATCH') {
return res.status(405).json({ error: 'Method not allowed' })
}
const { id } = req.query
const { status, risk_level, rejection_reason } = req.body
if (!id || !status) {
return res.status(400).json({ error: 'ID and status are required' })
}
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
const db = new sqlite3.Database(dbPath)
try {
await new Promise<void>((resolve, reject) => {
const query = `
UPDATE sources
SET status = ?, risk_level = ?, rejection_reason = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`
db.run(
query,
[status, risk_level || 0, rejection_reason || null, id],
function(err) {
if (err) reject(err)
else resolve()
}
)
})
return res.status(200).json({ success: true })
} catch (error) {
console.error('Database error:', error)
return res.status(500).json({ error: 'Internal server error' })
} finally {
db.close()
}
}

View File

@@ -0,0 +1,43 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import sqlite3 from 'sqlite3'
import path from 'path'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' })
}
const { status = 'pending', page = '1', limit = '20' } = req.query
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
const db = new sqlite3.Database(dbPath)
try {
const sources = await new Promise<any[]>((resolve, reject) => {
const offset = (parseInt(page as string) - 1) * parseInt(limit as string)
db.all(
`SELECT * FROM sources
WHERE status = ?
ORDER BY created_at DESC
LIMIT ? OFFSET ?`,
[status, parseInt(limit as string), offset],
(err, rows) => {
if (err) reject(err)
else resolve(rows)
}
)
})
return res.status(200).json(sources)
} catch (error) {
console.error('Database error:', error)
return res.status(500).json({ error: 'Internal server error' })
} finally {
db.close()
}
}