feat: добавлена админ-панель и главная страница с навигацией по курсам
Основные изменения: Админ-панель: - Создана защищенная паролем админ-панель по пути /admin - Реализована система авторизации с сессионными куками - Добавлен CRUD для управления группами (создание, редактирование, удаление) - Добавлено поле "курс" (1-5) для каждой группы с возможностью редактирования Структура данных: - Миграция групп из TypeScript файла в JSON формат (groups.json) - Обновлена структура данных: добавлено поле course - Реализована автоматическая миграция старых данных в новый формат - Создан groups-loader для работы с JSON файлом Главная страница: - Создана главная страница с аккордеоном по курсам (1-5) - Группы сгруппированы по курсам для удобной навигации - Добавлены кнопки: "Добавить группу", переключение темы и GitHub - Убрана верхняя навигация с главной страницы Навигация: - Добавлена кнопка "К группам" в начало навигации на страницах расписания - На мобильных устройствах скрыты кнопки групп, оставлена только кнопка возврата - Улучшена адаптивность навигации Технические улучшения: - Исправлена проблема с tailwind-scrollbar-hide (заменен плагин на CSS класс) - Обновлены все компоненты для работы с новой структурой данных групп - Добавлена поддержка переменных окружения ADMIN_PASSWORD и ADMIN_SESSION_SECRET
This commit is contained in:
@@ -5,7 +5,7 @@ import { getSchedule } from '@/app/agregator/schedule'
|
||||
import { NextSerialized, nextDeserialized, nextSerialized } from '@/app/utils/date-serializer'
|
||||
import { NavBar } from '@/widgets/navbar'
|
||||
import { LastUpdateAt } from '@/entities/last-update-at'
|
||||
import { groups } from '@/shared/data/groups'
|
||||
import { loadGroups, GroupsData } from '@/shared/data/groups-loader'
|
||||
import { SITE_URL } from '@/shared/constants/urls'
|
||||
import crypto from 'crypto'
|
||||
import React from 'react'
|
||||
@@ -20,10 +20,11 @@ type PageProps = {
|
||||
}
|
||||
parsedAt: Date
|
||||
cacheAvailableFor: string[]
|
||||
groups: GroupsData
|
||||
}
|
||||
|
||||
export default function HomePage(props: NextSerialized<PageProps>) {
|
||||
const { schedule, group, cacheAvailableFor, parsedAt } = nextDeserialized<PageProps>(props)
|
||||
const { schedule, group, cacheAvailableFor, parsedAt, groups } = nextDeserialized<PageProps>(props)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (typeof window === 'undefined') return
|
||||
@@ -47,7 +48,7 @@ export default function HomePage(props: NextSerialized<PageProps>) {
|
||||
<meta property="og:title" content={`Группа ${group.name} — Расписание занятий в Колледже Связи`} />
|
||||
<meta property="og:description" content={`Расписание занятий группы ${group.name} на неделю в Колледже Связи ПГУТИ. Расписание пар, материалы для подготовки и изменения в расписании.`} />
|
||||
</Head>
|
||||
<NavBar cacheAvailableFor={cacheAvailableFor} />
|
||||
<NavBar cacheAvailableFor={cacheAvailableFor} groups={groups} />
|
||||
<LastUpdateAt date={parsedAt} />
|
||||
<Schedule days={schedule} />
|
||||
</>
|
||||
@@ -57,6 +58,7 @@ export default function HomePage(props: NextSerialized<PageProps>) {
|
||||
const cachedSchedules = new Map<string, { lastFetched: Date, results: Day[] }>()
|
||||
const maxCacheDurationInMS = 1000 * 60 * 60
|
||||
export async function getServerSideProps(context: GetServerSidePropsContext<{ group: string }>): Promise<GetServerSidePropsResult<NextSerialized<PageProps>>> {
|
||||
const groups = loadGroups()
|
||||
const group = context.params?.group
|
||||
if (group && Object.hasOwn(groups, group) && group in groups) {
|
||||
let schedule
|
||||
@@ -68,7 +70,8 @@ export async function getServerSideProps(context: GetServerSidePropsContext<{ gr
|
||||
parsedAt = cachedSchedule.lastFetched
|
||||
} else {
|
||||
try {
|
||||
schedule = await getSchedule(...groups[group])
|
||||
const groupInfo = groups[group]
|
||||
schedule = await getSchedule(groupInfo.parseId, groupInfo.name)
|
||||
parsedAt = new Date()
|
||||
cachedSchedules.set(group, { lastFetched: new Date(), results: schedule })
|
||||
} catch(e) {
|
||||
@@ -109,9 +112,10 @@ export async function getServerSideProps(context: GetServerSidePropsContext<{ gr
|
||||
parsedAt: parsedAt,
|
||||
group: {
|
||||
id: group,
|
||||
name: groups[group][1]
|
||||
name: groups[group].name
|
||||
},
|
||||
cacheAvailableFor
|
||||
cacheAvailableFor,
|
||||
groups
|
||||
})
|
||||
}
|
||||
} else {
|
||||
|
||||
525
src/pages/admin.tsx
Normal file
525
src/pages/admin.tsx
Normal file
@@ -0,0 +1,525 @@
|
||||
import React from 'react'
|
||||
import { GetServerSideProps } from 'next'
|
||||
import { Button } from '@/shadcn/ui/button'
|
||||
import { Input } from '@/shadcn/ui/input'
|
||||
import { Label } from '@/shadcn/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/shadcn/ui/card'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/shadcn/ui/dialog'
|
||||
import { loadGroups, GroupsData } from '@/shared/data/groups-loader'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shadcn/ui/select'
|
||||
import Head from 'next/head'
|
||||
|
||||
type AdminPageProps = {
|
||||
groups: GroupsData
|
||||
}
|
||||
|
||||
export default function AdminPage({ groups: initialGroups }: AdminPageProps) {
|
||||
const [authenticated, setAuthenticated] = React.useState<boolean | null>(null)
|
||||
const [password, setPassword] = React.useState('')
|
||||
const [loading, setLoading] = React.useState(false)
|
||||
const [error, setError] = React.useState<string | null>(null)
|
||||
const [groups, setGroups] = React.useState<GroupsData>(initialGroups)
|
||||
const [editingGroup, setEditingGroup] = React.useState<{ id: string; parseId: number; name: string; course: number } | null>(null)
|
||||
const [showAddDialog, setShowAddDialog] = React.useState(false)
|
||||
const [showEditDialog, setShowEditDialog] = React.useState(false)
|
||||
const [showDeleteDialog, setShowDeleteDialog] = React.useState(false)
|
||||
const [groupToDelete, setGroupToDelete] = React.useState<string | null>(null)
|
||||
|
||||
// Форма добавления/редактирования
|
||||
const [formData, setFormData] = React.useState({
|
||||
id: '',
|
||||
parseId: '',
|
||||
name: '',
|
||||
course: '1'
|
||||
})
|
||||
|
||||
// Проверка авторизации при загрузке
|
||||
React.useEffect(() => {
|
||||
checkAuth()
|
||||
}, [])
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/check-auth')
|
||||
const data = await res.json()
|
||||
setAuthenticated(data.authenticated)
|
||||
} catch (err) {
|
||||
setAuthenticated(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password })
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
if (res.ok && data.success) {
|
||||
setAuthenticated(true)
|
||||
setPassword('')
|
||||
// Обновляем список групп после авторизации
|
||||
await loadGroupsList()
|
||||
} else {
|
||||
setError(data.error || 'Ошибка авторизации')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка соединения с сервером')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadGroupsList = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/groups')
|
||||
const data = await res.json()
|
||||
if (data.groups) {
|
||||
setGroups(data.groups)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error loading groups:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddGroup = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/groups', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
id: formData.id,
|
||||
parseId: parseInt(formData.parseId, 10),
|
||||
name: formData.name,
|
||||
course: parseInt(formData.course, 10)
|
||||
})
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
if (res.ok && data.success) {
|
||||
setGroups(data.groups)
|
||||
setShowAddDialog(false)
|
||||
setFormData({ id: '', parseId: '', name: '', course: '1' })
|
||||
} else {
|
||||
setError(data.error || 'Ошибка при добавлении группы')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка соединения с сервером')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEditGroup = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!editingGroup) return
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/groups/${editingGroup.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
parseId: parseInt(formData.parseId, 10),
|
||||
name: formData.name,
|
||||
course: parseInt(formData.course, 10)
|
||||
})
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
if (res.ok && data.success) {
|
||||
setGroups(data.groups)
|
||||
setShowEditDialog(false)
|
||||
setEditingGroup(null)
|
||||
setFormData({ id: '', parseId: '', name: '', course: '1' })
|
||||
} else {
|
||||
setError(data.error || 'Ошибка при редактировании группы')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка соединения с сервером')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteGroup = async () => {
|
||||
if (!groupToDelete) return
|
||||
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/groups/${groupToDelete}`, {
|
||||
method: 'DELETE'
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
if (res.ok && data.success) {
|
||||
setGroups(data.groups)
|
||||
setShowDeleteDialog(false)
|
||||
setGroupToDelete(null)
|
||||
} else {
|
||||
setError(data.error || 'Ошибка при удалении группы')
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Ошибка соединения с сервером')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openEditDialog = (id: string) => {
|
||||
const group = groups[id]
|
||||
if (group) {
|
||||
setEditingGroup({ id, parseId: group.parseId, name: group.name, course: group.course })
|
||||
setFormData({ id, parseId: group.parseId.toString(), name: group.name, course: group.course.toString() })
|
||||
setShowEditDialog(true)
|
||||
}
|
||||
}
|
||||
|
||||
const openDeleteDialog = (id: string) => {
|
||||
setGroupToDelete(id)
|
||||
setShowDeleteDialog(true)
|
||||
}
|
||||
|
||||
if (authenticated === null) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div>Загрузка...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Админ-панель — Авторизация</title>
|
||||
</Head>
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader>
|
||||
<CardTitle>Авторизация</CardTitle>
|
||||
<CardDescription>Введите пароль для доступа к админ-панели</CardDescription>
|
||||
</CardHeader>
|
||||
<form onSubmit={handleLogin}>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 bg-destructive/10 text-destructive rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Пароль</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardFooter>
|
||||
<Button type="submit" disabled={loading} className="w-full">
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Админ-панель — Управление группами</title>
|
||||
</Head>
|
||||
<div className="min-h-screen p-4 md:p-8">
|
||||
<div className="max-w-6xl mx-auto space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-3xl font-bold">Админ-панель</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await fetch('/api/admin/logout', { method: 'POST' })
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err)
|
||||
}
|
||||
setAuthenticated(false)
|
||||
}}
|
||||
>
|
||||
Выйти
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-destructive/10 text-destructive rounded-md">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<CardTitle>Группы</CardTitle>
|
||||
<CardDescription>Управление группами для расписания</CardDescription>
|
||||
</div>
|
||||
<Button onClick={() => setShowAddDialog(true)}>
|
||||
Добавить группу
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{Object.keys(groups).length === 0 ? (
|
||||
<p className="text-muted-foreground">Группы не найдены</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{Object.entries(groups).map(([id, group]) => (
|
||||
<div
|
||||
key={id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<div className="font-semibold">{group.name}</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
ID: {id} | Parse ID: {group.parseId} | Курс: {group.course}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditDialog(id)}
|
||||
>
|
||||
Редактировать
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => openDeleteDialog(id)}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Диалог добавления группы */}
|
||||
<Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Добавить группу</DialogTitle>
|
||||
<DialogDescription>
|
||||
Заполните данные для новой группы
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleAddGroup}>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-id">ID группы (slug)</Label>
|
||||
<Input
|
||||
id="add-id"
|
||||
value={formData.id}
|
||||
onChange={(e) => setFormData({ ...formData, id: e.target.value })}
|
||||
placeholder="ib4k"
|
||||
required
|
||||
pattern="[a-z0-9_-]+"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Только строчные буквы, цифры, дефисы и подчеркивания
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-parse-id">ID для парсинга</Label>
|
||||
<Input
|
||||
id="add-parse-id"
|
||||
type="number"
|
||||
value={formData.parseId}
|
||||
onChange={(e) => setFormData({ ...formData, parseId: e.target.value })}
|
||||
placeholder="138"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-name">Название группы</Label>
|
||||
<Input
|
||||
id="add-name"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
placeholder="ИБ-4к"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="add-course">Курс</Label>
|
||||
<Select
|
||||
value={formData.course}
|
||||
onValueChange={(value) => setFormData({ ...formData, course: value })}
|
||||
>
|
||||
<SelectTrigger id="add-course">
|
||||
<SelectValue placeholder="Выберите курс" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">1 курс</SelectItem>
|
||||
<SelectItem value="2">2 курс</SelectItem>
|
||||
<SelectItem value="3">3 курс</SelectItem>
|
||||
<SelectItem value="4">4 курс</SelectItem>
|
||||
<SelectItem value="5">5 курс</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setShowAddDialog(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Сохранение...' : 'Добавить'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Диалог редактирования группы */}
|
||||
<Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Редактировать группу</DialogTitle>
|
||||
<DialogDescription>
|
||||
Измените данные группы
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleEditGroup}>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-id">ID группы</Label>
|
||||
<Input
|
||||
id="edit-id"
|
||||
value={editingGroup?.id || ''}
|
||||
disabled
|
||||
className="bg-muted"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
ID группы нельзя изменить
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-parse-id">ID для парсинга</Label>
|
||||
<Input
|
||||
id="edit-parse-id"
|
||||
type="number"
|
||||
value={formData.parseId}
|
||||
onChange={(e) => setFormData({ ...formData, parseId: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-name">Название группы</Label>
|
||||
<Input
|
||||
id="edit-name"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-course">Курс</Label>
|
||||
<Select
|
||||
value={formData.course}
|
||||
onValueChange={(value) => setFormData({ ...formData, course: value })}
|
||||
>
|
||||
<SelectTrigger id="edit-course">
|
||||
<SelectValue placeholder="Выберите курс" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1">1 курс</SelectItem>
|
||||
<SelectItem value="2">2 курс</SelectItem>
|
||||
<SelectItem value="3">3 курс</SelectItem>
|
||||
<SelectItem value="4">4 курс</SelectItem>
|
||||
<SelectItem value="5">5 курс</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setShowEditDialog(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? 'Сохранение...' : 'Сохранить'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Диалог удаления группы */}
|
||||
<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Удалить группу?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Вы уверены, что хотите удалить группу "{groupToDelete && groups[groupToDelete]?.name}"?
|
||||
Это действие нельзя отменить.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setShowDeleteDialog(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={handleDeleteGroup} disabled={loading}>
|
||||
{loading ? 'Удаление...' : 'Удалить'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<AdminPageProps> = async () => {
|
||||
const groups = loadGroups()
|
||||
return {
|
||||
props: {
|
||||
groups
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
20
src/pages/api/admin/check-auth.ts
Normal file
20
src/pages/api/admin/check-auth.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { checkAuth } from '@/shared/utils/auth'
|
||||
|
||||
type ResponseData = {
|
||||
authenticated: boolean
|
||||
}
|
||||
|
||||
export default function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
if (req.method !== 'GET') {
|
||||
res.status(405).json({ authenticated: false })
|
||||
return
|
||||
}
|
||||
|
||||
const authenticated = checkAuth(req)
|
||||
res.status(200).json({ authenticated })
|
||||
}
|
||||
|
||||
88
src/pages/api/admin/groups.ts
Normal file
88
src/pages/api/admin/groups.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { requireAuth } from '@/shared/utils/auth'
|
||||
import { loadGroups, saveGroups, GroupsData } from '@/shared/data/groups-loader'
|
||||
|
||||
type ResponseData = {
|
||||
groups?: GroupsData
|
||||
success?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
if (req.method === 'GET') {
|
||||
// Получение списка групп
|
||||
const groups = loadGroups()
|
||||
res.status(200).json({ groups })
|
||||
return
|
||||
}
|
||||
|
||||
if (req.method === 'POST') {
|
||||
// Добавление новой группы
|
||||
const { id, parseId, name, course } = req.body
|
||||
|
||||
if (!id || typeof id !== 'string') {
|
||||
res.status(400).json({ error: 'Group ID is required' })
|
||||
return
|
||||
}
|
||||
|
||||
if (!parseId || typeof parseId !== 'number') {
|
||||
res.status(400).json({ error: 'Parse ID must be a number' })
|
||||
return
|
||||
}
|
||||
|
||||
if (!name || typeof name !== 'string') {
|
||||
res.status(400).json({ error: 'Group name is required' })
|
||||
return
|
||||
}
|
||||
|
||||
// Валидация курса (1-5)
|
||||
const groupCourse = course !== undefined ? Number(course) : 1
|
||||
if (!Number.isInteger(groupCourse) || groupCourse < 1 || groupCourse > 5) {
|
||||
res.status(400).json({ error: 'Course must be a number between 1 and 5' })
|
||||
return
|
||||
}
|
||||
|
||||
// Валидация ID (только латинские буквы, цифры, дефисы и подчеркивания)
|
||||
if (!/^[a-z0-9_-]+$/.test(id)) {
|
||||
res.status(400).json({ error: 'Group ID must contain only lowercase letters, numbers, dashes and underscores' })
|
||||
return
|
||||
}
|
||||
|
||||
const groups = loadGroups()
|
||||
|
||||
// Проверка на дубликат
|
||||
if (groups[id]) {
|
||||
res.status(400).json({ error: 'Group with this ID already exists' })
|
||||
return
|
||||
}
|
||||
|
||||
// Добавляем группу
|
||||
groups[id] = {
|
||||
parseId,
|
||||
name,
|
||||
course: groupCourse
|
||||
}
|
||||
|
||||
try {
|
||||
saveGroups(groups)
|
||||
res.status(200).json({ success: true, groups })
|
||||
} catch (error) {
|
||||
console.error('Error saving groups:', error)
|
||||
res.status(500).json({ error: 'Failed to save groups' })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
res.status(405).json({ error: 'Method not allowed' })
|
||||
}
|
||||
|
||||
export default function protectedHandler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
return requireAuth(req, res, handler)
|
||||
}
|
||||
|
||||
97
src/pages/api/admin/groups/[id].ts
Normal file
97
src/pages/api/admin/groups/[id].ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { requireAuth } from '@/shared/utils/auth'
|
||||
import { loadGroups, saveGroups, GroupsData } from '@/shared/data/groups-loader'
|
||||
|
||||
type ResponseData = {
|
||||
success?: boolean
|
||||
groups?: GroupsData
|
||||
error?: string
|
||||
}
|
||||
|
||||
async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
const { id } = req.query
|
||||
|
||||
if (!id || typeof id !== 'string') {
|
||||
res.status(400).json({ error: 'Group ID is required' })
|
||||
return
|
||||
}
|
||||
|
||||
const groups = loadGroups()
|
||||
|
||||
if (req.method === 'PUT') {
|
||||
// Редактирование группы
|
||||
const { parseId, name, course } = req.body
|
||||
|
||||
if (!groups[id]) {
|
||||
res.status(404).json({ error: 'Group not found' })
|
||||
return
|
||||
}
|
||||
|
||||
if (parseId !== undefined && typeof parseId !== 'number') {
|
||||
res.status(400).json({ error: 'Parse ID must be a number' })
|
||||
return
|
||||
}
|
||||
|
||||
if (name !== undefined && typeof name !== 'string') {
|
||||
res.status(400).json({ error: 'Group name must be a string' })
|
||||
return
|
||||
}
|
||||
|
||||
if (course !== undefined) {
|
||||
const groupCourse = Number(course)
|
||||
if (!Number.isInteger(groupCourse) || groupCourse < 1 || groupCourse > 5) {
|
||||
res.status(400).json({ error: 'Course must be a number between 1 and 5' })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Обновляем группу
|
||||
const currentGroup = groups[id]
|
||||
groups[id] = {
|
||||
parseId: parseId !== undefined ? parseId : currentGroup.parseId,
|
||||
name: name !== undefined ? name : currentGroup.name,
|
||||
course: course !== undefined ? Number(course) : currentGroup.course
|
||||
}
|
||||
|
||||
try {
|
||||
saveGroups(groups)
|
||||
res.status(200).json({ success: true, groups })
|
||||
} catch (error) {
|
||||
console.error('Error saving groups:', error)
|
||||
res.status(500).json({ error: 'Failed to save groups' })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (req.method === 'DELETE') {
|
||||
// Удаление группы
|
||||
if (!groups[id]) {
|
||||
res.status(404).json({ error: 'Group not found' })
|
||||
return
|
||||
}
|
||||
|
||||
delete groups[id]
|
||||
|
||||
try {
|
||||
saveGroups(groups)
|
||||
res.status(200).json({ success: true, groups })
|
||||
} catch (error) {
|
||||
console.error('Error saving groups:', error)
|
||||
res.status(500).json({ error: 'Failed to save groups' })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
res.status(405).json({ error: 'Method not allowed' })
|
||||
}
|
||||
|
||||
export default function protectedHandler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
return requireAuth(req, res, handler)
|
||||
}
|
||||
|
||||
32
src/pages/api/admin/login.ts
Normal file
32
src/pages/api/admin/login.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { verifyPassword, setSessionCookie } from '@/shared/utils/auth'
|
||||
|
||||
type ResponseData = {
|
||||
success?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export default function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
if (req.method !== 'POST') {
|
||||
res.status(405).json({ error: 'Method not allowed' })
|
||||
return
|
||||
}
|
||||
|
||||
const { password } = req.body
|
||||
|
||||
if (!password || typeof password !== 'string') {
|
||||
res.status(400).json({ error: 'Password is required' })
|
||||
return
|
||||
}
|
||||
|
||||
if (verifyPassword(password)) {
|
||||
setSessionCookie(res)
|
||||
res.status(200).json({ success: true })
|
||||
} else {
|
||||
res.status(401).json({ error: 'Invalid password' })
|
||||
}
|
||||
}
|
||||
|
||||
20
src/pages/api/admin/logout.ts
Normal file
20
src/pages/api/admin/logout.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { clearSessionCookie } from '@/shared/utils/auth'
|
||||
|
||||
type ResponseData = {
|
||||
success?: boolean
|
||||
}
|
||||
|
||||
export default function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ResponseData>
|
||||
) {
|
||||
if (req.method !== 'POST') {
|
||||
res.status(405).json({})
|
||||
return
|
||||
}
|
||||
|
||||
clearSessionCookie(res)
|
||||
res.status(200).json({ success: true })
|
||||
}
|
||||
|
||||
@@ -1,16 +1,189 @@
|
||||
import { GetServerSidePropsResult } from 'next'
|
||||
import { groups } from '@/shared/data/groups'
|
||||
import React from 'react'
|
||||
import { GetServerSideProps } from 'next'
|
||||
import { loadGroups, GroupsData } from '@/shared/data/groups-loader'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/shadcn/ui/card'
|
||||
import { Button } from '@/shadcn/ui/button'
|
||||
import { ThemeSwitcher } from '@/features/theme-switch'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/shadcn/ui/dialog'
|
||||
import Link from 'next/link'
|
||||
import Head from 'next/head'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { cn } from '@/shared/utils'
|
||||
import { GITHUB_REPO_URL, TELEGRAM_CONTACT_URL } from '@/shared/constants/urls'
|
||||
import { MdAdd } from 'react-icons/md'
|
||||
import { FaGithub } from 'react-icons/fa'
|
||||
import { BsTelegram } from 'react-icons/bs'
|
||||
|
||||
export default function HomePage() { }
|
||||
type HomePageProps = {
|
||||
groups: GroupsData
|
||||
groupsByCourse: { [course: number]: Array<{ id: string; name: string }> }
|
||||
}
|
||||
|
||||
export default function HomePage({ groups, groupsByCourse }: HomePageProps) {
|
||||
const [openCourses, setOpenCourses] = React.useState<Set<number>>(new Set([1]))
|
||||
const [addGroupDialogOpen, setAddGroupDialogOpen] = React.useState(false)
|
||||
|
||||
const toggleCourse = (course: number) => {
|
||||
setOpenCourses(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(course)) {
|
||||
next.delete(course)
|
||||
} else {
|
||||
next.add(course)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Расписание занятий — Колледж Связи ПГУТИ</title>
|
||||
<meta name="description" content="Расписание занятий для всех групп Колледжа Связи ПГУТИ. Выберите группу для просмотра расписания." />
|
||||
</Head>
|
||||
<div className="min-h-screen p-4 md:p-8">
|
||||
<div className="max-w-4xl mx-auto space-y-4">
|
||||
<div className="text-center space-y-2 mb-8">
|
||||
<h1 className="text-3xl md:text-4xl font-bold">Расписание занятий</h1>
|
||||
<p className="text-muted-foreground">Выберите группу для просмотра расписания</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{[1, 2, 3, 4, 5].map(course => {
|
||||
const courseGroups = groupsByCourse[course] || []
|
||||
const isOpen = openCourses.has(course)
|
||||
|
||||
if (courseGroups.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Card key={course}>
|
||||
<CardHeader
|
||||
className="cursor-pointer"
|
||||
onClick={() => toggleCourse(course)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-xl">
|
||||
{course} курс
|
||||
</CardTitle>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-5 w-5 transition-transform duration-200",
|
||||
isOpen && "transform rotate-180"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{isOpen && (
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-3 sm:grid-cols-2 lg:grid-cols-3 gap-2">
|
||||
{courseGroups.map(({ id, name }) => (
|
||||
<Link key={id} href={`/${id}`}>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-center h-auto py-3 px-2 sm:px-4 text-sm sm:text-base whitespace-nowrap"
|
||||
>
|
||||
{name}
|
||||
</Button>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{Object.keys(groups).length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-8 text-center text-muted-foreground">
|
||||
Группы не найдены
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-3 mt-8">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setAddGroupDialogOpen(true)}
|
||||
className="gap-2"
|
||||
>
|
||||
<MdAdd className="h-4 w-4" />
|
||||
Добавить группу
|
||||
</Button>
|
||||
<div className="relative">
|
||||
<ThemeSwitcher />
|
||||
<span className="absolute -bottom-5 left-1/2 transform -translate-x-1/2 text-xs text-muted-foreground whitespace-nowrap sm:hidden">
|
||||
Тема
|
||||
</span>
|
||||
</div>
|
||||
<Link href={GITHUB_REPO_URL} target="_blank" rel="noopener noreferrer">
|
||||
<Button variant="outline" className="gap-2">
|
||||
<FaGithub className="h-4 w-4" />
|
||||
GitHub
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Диалог добавления группы */}
|
||||
<Dialog open={addGroupDialogOpen} onOpenChange={setAddGroupDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Добавить группу</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription>
|
||||
Если вы хотите добавить свою группу на сайт, скиньтесь всей группой и задонатьте мне 500 ₽
|
||||
</DialogDescription>
|
||||
<DialogDescription>
|
||||
Для меня это будет очень хорошая поддержка🥺🥺🥺
|
||||
</DialogDescription>
|
||||
<DialogFooter className="!justify-start !flex-row mt-3 gap-3">
|
||||
<Link href={TELEGRAM_CONTACT_URL}>
|
||||
<Button tabIndex={-1} className="gap-3">
|
||||
<BsTelegram /> Мой Telegram
|
||||
</Button>
|
||||
</Link>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<HomePageProps> = async () => {
|
||||
const groups = loadGroups()
|
||||
|
||||
// Группируем группы по курсам
|
||||
const groupsByCourse: { [course: number]: Array<{ id: string; name: string }> } = {}
|
||||
|
||||
for (const [id, group] of Object.entries(groups)) {
|
||||
const course = group.course
|
||||
if (!groupsByCourse[course]) {
|
||||
groupsByCourse[course] = []
|
||||
}
|
||||
groupsByCourse[course].push({ id, name: group.name })
|
||||
}
|
||||
|
||||
// Сортируем группы внутри каждого курса по имени
|
||||
for (const course in groupsByCourse) {
|
||||
groupsByCourse[Number(course)].sort((a, b) => a.name.localeCompare(b.name))
|
||||
}
|
||||
|
||||
export async function getServerSideProps(): Promise<GetServerSidePropsResult<Record<string, never>>> {
|
||||
// Получаем первую группу из списка
|
||||
const firstGroupId = Object.keys(groups)[0]
|
||||
|
||||
return {
|
||||
redirect: {
|
||||
destination: `/${firstGroupId}`,
|
||||
permanent: true
|
||||
props: {
|
||||
groups,
|
||||
groupsByCourse
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { ISitemapField, getServerSideSitemapLegacy } from 'next-sitemap'
|
||||
import { GetServerSideProps } from 'next'
|
||||
import { groups } from '@/shared/data/groups'
|
||||
import { loadGroups } from '@/shared/data/groups-loader'
|
||||
import { SITEMAP_SITE_URL } from '@/shared/constants/urls'
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async (ctx) => {
|
||||
const groups = loadGroups()
|
||||
const fields = Object.keys(groups).map<ISitemapField>(group => (
|
||||
{
|
||||
loc: `${SITEMAP_SITE_URL}/${group}`,
|
||||
|
||||
Reference in New Issue
Block a user