project init

This commit is contained in:
2026-02-06 02:17:59 +03:00
commit b9d9b9ed17
129 changed files with 22835 additions and 0 deletions

View File

@ -0,0 +1,139 @@
'use client';
import { Check, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { cn } from '@/lib/utils';
import { SUBSCRIPTION_PLANS, formatPlanPrice } from '@coursecraft/shared';
const locale = 'ru';
const plans = SUBSCRIPTION_PLANS.map((plan) => ({
tier: plan.tier,
name: plan.nameRu,
priceFormatted: formatPlanPrice(plan, locale).formatted,
features: plan.featuresRu,
}));
const currentPlan = {
tier: 'FREE' as const,
coursesUsed: 1,
coursesLimit: 2,
renewalDate: null as string | null,
};
export default function BillingPage() {
const usagePercent = (currentPlan.coursesUsed / currentPlan.coursesLimit) * 100;
return (
<div className="space-y-6 max-w-4xl">
<div>
<h1 className="text-3xl font-bold">Подписка</h1>
<p className="text-muted-foreground">
Управляйте вашей подпиской и лимитами
</p>
</div>
{/* Current usage */}
<Card>
<CardHeader>
<CardTitle>Текущее использование</CardTitle>
<CardDescription>
Ваш тарифный план: {plans.find((p) => p.tier === currentPlan.tier)?.name}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium">Курсы в этом месяце</span>
<span className="text-sm text-muted-foreground">
{currentPlan.coursesUsed} / {currentPlan.coursesLimit}
</span>
</div>
<Progress value={usagePercent} className="h-2" />
</div>
{currentPlan.renewalDate && (
<p className="text-sm text-muted-foreground">
Следующее обновление: {currentPlan.renewalDate}
</p>
)}
</CardContent>
</Card>
{/* Plans */}
<div className="grid gap-6 md:grid-cols-3">
{plans.map((plan) => {
const isCurrent = plan.tier === currentPlan.tier;
const isUpgrade =
(currentPlan.tier === 'FREE' && plan.tier !== 'FREE') ||
(currentPlan.tier === 'PREMIUM' && plan.tier === 'PRO');
return (
<Card
key={plan.tier}
className={cn(isCurrent && 'border-primary')}
>
<CardHeader>
<CardTitle className="flex items-center justify-between">
{plan.name}
{isCurrent && (
<span className="text-xs bg-primary text-primary-foreground px-2 py-1 rounded-full">
Текущий
</span>
)}
</CardTitle>
<CardDescription>
<span className="text-3xl font-bold">{plan.priceFormatted}</span>
{plan.priceFormatted !== 'Бесплатно' && (
<span className="text-muted-foreground">/месяц</span>
)}
</CardDescription>
</CardHeader>
<CardContent>
<ul className="space-y-2">
{plan.features.map((feature) => (
<li key={feature} className="flex items-center gap-2 text-sm">
<Check className="h-4 w-4 text-primary shrink-0" />
{feature}
</li>
))}
</ul>
</CardContent>
<CardFooter>
{isCurrent ? (
<Button variant="outline" className="w-full" disabled>
Текущий план
</Button>
) : isUpgrade ? (
<Button className="w-full">
<Zap className="mr-2 h-4 w-4" />
Улучшить
</Button>
) : (
<Button variant="outline" className="w-full">
Выбрать
</Button>
)}
</CardFooter>
</Card>
);
})}
</div>
{currentPlan.tier !== 'FREE' && (
<Card>
<CardHeader>
<CardTitle>Управление подпиской</CardTitle>
</CardHeader>
<CardContent className="flex gap-4">
<Button variant="outline">Изменить способ оплаты</Button>
<Button variant="outline" className="text-destructive">
Отменить подписку
</Button>
</CardContent>
</Card>
)}
</div>
);
}

View File

@ -0,0 +1,218 @@
'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { ChevronLeft, ChevronRight, Save, Wand2, Eye, Pencil } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { CourseEditor } from '@/components/editor/course-editor';
import { LessonContentViewer } from '@/components/editor/lesson-content-viewer';
import { LessonSidebar } from '@/components/editor/lesson-sidebar';
import { cn } from '@/lib/utils';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/auth-context';
type Lesson = { id: string; title: string };
type Chapter = { id: string; title: string; lessons: Lesson[] };
type CourseData = { id: string; title: string; chapters: Chapter[] };
const emptyDoc = { type: 'doc', content: [] };
export default function CourseEditPage() {
const params = useParams();
const { loading: authLoading } = useAuth();
const courseId = params?.id as string;
const [course, setCourse] = useState<CourseData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [activeLesson, setActiveLesson] = useState<{ chapterId: string; lessonId: string } | null>(null);
const [content, setContent] = useState<Record<string, unknown>>(emptyDoc);
const [contentLoading, setContentLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [readOnly, setReadOnly] = useState(false);
useEffect(() => {
if (!courseId || authLoading) return;
let cancelled = false;
(async () => {
setLoading(true);
setError(null);
try {
const data = await api.getCourse(courseId);
if (!cancelled) {
setCourse(data);
const firstChapter = data.chapters?.[0];
const firstLesson = firstChapter?.lessons?.[0];
if (firstChapter && firstLesson) {
setActiveLesson({ chapterId: firstChapter.id, lessonId: firstLesson.id });
}
}
} catch (e: any) {
if (!cancelled) setError(e?.message || 'Не удалось загрузить курс');
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
}, [courseId, authLoading]);
// Load lesson content when active lesson changes
useEffect(() => {
if (!courseId || !activeLesson) {
setContent(emptyDoc);
return;
}
let cancelled = false;
setContentLoading(true);
(async () => {
try {
const lessonData = await api.getLesson(courseId, activeLesson.lessonId);
if (!cancelled && lessonData?.content) {
setContent(
typeof lessonData.content === 'object' && lessonData.content !== null
? (lessonData.content as Record<string, unknown>)
: emptyDoc
);
} else if (!cancelled) {
setContent(emptyDoc);
}
} catch {
if (!cancelled) setContent(emptyDoc);
} finally {
if (!cancelled) setContentLoading(false);
}
})();
return () => { cancelled = true; };
}, [courseId, activeLesson?.lessonId]);
const handleSelectLesson = (lessonId: string) => {
if (!course) return;
for (const ch of course.chapters) {
const lesson = ch.lessons.find((l) => l.id === lessonId);
if (lesson) {
setActiveLesson({ chapterId: ch.id, lessonId: lesson.id });
return;
}
}
};
const handleSave = async () => {
if (!courseId || !activeLesson || saving) return;
setSaving(true);
try {
await api.updateLesson(courseId, activeLesson.lessonId, { content });
} catch (e: any) {
console.error('Save failed:', e);
} finally {
setSaving(false);
}
};
if (authLoading || loading) {
return (
<div className="flex h-[calc(100vh-4rem)] items-center justify-center">
<p className="text-muted-foreground">Загрузка курса...</p>
</div>
);
}
if (error || !course) {
return (
<div className="flex h-[calc(100vh-4rem)] items-center justify-center">
<p className="text-destructive">{error || 'Курс не найден'}</p>
</div>
);
}
const flatLessons = course.chapters.flatMap((ch) =>
ch.lessons.map((l) => ({ ...l, chapterId: ch.id }))
);
const activeLessonMeta = activeLesson
? flatLessons.find((l) => l.id === activeLesson.lessonId)
: null;
return (
<div className="relative flex h-[calc(100vh-4rem)] -m-6">
<div
className={cn(
'border-r bg-muted/30 transition-all duration-300',
sidebarOpen ? 'w-72' : 'w-0'
)}
>
{sidebarOpen && (
<LessonSidebar
course={course}
activeLesson={activeLesson?.lessonId ?? ''}
onSelectLesson={handleSelectLesson}
/>
)}
</div>
<button
className="absolute left-0 top-1/2 -translate-y-1/2 z-10 flex h-8 w-6 items-center justify-center rounded-r-md border border-l-0 bg-background shadow-sm hover:bg-muted transition-colors"
style={{ left: sidebarOpen ? '288px' : '0px' }}
onClick={() => setSidebarOpen(!sidebarOpen)}
>
{sidebarOpen ? (
<ChevronLeft className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</button>
<div className="flex-1 flex flex-col min-h-0">
<div className="flex shrink-0 items-center justify-between border-b px-4 py-2">
<h2 className="font-medium truncate">
{activeLessonMeta?.title ?? 'Выберите урок'}
</h2>
<div className="flex items-center gap-2">
{readOnly ? (
<>
<Button variant="outline" size="sm" asChild>
<Link href={`/dashboard/courses/${courseId}`}>
<Eye className="mr-2 h-4 w-4" />
Просмотр курса
</Link>
</Button>
<Button size="sm" onClick={() => setReadOnly(false)}>
<Pencil className="mr-2 h-4 w-4" />
Редактировать
</Button>
</>
) : (
<>
<Button variant="outline" size="sm" onClick={() => setReadOnly(true)}>
<Eye className="mr-2 h-4 w-4" />
Режим просмотра
</Button>
<Button variant="outline" size="sm">
<Wand2 className="mr-2 h-4 w-4" />
AI помощник
</Button>
<Button size="sm" onClick={handleSave} disabled={saving || !activeLesson}>
<Save className="mr-2 h-4 w-4" />
{saving ? 'Сохранение...' : 'Сохранить'}
</Button>
</>
)}
</div>
</div>
<div className="flex-1 flex flex-col min-h-0 overflow-auto p-6">
<div className="w-full max-w-3xl mx-auto flex-1 min-h-0 flex flex-col">
{contentLoading ? (
<p className="text-muted-foreground">Загрузка контента...</p>
) : readOnly ? (
<LessonContentViewer content={content} className="prose-reader min-h-[400px]" />
) : (
<CourseEditor content={content} onChange={setContent} />
)}
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,235 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, Edit, Trash2, ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/auth-context';
import { LessonContentViewer } from '@/components/editor/lesson-content-viewer';
import { LessonSidebar } from '@/components/editor/lesson-sidebar';
import { cn } from '@/lib/utils';
type Lesson = { id: string; title: string; durationMinutes?: number | null; order: number };
type Chapter = { id: string; title: string; description?: string | null; order: number; lessons: Lesson[] };
type CourseData = {
id: string;
title: string;
description?: string | null;
status: string;
chapters: Chapter[];
};
export default function CoursePage() {
const params = useParams();
const router = useRouter();
const { loading: authLoading } = useAuth();
const id = params?.id as string;
const [course, setCourse] = useState<CourseData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [selectedLessonId, setSelectedLessonId] = useState<string | null>(null);
const [lessonContent, setLessonContent] = useState<Record<string, unknown> | null>(null);
const [lessonContentLoading, setLessonContentLoading] = useState(false);
useEffect(() => {
if (!id || authLoading) return;
let cancelled = false;
(async () => {
setLoading(true);
setError(null);
try {
const data = await api.getCourse(id);
if (!cancelled) {
setCourse(data);
const first = data.chapters?.[0]?.lessons?.[0];
if (first) setSelectedLessonId(first.id);
}
} catch (e: any) {
if (!cancelled) setError(e?.message || 'Не удалось загрузить курс');
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => { cancelled = true; };
}, [id, authLoading]);
useEffect(() => {
if (!id || !selectedLessonId) {
setLessonContent(null);
return;
}
let cancelled = false;
setLessonContentLoading(true);
(async () => {
try {
const data = await api.getLesson(id, selectedLessonId);
const content = data?.content;
if (!cancelled)
setLessonContent(
typeof content === 'object' && content !== null ? (content as Record<string, unknown>) : null
);
} catch {
if (!cancelled) setLessonContent(null);
} finally {
if (!cancelled) setLessonContentLoading(false);
}
})();
return () => { cancelled = true; };
}, [id, selectedLessonId]);
const handleDelete = async () => {
if (!course?.id || deleting) return;
setDeleting(true);
try {
await api.deleteCourse(course.id);
router.push('/dashboard');
router.refresh();
} catch (e: any) {
setError(e?.message || 'Не удалось удалить курс');
} finally {
setDeleting(false);
}
};
if (authLoading || loading) {
return (
<div className="flex h-[calc(100vh-4rem)] items-center justify-center">
<p className="text-muted-foreground">Загрузка курса...</p>
</div>
);
}
if (error || !course) {
return (
<div className="flex flex-col gap-4 p-6">
<Button variant="ghost" asChild>
<Link href="/dashboard"><ArrowLeft className="mr-2 h-4 w-4" />Назад к курсам</Link>
</Button>
<p className="text-destructive">{error || 'Курс не найден'}</p>
</div>
);
}
const activeLessonTitle = selectedLessonId
? (() => {
for (const ch of course.chapters) {
const lesson = ch.lessons.find((l) => l.id === selectedLessonId);
if (lesson) return lesson.title;
}
return null;
})()
: null;
return (
<div className="flex h-[calc(100vh-4rem)] -m-6 flex-col">
{/* Top bar */}
<div className="flex shrink-0 items-center justify-between border-b bg-background px-4 py-3">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" asChild>
<Link href="/dashboard">
<ArrowLeft className="mr-2 h-4 w-4" />
К курсам
</Link>
</Button>
<span className="text-muted-foreground">/</span>
<span className="font-medium truncate max-w-[200px] sm:max-w-xs">{course.title}</span>
</div>
<div className="flex items-center gap-2">
<Button size="sm" asChild>
<Link href={`/dashboard/courses/${course.id}/edit`}>
<Edit className="mr-2 h-4 w-4" />
Редактировать
</Link>
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="icon" className="text-destructive hover:text-destructive hover:bg-destructive/10">
<Trash2 className="h-4 w-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Удалить курс?</AlertDialogTitle>
<AlertDialogDescription>
Курс «{course.title}» будет удалён безвозвратно.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => { e.preventDefault(); handleDelete(); }}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={deleting}
>
{deleting ? 'Удаление...' : 'Удалить'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<div className="relative flex flex-1 min-h-0">
{/* Left: list of lessons (paragraphs) */}
<div
className={cn(
'border-r bg-muted/20 flex flex-col transition-[width] duration-200',
sidebarOpen ? 'w-72 shrink-0' : 'w-0 overflow-hidden'
)}
>
{sidebarOpen && (
<LessonSidebar
course={course}
activeLesson={selectedLessonId ?? ''}
onSelectLesson={setSelectedLessonId}
readOnly
/>
)}
</div>
<button
type="button"
className="absolute top-4 z-10 flex h-8 w-6 items-center justify-center rounded-r-md border border-l-0 bg-background shadow-sm hover:bg-muted transition-colors"
style={{ left: sidebarOpen ? '17rem' : 0 }}
onClick={() => setSidebarOpen(!sidebarOpen)}
>
{sidebarOpen ? <ChevronLeft className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
{/* Center: lesson content (read-only) */}
<main className="flex-1 flex flex-col min-h-0 overflow-auto">
<div className="max-w-3xl mx-auto w-full px-6 py-8">
{activeLessonTitle && (
<h1 className="text-2xl font-bold mb-6 text-foreground">{activeLessonTitle}</h1>
)}
{lessonContentLoading ? (
<p className="text-muted-foreground">Загрузка...</p>
) : selectedLessonId ? (
<LessonContentViewer
content={lessonContent}
className="prose-reader min-h-[400px] [&_.ProseMirror]:min-h-[300px]"
/>
) : (
<p className="text-muted-foreground">Выберите урок в списке слева.</p>
)}
</div>
</main>
</div>
</div>
);
}

View File

@ -0,0 +1,512 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { Send, Sparkles, Loader2, Check, ArrowRight, X, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { cn } from '@/lib/utils';
import { api } from '@/lib/api';
import { useToast } from '@/components/ui/use-toast';
type Step = 'prompt' | 'questions' | 'generating' | 'complete' | 'error';
interface ClarifyingQuestion {
id: string;
question: string;
type: 'single_choice' | 'multiple_choice' | 'text';
options?: string[];
required: boolean;
}
export default function NewCoursePage() {
const router = useRouter();
const { toast } = useToast();
const [step, setStep] = useState<Step>('prompt');
const [prompt, setPrompt] = useState('');
const [generationId, setGenerationId] = useState<string | null>(null);
const [questions, setQuestions] = useState<ClarifyingQuestion[]>([]);
const [answers, setAnswers] = useState<Record<string, string | string[]>>({});
const [progress, setProgress] = useState(0);
const [currentStepText, setCurrentStepText] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const [courseId, setCourseId] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
// Poll for generation status
const pollStatus = useCallback(async () => {
if (!generationId) return;
try {
const status = await api.getGenerationStatus(generationId);
setProgress(status.progress);
setCurrentStepText(status.currentStep || '');
// Normalize status to uppercase for comparison
const normalizedStatus = status.status?.toUpperCase();
switch (normalizedStatus) {
case 'WAITING_FOR_ANSWERS':
if (status.questions) {
// questions can be array or object with questions array
const questionsArray = Array.isArray(status.questions)
? status.questions
: (status.questions as any)?.questions || [];
if (questionsArray.length > 0) {
setQuestions(questionsArray as ClarifyingQuestion[]);
setStep('questions');
}
}
break;
case 'COMPLETED':
setStep('complete');
if (status.course) {
setCourseId(status.course.id);
}
break;
case 'FAILED':
case 'CANCELLED':
setStep('error');
setErrorMessage(status.errorMessage || 'Генерация не удалась');
break;
default:
// Continue polling for other statuses (PENDING, ANALYZING, ASKING_QUESTIONS, RESEARCHING, GENERATING_OUTLINE, GENERATING_CONTENT)
if (step !== 'questions') {
setStep('generating');
}
}
} catch (error) {
console.error('Failed to get status:', error);
}
}, [generationId, step]);
// Start polling when we have a generation ID
useEffect(() => {
if (!generationId || step === 'complete' || step === 'error' || step === 'questions') {
return;
}
const interval = setInterval(pollStatus, 2000);
return () => clearInterval(interval);
}, [generationId, step, pollStatus]);
const handleSubmitPrompt = async () => {
if (!prompt.trim() || isSubmitting) return;
setIsSubmitting(true);
try {
const result = await api.startGeneration(prompt);
setGenerationId(result.id);
setStep('generating');
setProgress(result.progress);
// Start polling immediately
setTimeout(pollStatus, 1000);
} catch (error: any) {
toast({
title: 'Ошибка',
description: error.message || 'Не удалось начать генерацию',
variant: 'destructive',
});
} finally {
setIsSubmitting(false);
}
};
const handleAnswerQuestion = (questionId: string, answer: string) => {
setAnswers((prev) => ({ ...prev, [questionId]: answer }));
};
const handleAnswerMultiple = (questionId: string, option: string) => {
setAnswers((prev) => {
const current = prev[questionId] as string[] || [];
const updated = current.includes(option)
? current.filter((o) => o !== option)
: [...current, option];
return { ...prev, [questionId]: updated };
});
};
const handleSubmitAnswers = async () => {
if (!generationId || isSubmitting) return;
setIsSubmitting(true);
try {
await api.answerQuestions(generationId, answers);
setStep('generating');
// Resume polling
setTimeout(pollStatus, 1000);
} catch (error: any) {
toast({
title: 'Ошибка',
description: error.message || 'Не удалось отправить ответы',
variant: 'destructive',
});
} finally {
setIsSubmitting(false);
}
};
const handleCancel = async () => {
if (!generationId) return;
try {
await api.cancelGeneration(generationId);
router.push('/dashboard');
} catch (error) {
router.push('/dashboard');
}
};
const handleRetry = () => {
setStep('prompt');
setGenerationId(null);
setQuestions([]);
setAnswers({});
setProgress(0);
setCurrentStepText('');
setErrorMessage('');
setCourseId(null);
};
const allRequiredAnswered = questions
.filter((q) => q.required)
.every((q) => {
const answer = answers[q.id];
if (Array.isArray(answer)) return answer.length > 0;
return Boolean(answer);
});
return (
<div className="max-w-3xl mx-auto space-y-8">
<div className="text-center">
<h1 className="text-3xl font-bold">Создать новый курс</h1>
<p className="text-muted-foreground mt-2">
Опишите тему курса, и AI создаст его за вас
</p>
</div>
<AnimatePresence mode="wait">
{/* Step 1: Prompt */}
{step === 'prompt' && (
<motion.div
key="prompt"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
<Card>
<CardContent className="p-6">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary/10">
<Sparkles className="h-5 w-5 text-primary" />
</div>
<div className="flex-1 space-y-4">
<p className="text-sm text-muted-foreground">
Привет! Я помогу вам создать курс. Просто опишите, о чём
должен быть ваш курс.
</p>
<textarea
className="w-full min-h-[120px] rounded-lg border bg-background p-4 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none"
placeholder="Например: Сделай курс по маркетингу для начинающих с акцентом на социальные сети..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
disabled={isSubmitting}
/>
<div className="flex justify-end">
<Button
onClick={handleSubmitPrompt}
disabled={!prompt.trim() || isSubmitting}
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Отправка...
</>
) : (
<>
Продолжить
<Send className="ml-2 h-4 w-4" />
</>
)}
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
</motion.div>
)}
{/* Step 2: Questions */}
{step === 'questions' && (
<motion.div
key="questions"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
className="space-y-4"
>
{/* User prompt */}
<Card className="bg-muted/50">
<CardContent className="p-4">
<p className="text-sm">{prompt}</p>
</CardContent>
</Card>
{/* AI questions */}
<Card>
<CardContent className="p-6">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary/10">
<Sparkles className="h-5 w-5 text-primary" />
</div>
<div className="flex-1 space-y-6">
<p className="text-sm text-muted-foreground">
Отлично! Чтобы создать идеальный курс, мне нужно уточнить
несколько деталей:
</p>
{questions.map((question, index) => (
<div key={question.id} className="space-y-3">
<p className="font-medium">
{index + 1}. {question.question}
{question.required && (
<span className="text-destructive">*</span>
)}
</p>
{question.type === 'single_choice' && question.options && (
<div className="grid gap-2">
{question.options.map((option) => (
<button
key={option}
className={cn(
'flex items-center gap-3 rounded-lg border p-3 text-left text-sm transition-colors',
answers[question.id] === option
? 'border-primary bg-primary/5'
: 'hover:bg-muted'
)}
onClick={() =>
handleAnswerQuestion(question.id, option)
}
>
<div
className={cn(
'flex h-5 w-5 items-center justify-center rounded-full border-2',
answers[question.id] === option
? 'border-primary bg-primary'
: 'border-muted-foreground'
)}
>
{answers[question.id] === option && (
<Check className="h-3 w-3 text-primary-foreground" />
)}
</div>
{option}
</button>
))}
</div>
)}
{question.type === 'multiple_choice' && question.options && (
<div className="grid gap-2">
{question.options.map((option) => {
const selected = (answers[question.id] as string[] || []).includes(option);
return (
<button
key={option}
className={cn(
'flex items-center gap-3 rounded-lg border p-3 text-left text-sm transition-colors',
selected
? 'border-primary bg-primary/5'
: 'hover:bg-muted'
)}
onClick={() =>
handleAnswerMultiple(question.id, option)
}
>
<div
className={cn(
'flex h-5 w-5 items-center justify-center rounded border-2',
selected
? 'border-primary bg-primary'
: 'border-muted-foreground'
)}
>
{selected && (
<Check className="h-3 w-3 text-primary-foreground" />
)}
</div>
{option}
</button>
);
})}
</div>
)}
{question.type === 'text' && (
<textarea
className="w-full rounded-lg border bg-background p-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none"
placeholder="Введите ответ..."
rows={3}
value={(answers[question.id] as string) || ''}
onChange={(e) =>
handleAnswerQuestion(question.id, e.target.value)
}
/>
)}
</div>
))}
<div className="flex justify-between pt-4">
<Button variant="ghost" onClick={handleCancel}>
<X className="mr-2 h-4 w-4" />
Отменить
</Button>
<Button
onClick={handleSubmitAnswers}
disabled={!allRequiredAnswered || isSubmitting}
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Отправка...
</>
) : (
<>
Создать курс
<ArrowRight className="ml-2 h-4 w-4" />
</>
)}
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
</motion.div>
)}
{/* Step 3: Generating */}
{step === 'generating' && (
<motion.div
key="generating"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
<Card>
<CardContent className="p-8 text-center space-y-6">
<div className="flex justify-center">
<div className="relative">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10">
<Loader2 className="h-10 w-10 text-primary animate-spin" />
</div>
</div>
</div>
<div className="space-y-2">
<h2 className="text-xl font-semibold">Генерация курса</h2>
<p className="text-muted-foreground">{currentStepText || 'Подготовка...'}</p>
</div>
<div className="max-w-md mx-auto space-y-2">
<Progress value={progress} className="h-2" />
<p className="text-sm text-muted-foreground">{progress}%</p>
</div>
<Button variant="ghost" onClick={handleCancel}>
<X className="mr-2 h-4 w-4" />
Отменить генерацию
</Button>
</CardContent>
</Card>
</motion.div>
)}
{/* Step 4: Complete */}
{step === 'complete' && (
<motion.div
key="complete"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
<Card>
<CardContent className="p-8 text-center space-y-6">
<div className="flex justify-center">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-green-100 dark:bg-green-900">
<Check className="h-10 w-10 text-green-600 dark:text-green-400" />
</div>
</div>
<div className="space-y-2">
<h2 className="text-xl font-semibold">Курс готов!</h2>
<p className="text-muted-foreground">
Ваш курс успешно создан. Теперь вы можете просмотреть и
отредактировать его.
</p>
</div>
<div className="flex justify-center gap-4">
<Button variant="outline" asChild>
<a href="/dashboard">К списку курсов</a>
</Button>
{courseId && (
<Button asChild>
<a href={`/dashboard/courses/${courseId}/edit`}>
Редактировать курс
<ArrowRight className="ml-2 h-4 w-4" />
</a>
</Button>
)}
</div>
</CardContent>
</Card>
</motion.div>
)}
{/* Error state */}
{step === 'error' && (
<motion.div
key="error"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
>
<Card>
<CardContent className="p-8 text-center space-y-6">
<div className="flex justify-center">
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-red-100 dark:bg-red-900">
<AlertCircle className="h-10 w-10 text-red-600 dark:text-red-400" />
</div>
</div>
<div className="space-y-2">
<h2 className="text-xl font-semibold">Ошибка генерации</h2>
<p className="text-muted-foreground">
{errorMessage || 'Произошла ошибка при генерации курса.'}
</p>
</div>
<div className="flex justify-center gap-4">
<Button variant="outline" asChild>
<a href="/dashboard">К списку курсов</a>
</Button>
<Button onClick={handleRetry}>
Попробовать снова
</Button>
</div>
</CardContent>
</Card>
</motion.div>
)}
</AnimatePresence>
</div>
);
}

View File

@ -0,0 +1,139 @@
'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Plus, BookOpen, Clock, TrendingUp, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { CourseCard } from '@/components/dashboard/course-card';
import { api } from '@/lib/api';
import { useToast } from '@/components/ui/use-toast';
import { useAuth } from '@/contexts/auth-context';
interface Course {
id: string;
title: string;
description: string | null;
status: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED' | 'GENERATING';
chaptersCount: number;
lessonsCount: number;
updatedAt: string;
}
export default function DashboardPage() {
const { toast } = useToast();
const { loading: authLoading, user } = useAuth();
const [courses, setCourses] = useState<Course[]>([]);
const [loading, setLoading] = useState(true);
const [stats, setStats] = useState({
total: 0,
drafts: 0,
published: 0,
});
const loadCourses = async () => {
setLoading(true);
try {
const result = await api.getCourses();
setCourses(result.data);
const total = result.data.length;
const drafts = result.data.filter((c: Course) => c.status === 'DRAFT').length;
const published = result.data.filter((c: Course) => c.status === 'PUBLISHED').length;
setStats({ total, drafts, published });
} catch (error: any) {
if (error.message !== 'Unauthorized') {
toast({
title: 'Ошибка загрузки',
description: 'Не удалось загрузить курсы',
variant: 'destructive',
});
}
} finally {
setLoading(false);
}
};
useEffect(() => {
if (authLoading) return;
if (!user) {
setLoading(false);
return;
}
loadCourses();
}, [toast, authLoading, user]);
const statsCards = [
{ name: 'Всего курсов', value: stats.total.toString(), icon: BookOpen },
{ name: 'Черновики', value: stats.drafts.toString(), icon: Clock },
{ name: 'Опубликовано', value: stats.published.toString(), icon: TrendingUp },
];
if (authLoading || loading) {
return (
<div className="flex items-center justify-center min-h-[400px]">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-8">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">Мои курсы</h1>
<p className="text-muted-foreground">
Управляйте своими курсами и создавайте новые
</p>
</div>
<Button asChild>
<Link href="/dashboard/courses/new">
<Plus className="mr-2 h-4 w-4" />
Создать курс
</Link>
</Button>
</div>
{/* Stats */}
<div className="grid gap-4 md:grid-cols-3">
{statsCards.map((stat) => (
<Card key={stat.name}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{stat.name}</CardTitle>
<stat.icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stat.value}</div>
</CardContent>
</Card>
))}
</div>
{/* Courses grid */}
{courses.length > 0 ? (
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{courses.map((course) => (
<CourseCard key={course.id} course={course} onDeleted={loadCourses} />
))}
</div>
) : (
<Card className="p-12 text-center">
<CardHeader>
<CardTitle>Нет курсов</CardTitle>
<CardDescription>
Создайте свой первый курс с помощью AI
</CardDescription>
</CardHeader>
<CardContent>
<Button asChild>
<Link href="/dashboard/courses/new">
<Plus className="mr-2 h-4 w-4" />
Создать курс
</Link>
</Button>
</CardContent>
</Card>
)}
</div>
);
}

View File

@ -0,0 +1,137 @@
'use client';
import { useState } from 'react';
import { Save } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
export default function SettingsPage() {
const { toast } = useToast();
const [settings, setSettings] = useState({
name: 'John Doe',
email: 'john@example.com',
customAiModel: '',
emailNotifications: true,
marketingEmails: false,
});
const handleSave = () => {
toast({
title: 'Настройки сохранены',
description: 'Ваши настройки успешно обновлены.',
});
};
return (
<div className="space-y-6 max-w-2xl">
<div>
<h1 className="text-3xl font-bold">Настройки</h1>
<p className="text-muted-foreground">
Управляйте настройками вашего аккаунта
</p>
</div>
{/* Profile */}
<Card>
<CardHeader>
<CardTitle>Профиль</CardTitle>
<CardDescription>Информация о вашем аккаунте</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Имя</Label>
<Input
id="name"
value={settings.name}
onChange={(e) => setSettings({ ...settings, name: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" value={settings.email} disabled />
<p className="text-xs text-muted-foreground">
Email нельзя изменить
</p>
</div>
</CardContent>
</Card>
{/* AI Settings */}
<Card>
<CardHeader>
<CardTitle>Настройки AI</CardTitle>
<CardDescription>
Настройте модель нейросети для генерации курсов
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="aiModel">Пользовательская модель</Label>
<Input
id="aiModel"
placeholder="qwen/qwen3-coder-next"
value={settings.customAiModel}
onChange={(e) =>
setSettings({ ...settings, customAiModel: e.target.value })
}
/>
<p className="text-xs text-muted-foreground">
Укажите модель в формате provider/model-name. Если оставить пустым,
будет использована модель по умолчанию для вашего тарифа.
</p>
</div>
</CardContent>
</Card>
{/* Notifications */}
<Card>
<CardHeader>
<CardTitle>Уведомления</CardTitle>
<CardDescription>Настройки email уведомлений</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Уведомления о курсах</Label>
<p className="text-sm text-muted-foreground">
Получать уведомления о статусе генерации
</p>
</div>
<input
type="checkbox"
checked={settings.emailNotifications}
onChange={(e) =>
setSettings({ ...settings, emailNotifications: e.target.checked })
}
className="h-4 w-4"
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Маркетинговые письма</Label>
<p className="text-sm text-muted-foreground">
Получать новости и специальные предложения
</p>
</div>
<input
type="checkbox"
checked={settings.marketingEmails}
onChange={(e) =>
setSettings({ ...settings, marketingEmails: e.target.checked })
}
className="h-4 w-4"
/>
</div>
</CardContent>
</Card>
<Button onClick={handleSave}>
<Save className="mr-2 h-4 w-4" />
Сохранить настройки
</Button>
</div>
);
}