feat: initial commit — backend API + student cabinet frontend
- Go backend: auth (JWT), points earn/spend, QR token generation, partners, admin grant/stats endpoints with chi router - Next.js 14 frontend: login, student dashboard, transaction history, QR display, partners list - PostgreSQL migrations (4 tables), Redis cache, Docker Compose - CORS middleware, role-based route protection, Zustand auth store Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
'use client';
|
||||
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button, Input, Card } from '@/components/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import { useAuthStore } from '@/lib/store';
|
||||
import type { TokenPair, Profile, UserRole } from '@/lib/types';
|
||||
|
||||
function parseJwtRole(token: string): UserRole | null {
|
||||
try {
|
||||
const part = token.split('.')[1];
|
||||
const padded = part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '=');
|
||||
const decoded = JSON.parse(atob(padded.replace(/-/g, '+').replace(/_/g, '/'))) as {
|
||||
role?: string;
|
||||
};
|
||||
const role = decoded.role;
|
||||
if (role === 'student' || role === 'partner' || role === 'admin') return role;
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ROLE_REDIRECT: Record<UserRole, string> = {
|
||||
student: '/dashboard',
|
||||
partner: '/scan',
|
||||
admin: '/admin/dashboard',
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { setTokens, setUser } = useAuthStore();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const tokens = await api.post<TokenPair>('/api/v1/auth/login', { email, password });
|
||||
|
||||
setTokens(tokens.access_token, tokens.refresh_token);
|
||||
|
||||
const profile = await api.get<Profile>('/api/v1/me');
|
||||
const role = parseJwtRole(tokens.access_token);
|
||||
if (!role) throw new Error('Не удалось определить роль пользователя');
|
||||
|
||||
setUser({ ...profile, role });
|
||||
router.push(ROLE_REDIRECT[role]);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Ошибка входа');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<h1 className="mb-6 text-2xl font-bold text-white">CU Points</h1>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<Input
|
||||
label="Email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder="student@cu.ru"
|
||||
/>
|
||||
<Input
|
||||
label="Пароль"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="rounded-lg bg-red-900/30 px-3 py-2 text-sm text-red-400">{error}</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" isLoading={loading} className="mt-2 w-full">
|
||||
Войти
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export default function ScanPage() {
|
||||
// TODO: QR scanner + amount input form → POST /api/v1/partner/spend → show result
|
||||
return (
|
||||
<main className="p-6">
|
||||
<p className="text-gray-500">Partner scan — coming soon</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { BalanceCard } from '@/components/BalanceCard';
|
||||
import { TransactionList } from '@/components/TransactionList';
|
||||
import { Spinner } from '@/components/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import { useAuthStore } from '@/lib/store';
|
||||
import type { Profile, Transaction, PaginatedResponse } from '@/lib/types';
|
||||
|
||||
export default function StudentDashboardPage() {
|
||||
const { user, updateBalance } = useAuthStore();
|
||||
|
||||
const [profile, setProfile] = useState<Profile | null>(null);
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
const [loadingProfile, setLoadingProfile] = useState(true);
|
||||
const [loadingTxs, setLoadingTxs] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
try {
|
||||
const [p, page] = await Promise.all([
|
||||
api.get<Profile>('/api/v1/me'),
|
||||
api.get<PaginatedResponse<Transaction>>('/api/v1/me/transactions?limit=5'),
|
||||
]);
|
||||
setProfile(p);
|
||||
updateBalance(p.balance);
|
||||
setTransactions(page.transactions);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Ошибка загрузки');
|
||||
} finally {
|
||||
setLoadingProfile(false);
|
||||
setLoadingTxs(false);
|
||||
}
|
||||
}
|
||||
load();
|
||||
}, [updateBalance]);
|
||||
|
||||
if (loadingProfile) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center">
|
||||
<Spinner size="lg" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center p-6">
|
||||
<p className="text-red-400">{error}</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const displayName = profile?.name ?? user?.name ?? '';
|
||||
const balance = profile?.balance ?? user?.balance ?? 0;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-lg space-y-6 p-4 pb-10 pt-6">
|
||||
<h1 className="text-xl font-bold text-white">
|
||||
Привет, {displayName.split(' ')[0]} 👋
|
||||
</h1>
|
||||
|
||||
<BalanceCard balance={balance} name={displayName} />
|
||||
|
||||
<section>
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-gray-200">Последние операции</h2>
|
||||
<Link href="/history" className="text-sm text-blue-400 hover:text-blue-300">
|
||||
Вся история →
|
||||
</Link>
|
||||
</div>
|
||||
<div className="rounded-2xl bg-gray-800 p-4 ring-1 ring-gray-700">
|
||||
<TransactionList transactions={transactions} isLoading={loadingTxs} />
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { TransactionList } from '@/components/TransactionList';
|
||||
import { Button } from '@/components/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import type { Transaction, PaginatedResponse } from '@/lib/types';
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export default function HistoryPage() {
|
||||
const [transactions, setTransactions] = useState<Transaction[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchPage = useCallback(async (currentOffset: number, append: boolean) => {
|
||||
if (append) setLoadingMore(true);
|
||||
else setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const page = await api.get<PaginatedResponse<Transaction>>(
|
||||
`/api/v1/me/transactions?limit=${PAGE_SIZE}&offset=${currentOffset}`,
|
||||
);
|
||||
setTransactions((prev) => (append ? [...prev, ...page.transactions] : page.transactions));
|
||||
setTotal(page.total);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Ошибка загрузки');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPage(0, false);
|
||||
}, [fetchPage]);
|
||||
|
||||
function handleLoadMore() {
|
||||
const nextOffset = offset + PAGE_SIZE;
|
||||
setOffset(nextOffset);
|
||||
fetchPage(nextOffset, true);
|
||||
}
|
||||
|
||||
const hasMore = transactions.length < total;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-lg p-4 pb-10 pt-6">
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<Link href="/dashboard" className="text-sm text-blue-400 hover:text-blue-300">
|
||||
← Назад
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold text-white">История операций</h1>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="mb-4 rounded-lg bg-red-900/30 px-3 py-2 text-sm text-red-400">{error}</p>
|
||||
)}
|
||||
|
||||
<div className="rounded-2xl bg-gray-800 p-4 ring-1 ring-gray-700">
|
||||
<TransactionList transactions={transactions} isLoading={loading} />
|
||||
</div>
|
||||
|
||||
{!loading && hasMore && (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button variant="secondary" onClick={handleLoadMore} isLoading={loadingMore}>
|
||||
Загрузить ещё
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !hasMore && transactions.length > 0 && (
|
||||
<p className="mt-4 text-center text-xs text-gray-600">Это все операции</p>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { PartnerCard } from '@/components/PartnerCard';
|
||||
import { Spinner } from '@/components/ui';
|
||||
import { api } from '@/lib/api';
|
||||
import type { Partner } from '@/lib/types';
|
||||
|
||||
export default function PartnersPage() {
|
||||
const [partners, setPartners] = useState<Partner[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api.get<Partner[]>('/api/v1/partners');
|
||||
setPartners(data);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Ошибка загрузки партнёров');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
load();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-lg p-4 pb-10 pt-6">
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<Link href="/dashboard" className="text-sm text-blue-400 hover:text-blue-300">
|
||||
← Назад
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold text-white">Партнёры</h1>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div className="flex justify-center py-12">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="rounded-lg bg-red-900/30 px-3 py-2 text-sm text-red-400">{error}</p>
|
||||
)}
|
||||
|
||||
{!loading && !error && partners.length === 0 && (
|
||||
<p className="py-8 text-center text-sm text-gray-500">Партнёры пока не добавлены</p>
|
||||
)}
|
||||
|
||||
{!loading && partners.length > 0 && (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{partners.map((p) => (
|
||||
<PartnerCard key={p.id} partner={p} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { QRDisplay } from '@/components/QRDisplay';
|
||||
|
||||
export default function QRPage() {
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center gap-6 p-6">
|
||||
<h1 className="text-xl font-bold text-white">Оплата поинтами</h1>
|
||||
|
||||
<QRDisplay />
|
||||
|
||||
<p className="max-w-xs text-center text-sm text-gray-500">
|
||||
Покажи этот QR кассиру. Он действителен 5 минут и может быть использован только один раз.
|
||||
</p>
|
||||
|
||||
<Link href="/dashboard" className="text-sm text-blue-400 hover:text-blue-300">
|
||||
← Назад
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export default function AdminDashboardPage() {
|
||||
// TODO(notion): fetch GET /api/v1/admin/stats → display key metrics + recent transactions
|
||||
return (
|
||||
<main className="p-6">
|
||||
<p className="text-gray-500">Admin dashboard — coming soon</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export default function GrantPage() {
|
||||
// TODO(notion): form (user_id, amount, description) → POST /api/v1/admin/points/grant → confirmation
|
||||
return (
|
||||
<main className="p-6">
|
||||
<p className="text-gray-500">Grant points — coming soon</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,20 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--background: #0d0d14;
|
||||
--foreground: #f1f5f9;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.text-balance {
|
||||
text-wrap: balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Metadata } from 'next';
|
||||
import localFont from 'next/font/local';
|
||||
import './globals.css';
|
||||
|
||||
const geistSans = localFont({
|
||||
src: './fonts/GeistVF.woff',
|
||||
variable: '--font-geist-sans',
|
||||
weight: '100 900',
|
||||
});
|
||||
const geistMono = localFont({
|
||||
src: './fonts/GeistMonoVF.woff',
|
||||
variable: '--font-geist-mono',
|
||||
weight: '100 900',
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'CU Points',
|
||||
description: 'Система лояльности Центрального Университета',
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="ru">
|
||||
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function RootPage() {
|
||||
redirect('/login');
|
||||
}
|
||||
Reference in New Issue
Block a user