Ship Novya PWA with backend for deployable production use.

Fix production TypeScript builds and add DEPLOY.md so the app can be hosted from this repo.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ar.badiei
2026-09-03 21:01:52 +03:30
co-authored by Cursor
parent aa9236fb92
commit 370ac15471
193 changed files with 25997 additions and 1991 deletions
+209 -104
View File
@@ -1,125 +1,230 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import type { ReactNode } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { useNavigate } from 'react-router-dom';
import { LogOut, User as UserIcon, Mail, Phone } from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { useCurrentSession } from '@/hooks/useCurrentSession';
import { PROGRAM_SESSION_COUNT } from '@/data/program/sessions';
import { getProgramProgress } from '@/services/programService';
import { Progress } from '@/components/ui/progress';
import { Navigate, useNavigate } from 'react-router-dom';
import { Check, ChevronLeft, Loader2, Lock } from 'lucide-react';
import { cn } from '@/lib/utils';
import { StaggeredList, StaggerItem, AnimationWrapper } from '@/components/motion';
import { motion } from 'framer-motion';
import { fastTransition } from '@/lib/motion';
type StepState = 'open' | 'locked' | 'done';
/**
* Course Status surface (profile menu → وضعیت دوره).
* Journey status only — no settings, scores, or assessment results.
*/
export default function AccountPage() {
const { user, signOut } = useAuth();
const { effectiveUserId, isGuest, guestSessionHydrated } = useAuth();
const { progress, loading, permissions } = useLearningJourney(effectiveUserId ?? undefined);
const { currentSession, isProgramComplete, programProgress } = useCurrentSession(effectiveUserId);
const navigate = useNavigate();
const { toast } = useToast();
const handleSignOut = async () => {
try {
await signOut();
toast({
title: 'خروج موفق',
description: 'با موفقیت خارج شدید'
});
navigate('/');
} catch (error) {
toast({
title: 'خطا',
description: 'خطا در خروج از حساب کاربری',
variant: 'destructive'
});
}
};
if (!guestSessionHydrated || loading) {
return (
<div className="flex min-h-[50vh] items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-neon-cyan" />
</div>
);
}
const getUserInitials = () => {
if (user?.email) {
return user.email.substring(0, 2).toUpperCase();
}
if (user?.phone) {
return user.phone.slice(-2);
}
return 'U';
};
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
const cachedProgress = getProgramProgress(effectiveUserId);
const effectiveProgramProgress = programProgress ?? cachedProgress;
const completedSessions = effectiveProgramProgress.completedSessions.length;
const programDone =
isProgramComplete ||
Boolean(effectiveProgramProgress.completedAt) ||
completedSessions >= PROGRAM_SESSION_COUNT;
const progressPercent = programDone
? 100
: Math.round((completedSessions / PROGRAM_SESSION_COUNT) * 100);
const preDone = Boolean(progress?.pre_test_completed_at);
const trainingDone = Boolean(progress?.training_completed_at) || programDone;
const postDone = Boolean(progress?.post_test_completed_at);
const displaySessionOrder =
currentSession?.order ??
(programDone ? PROGRAM_SESSION_COUNT : Math.max(effectiveProgramProgress.currentSessionOrder, 1));
const preState: StepState = preDone ? 'done' : 'open';
const trainingState: StepState = !permissions.canOpenTraining
? 'locked'
: trainingDone
? 'done'
: 'open';
const postState: StepState = postDone
? 'done'
: permissions.canTakePostTest || (trainingDone && preDone && !postDone)
? 'open'
: 'locked';
return (
<div className="min-h-screen bg-gradient-to-br from-background to-muted p-4 pb-20">
<div className="mx-auto max-w-sm">
<div className="mb-4">
<h1 className="text-2xl font-bold mb-2">حساب کاربری</h1>
<p className="text-sm text-muted-foreground">مدیریت اطلاعات و تنظیمات حساب کاربری</p>
</div>
<div className="h-full min-h-0 flex-1 overflow-y-auto px-4 py-6">
<div className="mx-auto w-full max-w-md space-y-4">
<AnimationWrapper immediate className="space-y-1 pb-2">
<h1 className="text-2xl font-bold tracking-tight text-foreground">وضعیت دوره</h1>
{isGuest && <p className="text-sm text-body">جلسه مهمان</p>}
</AnimationWrapper>
<Card>
<CardHeader>
<CardTitle>اطلاعات کاربری</CardTitle>
<CardDescription>جزئیات حساب کاربری شما</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<Avatar className="h-16 w-16">
<AvatarImage src={user?.user_metadata?.avatar_url} alt={user?.email || 'User'} />
<AvatarFallback className="text-lg">{getUserInitials()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<h3 className="text-lg font-semibold mb-2 truncate">
{user?.user_metadata?.full_name || user?.email || user?.phone || 'کاربر'}
</h3>
<div className="space-y-2 text-sm text-muted-foreground">
{user?.email && (
<div className="flex items-center gap-2">
<Mail className="h-4 w-4 flex-shrink-0" />
<span className="truncate">{user.email}</span>
</div>
)}
{user?.phone && (
<div className="flex items-center gap-2">
<Phone className="h-4 w-4 flex-shrink-0" />
<span className="truncate">{user.phone}</span>
</div>
)}
</div>
</div>
</div>
<StaggeredList itemCount={3} className="space-y-3" role="region" aria-label="وضعیت دوره">
<StaggerItem>
<StatusRow
title="پیش‌آزمون"
state={preState}
onOpen={() => navigate('/assessment/pre')}
lockedHint={preDone ? 'انجام شده — قابل تکرار نیست' : undefined}
>
{preDone ? (
<StatusDone label="انجام شده" />
) : (
<p className="text-sm text-body">برای شروع مسیر، پیش‌آزمون را انجام دهید</p>
)}
</StatusRow>
</StaggerItem>
<div className="border-t pt-6">
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<div className="font-medium">شناسه کاربری</div>
<div className="text-sm text-muted-foreground font-mono">
{user?.id?.substring(0, 8)}...
</div>
<StaggerItem>
<StatusRow
title="دوره آموزشی"
state={trainingState}
onOpen={() => navigate('/chat')}
lockedHint={
trainingDone ? 'دوره تکمیل شده' : 'پس از انجام پیش‌آزمون فعال می‌شود'
}
>
{trainingDone ? (
<StatusDone label="دوره تکمیل شده" />
) : !permissions.canOpenTraining ? (
<p className="flex items-start gap-2 text-sm text-body">
<Lock className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
<span>پس از انجام پیش‌آزمون فعال می‌شود</span>
</p>
) : (
<div className="space-y-2">
<p className="text-sm font-medium text-foreground">
جلسه {displaySessionOrder} از {PROGRAM_SESSION_COUNT}
</p>
<div className="flex items-center gap-3">
<Progress value={progressPercent} className="h-2.5 flex-1" />
<span className="min-w-[2.5rem] text-left text-sm tabular-nums text-body">
{progressPercent}٪
</span>
</div>
<UserIcon className="h-5 w-5 text-muted-foreground" />
</div>
)}
</StatusRow>
</StaggerItem>
{user?.created_at && (
<div className="flex items-center justify-between">
<div>
<div className="font-medium">تاریخ عضویت</div>
<div className="text-sm text-muted-foreground">
{new Date(user.created_at).toLocaleDateString('fa-IR')}
</div>
</div>
</div>
)}
</div>
</div>
<div className="border-t pt-6">
<Button
variant="destructive"
className="w-full"
onClick={handleSignOut}
>
<LogOut className="ml-2 h-4 w-4" />
خروج از حساب کاربری
</Button>
</div>
</CardContent>
</Card>
<StaggerItem>
<StatusRow
title="پس‌آزمون"
state={postState}
onOpen={() => navigate('/assessment/post')}
lockedHint={
postDone
? 'انجام شده — قابل تکرار نیست'
: 'پس از پایان دوره آموزشی فعال می‌شود'
}
>
{postState === 'done' && <StatusDone label="انجام شده" />}
{postState === 'open' && (
<p className="flex items-center gap-2 text-sm font-medium text-foreground">
<span
className="inline-block h-2 w-2 shrink-0 rounded-full bg-neon-teal shadow-[0_0_8px_rgba(52,184,150,0.7)]"
aria-hidden
/>
آماده انجام
</p>
)}
{postState === 'locked' && (
<p className="flex items-start gap-2 text-sm text-body">
<Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
<span>پس از پایان دوره فعال می‌شود</span>
</p>
)}
</StatusRow>
</StaggerItem>
</StaggeredList>
</div>
</div>
);
}
function StatusRow({
title,
children,
state,
onOpen,
lockedHint,
}: {
title: string;
children: ReactNode;
state: StepState;
onOpen: () => void;
lockedHint?: string;
}) {
const isInteractive = state === 'open';
const content = (
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1 space-y-2 text-right">
<h2 className="text-sm font-semibold text-foreground">{title}</h2>
{children}
</div>
{isInteractive ? (
<ChevronLeft className="mt-0.5 h-5 w-5 shrink-0 text-neon-cyan" aria-hidden />
) : (
<Lock
className={cn(
'mt-0.5 h-4 w-4 shrink-0',
state === 'done' ? 'text-neon-emerald/70' : 'text-muted-foreground'
)}
aria-hidden
/>
)}
</div>
);
if (isInteractive) {
return (
<motion.button
type="button"
onClick={onOpen}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
transition={fastTransition}
className="glass-panel w-full px-4 py-4 text-right transition-colors duration-200 hover:border-neon-cyan/55 hover:shadow-[0_0_18px_rgba(72,180,200,0.22)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neon-cyan/50"
aria-label={`${title} — باز کردن`}
>
{content}
</motion.button>
);
}
return (
<div
className="glass-panel w-full px-4 py-4 opacity-90"
aria-disabled="true"
title={lockedHint}
>
{content}
</div>
);
}
function StatusDone({ label }: { label: string }) {
return (
<p className="flex items-center gap-2 text-sm font-medium text-foreground">
<Check className="h-4 w-4 shrink-0 text-neon-emerald" aria-hidden />
{label}
</p>
);
}
+369
View File
@@ -0,0 +1,369 @@
import { useMemo, useState } from 'react';
import { Navigate, useNavigate, useParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { useAuth } from '@/hooks/useAuth';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import {
saveAssessment,
type AttemptPhase,
} from '@/services/assessmentService';
import { BackendError } from '@/services/backend';
import { getBackendErrorMessage, isBackendNetworkError } from '@/lib/backendError';
import { useToast } from '@/components/ui/use-toast';
import { PCQ24_QUESTIONS, PCQ_LIKERT_OPTIONS } from '@/config/pcq24';
import { cn } from '@/lib/utils';
const FADE_MS = 220;
export default function AssessmentPage() {
const { phase } = useParams<{ phase: AttemptPhase }>();
const navigate = useNavigate();
const { effectiveUserId } = useAuth();
const { toast } = useToast();
const { progress, loading, permissions, markPreTestDone, markPostTestDone, reloadProgress } = useLearningJourney(
effectiveUserId ?? undefined
);
const [answers, setAnswers] = useState<Record<string, string>>({});
const [submitting, setSubmitting] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [isRedirecting, setIsRedirecting] = useState(false);
const [showIntro, setShowIntro] = useState(true);
const [contentVisible, setContentVisible] = useState(true);
const [isAnimating, setIsAnimating] = useState(false);
const isPreTest = phase === 'pre';
const isPostTest = phase === 'post';
const invalidPhase = !isPreTest && !isPostTest;
const canAccess = useMemo(() => {
if (isPreTest) return permissions.canTakePreTest;
if (isPostTest) return permissions.canTakePostTest;
return false;
}, [isPostTest, isPreTest, permissions.canTakePostTest, permissions.canTakePreTest]);
const totalQuestions = PCQ24_QUESTIONS.length;
const currentQuestion = PCQ24_QUESTIONS[currentIndex];
const selectedValue = answers[currentQuestion.id];
const isLastQuestion = currentIndex === totalQuestions - 1;
const allAnswered = PCQ24_QUESTIONS.every((q) => Boolean(answers[q.id]));
const canSubmit = allAnswered && !submitting && !isRedirecting;
const progressPercent = ((currentIndex + 1) / totalQuestions) * 100;
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
if (invalidPhase) {
return <Navigate to="/" replace />;
}
if (!loading && !canAccess) {
if (isPreTest && progress?.pre_test_completed_at) {
return <Navigate to="/" replace />;
}
if (isPostTest && progress?.post_test_completed_at) {
return <Navigate to="/finished" replace />;
}
if (isPostTest) {
return <Navigate to="/" replace />;
}
}
const advanceWithFade = (delta: number) => {
if (isAnimating || submitting || isRedirecting) return;
setIsAnimating(true);
setContentVisible(false);
window.setTimeout(() => {
setCurrentIndex((prev) => Math.max(0, Math.min(prev + delta, totalQuestions - 1)));
setContentVisible(true);
window.setTimeout(() => setIsAnimating(false), FADE_MS);
}, FADE_MS);
};
const onSelect = (questionId: string, value: string) => {
if (isAnimating || submitting || isRedirecting) return;
setAnswers((prev) => ({ ...prev, [questionId]: value }));
if (!isLastQuestion) {
setIsAnimating(true);
window.setTimeout(() => {
setContentVisible(false);
window.setTimeout(() => {
setCurrentIndex((prev) => Math.min(prev + 1, totalQuestions - 1));
setContentVisible(true);
window.setTimeout(() => setIsAnimating(false), FADE_MS);
}, FADE_MS);
}, 90);
}
};
const handleSubmit = async () => {
if (PCQ24_QUESTIONS.some((q) => !answers[q.id])) {
toast({
title: 'پاسخ ناقص',
description: 'لطفا به همه سوال‌ها پاسخ دهید.',
variant: 'destructive',
});
return;
}
if (isPreTest && progress?.pre_test_completed_at) {
navigate('/', { replace: true });
return;
}
if (isPostTest) {
if (!permissions.canTakePostTest) {
navigate(progress?.post_test_completed_at ? '/finished' : '/', { replace: true });
return;
}
if (progress?.post_test_completed_at) {
navigate('/finished', { replace: true });
return;
}
}
setSubmitting(true);
try {
const rawAnswers = PCQ24_QUESTIONS.map((question) => ({
questionId: question.id,
selectedValue: answers[question.id],
}));
const submission = await saveAssessment({
userId: effectiveUserId,
phase: isPreTest ? 'pre' : 'post',
answers: rawAnswers,
});
if (isPreTest) {
await markPreTestDone(submission.completedAt);
await reloadProgress();
setSuccessMessage('پیش‌آزمون با موفقیت ثبت شد. در حال انتقال به فضای چت...');
setIsRedirecting(true);
setTimeout(() => navigate('/chat'), 800);
return;
}
await markPostTestDone(submission.completedAt);
await reloadProgress();
setSuccessMessage('پس‌آزمون با موفقیت ثبت شد. در حال انتقال به صفحه پایان دوره...');
setIsRedirecting(true);
setTimeout(() => navigate('/finished'), 800);
} catch (error: unknown) {
console.error('Error saving assessment:', error);
if (error instanceof BackendError) {
if (error.status === 401) {
toast({
title: 'نشست شما منقضی شده است',
description: 'لطفاً دوباره وارد حساب خود شوید.',
variant: 'destructive',
});
navigate('/login', { replace: true });
return;
}
if (error.status === 409) {
if (isPreTest) {
await markPreTestDone();
await reloadProgress();
navigate('/chat', { replace: true });
return;
}
toast({
title: 'قبلا ثبت شده است',
description: 'پس آزمون قبلا ثبت شده است.',
variant: 'default',
});
navigate('/finished', { replace: true });
return;
}
if (error.status === 422) {
toast({
title: 'پاسخ‌ها نامعتبر هستند',
description: 'لطفاً پاسخ‌ها را بررسی کنید و دوباره تلاش کنید.',
variant: 'destructive',
});
return;
}
}
if (isBackendNetworkError(error)) {
toast({
title: 'سرور در دسترس نیست',
description: 'ثبت آزمون انجام نشد. لطفاً چند لحظه بعد دوباره تلاش کنید.',
variant: 'destructive',
});
return;
}
toast({
title: 'خطا',
description: getBackendErrorMessage(error, 'ثبت آزمون با مشکل مواجه شد. لطفاً دوباره تلاش کنید.'),
variant: 'destructive',
});
} finally {
setSubmitting(false);
}
};
const introTitle = isPreTest ? 'پیش‌آزمون' : 'پس‌آزمون';
const introBody = isPreTest ? (
<>
<p>
قبل از شروع مسیر یادگیری، لازم است وضعیت سرمایه روان‌شناختی شما را بسنجیم. این پرسشنامه کوتاه
(PCQ-24) به ما کمک می‌کند آموزش را متناسب با شرایط شما پیش ببریم.
</p>
<p className="text-sm text-slate-300/90">
پاسخ درست یا غلط وجود ندارد؛ گزینه‌ای را انتخاب کنید که بیشتر با تجربه واقعی شما همخوانی دارد.
</p>
</>
) : (
<p>
پس از پایان آموزش، پرسشنامه سرمایه روان‌شناختی (PCQ-24) را دوباره تکمیل کنید تا پیشرفت شما مشخص
شود.
</p>
);
return (
<div className="relative h-full min-h-0 flex-1 overflow-hidden p-4">
{/* Intro overlay — dark veil on text area; bottom almost visible */}
{showIntro && (
<div
className="absolute inset-0 z-40 flex flex-col p-5 pt-6"
role="dialog"
aria-modal="true"
aria-labelledby="assessment-intro-title"
>
<div
className="pointer-events-none absolute inset-0"
style={{
background:
'linear-gradient(to bottom, rgba(0,0,0,0.97) 0%, rgba(0,0,0,0.95) 70%, rgba(0,0,0,0.88) 85%, rgba(0,0,0,0.35) 92%, rgba(0,0,0,0.08) 100%)',
}}
aria-hidden
/>
<div className="animate-in fade-in relative z-10 flex w-full flex-col items-stretch gap-5 text-right duration-500">
<h2
id="assessment-intro-title"
className="text-xl font-semibold text-white drop-shadow-lg"
>
{isPreTest ? 'راهنمای پیش‌آزمون' : 'راهنمای پس‌آزمون'}
</h2>
<div className="space-y-4 text-sm leading-7 text-slate-100">{introBody}</div>
<Button
type="button"
variant="neon"
className="mt-2 w-full"
onClick={() => setShowIntro(false)}
>
متوجه شدم
</Button>
</div>
</div>
)}
{/* Questions surface */}
<div
className={cn(
'mx-auto flex h-full w-full max-w-lg flex-col gap-3',
showIntro && 'pointer-events-none'
)}
>
<div className="shrink-0 space-y-2">
<div className="flex items-center justify-between text-sm text-body">
<span className="font-medium text-cyan-800 dark:text-neon-cyan">{introTitle}</span>
<span className="font-medium tabular-nums text-foreground">{`سوال ${currentIndex + 1} از ${totalQuestions}`}</span>
</div>
<Progress value={progressPercent} className="h-2" />
</div>
<div className="glass-panel flex min-h-0 flex-1 flex-col overflow-hidden p-4">
{/* Fixed question zone — number + text stay pinned (no vertical reflow) */}
<div className="relative h-[9.5rem] shrink-0 overflow-hidden pt-1">
<div
className={cn(
'absolute inset-x-0 top-0 transition-opacity duration-[220ms] ease-out',
contentVisible ? 'opacity-100' : 'opacity-0'
)}
>
<p className="mb-2 text-sm font-semibold tabular-nums text-cyan-950 dark:text-neon-teal">
{`سوال ${currentIndex + 1}`}
</p>
<h3 className="line-clamp-4 text-base font-semibold leading-7 text-foreground">
{currentQuestion.text}
</h3>
</div>
</div>
{/* Fixed answers grid — same slot for every question */}
<div
className={cn(
'mt-3 grid shrink-0 grid-cols-1 gap-2 transition-opacity duration-[220ms] ease-out',
contentVisible ? 'opacity-100' : 'opacity-0'
)}
>
{PCQ_LIKERT_OPTIONS.map((option) => {
const selected = selectedValue === option.value;
return (
<button
key={`${currentQuestion.id}-${option.value}`}
type="button"
disabled={isAnimating || submitting || isRedirecting || showIntro}
onClick={() => onSelect(currentQuestion.id, option.value)}
className={cn(
'flex h-11 w-full items-center justify-start rounded-xl border px-4 text-right text-sm transition-colors duration-200',
selected
? 'border-cyan-500 bg-cyan-100 text-cyan-950 shadow-sm dark:border-neon-cyan dark:bg-neon-blue/25 dark:text-white dark:shadow-glow-sm'
: 'border-slate-200 bg-white/80 text-body hover:border-cyan-400 hover:bg-white hover:text-foreground dark:border-neon-cyan/20 dark:bg-slate-900/35 dark:hover:border-neon-cyan/50 dark:hover:bg-slate-800/45 dark:hover:text-white'
)}
>
{option.label}
</button>
);
})}
</div>
</div>
<div className="grid shrink-0 grid-cols-2 gap-2">
<Button
type="button"
variant="glass"
disabled={currentIndex === 0 || isAnimating || submitting || isRedirecting || showIntro}
onClick={() => advanceWithFade(-1)}
>
سوال قبلی
</Button>
{isLastQuestion ? (
<Button
variant="neon"
className="w-full"
onClick={handleSubmit}
disabled={!canSubmit || showIntro || isAnimating}
>
{submitting ? 'در حال ثبت...' : 'ثبت آزمون'}
</Button>
) : (
<Button
type="button"
variant="neon"
className="w-full"
disabled={!selectedValue || isAnimating || submitting || isRedirecting || showIntro}
onClick={() => advanceWithFade(1)}
>
سوال بعدی
</Button>
)}
</div>
{successMessage && (
<p className="shrink-0 rounded-xl border border-neon-emerald/35 bg-neon-emerald/10 px-3 py-2 text-center text-sm text-neon-teal">
{successMessage}
</p>
)}
</div>
</div>
);
}
+102 -301
View File
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -7,384 +7,185 @@ import { Label } from '@/components/ui/label';
import { useAuth } from '@/hooks/useAuth';
import { useTheme } from '@/hooks/useTheme';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Mail, Phone, LogIn, Moon, Sun } from 'lucide-react';
import { getBackendErrorMessage } from '@/lib/backendError';
import { Loader2, Mail, Lock, Moon, Sun, Sparkles } from 'lucide-react';
import { AnimationWrapper } from '@/components/motion';
import { APP_NAME, APP_DESCRIPTION } from '@/utils/constants';
export default function LoginPage() {
const navigate = useNavigate();
const { signIn, signInWithGoogle, signInWithPhone, verifyOTP } = useAuth();
const location = useLocation();
const { signIn, isAuthenticated, continueAsGuest } = useAuth();
const { toggleTheme, isDark } = useTheme();
const { toast } = useToast();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [phone, setPhone] = useState('');
const [otp, setOtp] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [otpSent, setOtpSent] = useState(false);
const [authMethod, setAuthMethod] = useState<'email' | 'phone' | 'google'>('email');
const handleEmailLogin = async (e: React.FormEvent) => {
useEffect(() => {
if (!isAuthenticated) return;
const fromState = (location.state as { from?: { pathname?: string } | string } | null)?.from;
const from =
typeof fromState === 'string' ? fromState : fromState?.pathname;
// Avoid bouncing back to auth screens if `from` was login/signup.
const safeFrom =
from && from !== '/login' && from !== '/signup' ? from : '/';
navigate(safeFrom, { replace: true });
}, [isAuthenticated, location.state, navigate]);
const handleEmailLogin = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!email || !password) {
const form = new FormData(e.currentTarget);
const nextEmail = String(form.get('email') ?? email).trim();
const nextPassword = String(form.get('password') ?? password);
if (!nextEmail || !nextPassword) {
toast({
title: 'خطا',
description: 'لطفا ایمیل و رمز عبور را وارد کنید',
variant: 'destructive'
variant: 'destructive',
});
return;
}
setEmail(nextEmail);
setPassword(nextPassword);
setIsLoading(true);
try {
await signIn(email, password);
toast({
title: 'موفق',
description: 'با موفقیت وارد شدید'
});
navigate('/account');
} catch (error: any) {
await signIn(nextEmail, nextPassword);
toast({ title: 'موفق', description: 'با موفقیت وارد شدید' });
navigate('/', { replace: true });
} catch (error: unknown) {
console.error('Login error:', error);
let errorMessage = 'خطا در ورود';
if (error) {
const errorMsg = error.message || error.error?.message || String(error);
if (errorMsg.includes('Invalid login credentials') || errorMsg.includes('invalid_credentials')) {
errorMessage = 'ایمیل یا رمز عبور اشتباه است. لطفا دوباره تلاش کنید یا ثبت نام کنید.';
} else if (errorMsg.includes('Email not confirmed') || errorMsg.includes('email_not_confirmed')) {
errorMessage = 'لطفا ابتدا ایمیل خود را تأیید کنید.';
} else if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg || 'خطا در ورود. لطفا دوباره تلاش کنید.';
}
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
description: getBackendErrorMessage(error, 'خطا در ورود. لطفاً دوباره تلاش کنید.'),
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleGoogleLogin = async () => {
const handleContinueWithoutLogin = async () => {
setIsLoading(true);
try {
await signInWithGoogle();
// Redirect happens automatically
} catch (error: any) {
console.error('Google login error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'خطا در ورود با گوگل';
toast({
title: 'خطا',
description: errorMsg.includes('Supabase not configured')
? 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.'
: errorMsg,
variant: 'destructive'
});
setIsLoading(false);
}
};
const handleSendOTP = async (e: React.FormEvent) => {
e.preventDefault();
if (!phone) {
toast({
title: 'خطا',
description: 'لطفا شماره تلفن را وارد کنید',
variant: 'destructive'
});
return;
}
setIsLoading(true);
try {
await signInWithPhone(phone);
setOtpSent(true);
toast({
title: 'موفق',
description: 'کد تأیید ارسال شد'
});
} catch (error: any) {
console.error('Phone OTP error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'خطا در ارسال کد';
let errorMessage = 'خطا در ارسال کد';
if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Invalid phone number') || errorMsg.includes('invalid_phone')) {
errorMessage = 'شماره تلفن نامعتبر است. لطفا شماره را با فرمت صحیح وارد کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg;
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
} finally {
setIsLoading(false);
}
};
const handleVerifyOTP = async (e: React.FormEvent) => {
e.preventDefault();
if (!otp) {
toast({
title: 'خطا',
description: 'لطفا کد تأیید را وارد کنید',
variant: 'destructive'
});
return;
}
setIsLoading(true);
try {
await verifyOTP(phone, otp);
toast({
title: 'موفق',
description: 'با موفقیت وارد شدید'
});
navigate('/account');
} catch (error: any) {
console.error('OTP verification error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'کد تأیید نامعتبر است';
let errorMessage = 'کد تأیید نامعتبر است';
if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Invalid OTP') || errorMsg.includes('invalid_token')) {
errorMessage = 'کد تأیید نامعتبر است. لطفا دوباره تلاش کنید.';
} else if (errorMsg.includes('expired')) {
errorMessage = 'کد تأیید منقضی شده است. لطفا کد جدید درخواست کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg;
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
await continueAsGuest();
const fromState = (location.state as { from?: { pathname?: string } | string } | null)?.from;
const from =
typeof fromState === 'string' ? fromState : fromState?.pathname;
const safeFrom =
from && from !== '/login' && from !== '/signup' ? from : '/';
navigate(safeFrom, { replace: true });
} catch {
toast({ title: 'خطا', description: 'خطا در ایجاد حساب مهمان', variant: 'destructive' });
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted p-4 relative">
{/* Dark Mode Toggle Button */}
<div className="app-auth-screen ambient-glow relative flex h-full min-h-0 items-center justify-center overflow-y-auto p-4">
<button
type="button"
onClick={toggleTheme}
className="absolute top-4 left-4 p-2 rounded-lg bg-background/80 backdrop-blur-sm border border-input hover:bg-accent transition-colors"
className="absolute left-4 top-4 z-10 inline-flex h-10 w-10 items-center justify-center rounded-xl border border-neon-cyan/30 bg-background/80 text-neon-cyan backdrop-blur-md transition-all hover:shadow-glow-sm"
aria-label={isDark ? 'تغییر به حالت روشن' : 'تغییر به حالت تاریک'}
>
{isDark ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)}
{isDark ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
</button>
<Card className="w-full max-w-sm">
<CardHeader className="space-y-1">
<div className="flex justify-center mb-4">
<LogIn className="h-12 w-12 text-primary" />
<AnimationWrapper immediate interactive={false} className="relative z-10 w-full max-w-sm">
<Card className="relative w-full overflow-hidden">
<div
className="pointer-events-none absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-neon-blue/20 via-neon-cyan/5 to-transparent"
aria-hidden
/>
<CardHeader className="relative space-y-2">
<div className="mb-2 flex justify-center">
<div className="avatar-glow">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-white text-cyan-700 shadow-sm dark:bg-navy dark:text-neon-cyan dark:shadow-none">
<Sparkles className="h-7 w-7" />
</div>
</div>
</div>
<CardTitle className="text-2xl text-center">ورود</CardTitle>
<CardDescription className="text-center">
به حساب کاربری خود وارد شوید
<CardTitle className="text-center text-3xl font-bold tracking-tight text-foreground">{APP_NAME}</CardTitle>
<CardDescription className="text-center text-body">
ورود به {APP_NAME} — {APP_DESCRIPTION}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Auth Method Selector */}
<div className="flex gap-2">
<Button
type="button"
variant={authMethod === 'email' ? 'default' : 'outline'}
className="flex-1"
onClick={() => {
setAuthMethod('email');
setOtpSent(false);
}}
>
<Mail className="ml-2 h-4 w-4" />
ایمیل
</Button>
<Button
type="button"
variant={authMethod === 'phone' ? 'default' : 'outline'}
className="flex-1"
onClick={() => {
setAuthMethod('phone');
setOtpSent(false);
}}
>
<Phone className="ml-2 h-4 w-4" />
تلفن
</Button>
</div>
{/* Email Login */}
{authMethod === 'email' && (
<form onSubmit={handleEmailLogin} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">ایمیل</Label>
<CardContent className="relative space-y-4">
<form onSubmit={handleEmailLogin} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email" className="text-body">
ایمیل
</Label>
<div className="relative">
<Mail className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neon-cyan/70" />
<Input
id="email"
name="email"
type="email"
placeholder="example@email.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLoading}
className="pr-10"
autoComplete="email"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">رمز عبور</Label>
</div>
<div className="space-y-2">
<Label htmlFor="password" className="text-body">
رمز عبور
</Label>
<div className="relative">
<Lock className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neon-cyan/70" />
<Input
id="password"
name="password"
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={isLoading}
className="pr-10"
autoComplete="current-password"
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ورود...
</>
) : (
'ورود'
)}
</Button>
</form>
)}
{/* Phone OTP Login */}
{authMethod === 'phone' && (
<>
{!otpSent ? (
<form onSubmit={handleSendOTP} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="phone">شماره تلفن</Label>
<Input
id="phone"
type="tel"
placeholder="09123456789"
value={phone}
onChange={(e) => setPhone(e.target.value)}
disabled={isLoading}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ارسال...
</>
) : (
'ارسال کد تأیید'
)}
</Button>
</form>
</div>
<Button type="submit" variant="neon" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ورود...
</>
) : (
<form onSubmit={handleVerifyOTP} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="otp">کد تأیید</Label>
<Input
id="otp"
type="text"
placeholder="123456"
value={otp}
onChange={(e) => setOtp(e.target.value)}
disabled={isLoading}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال تأیید...
</>
) : (
'تأیید کد'
)}
</Button>
<Button
type="button"
variant="ghost"
className="w-full"
onClick={() => setOtpSent(false)}
disabled={isLoading}
>
تغییر شماره
</Button>
</form>
'ورود'
)}
</>
)}
{/* Google Login */}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-muted-foreground">یا</span>
</div>
</div>
</Button>
</form>
<Button
type="button"
variant="outline"
variant="glass"
className="w-full"
onClick={handleGoogleLogin}
onClick={handleContinueWithoutLogin}
disabled={isLoading}
>
<svg className="ml-2 h-4 w-4" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
/>
<path
fill="currentColor"
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
/>
<path
fill="currentColor"
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
/>
<path
fill="currentColor"
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
/>
</svg>
ورود با گوگل
ادامه بدون ورود
</Button>
<div className="text-center text-sm">
<div className="text-center text-sm text-body">
حساب کاربری ندارید؟{' '}
<Link to="/signup" className="text-primary hover:underline">
<Link to="/signup" className="text-neon-cyan hover:text-neon-teal hover:underline">
ثبت نام
</Link>
</div>
</CardContent>
</Card>
</AnimationWrapper>
</div>
);
}
+47 -132
View File
@@ -7,11 +7,13 @@ import { Label } from '@/components/ui/label';
import { useAuth } from '@/hooks/useAuth';
import { useTheme } from '@/hooks/useTheme';
import { useToast } from '@/components/ui/use-toast';
import { getBackendErrorMessage } from '@/lib/backendError';
import { Loader2, UserPlus, Moon, Sun } from 'lucide-react';
import { APP_NAME, APP_DESCRIPTION } from '@/utils/constants';
export default function SignupPage() {
const navigate = useNavigate();
const { signUp, signInWithGoogle } = useAuth();
const { signUp } = useAuth();
const { toggleTheme, isDark } = useTheme();
const { toast } = useToast();
const [email, setEmail] = useState('');
@@ -25,7 +27,7 @@ export default function SignupPage() {
toast({
title: 'خطا',
description: 'لطفا تمام فیلدها را پر کنید',
variant: 'destructive'
variant: 'destructive',
});
return;
}
@@ -34,123 +36,71 @@ export default function SignupPage() {
toast({
title: 'خطا',
description: 'رمز عبور و تکرار آن مطابقت ندارند',
variant: 'destructive'
variant: 'destructive',
});
return;
}
if (password.length < 6) {
if (password.length < 8) {
toast({
title: 'خطا',
description: 'رمز عبور باید حداقل 6 کاراکتر باشد',
variant: 'destructive'
description: 'رمز عبور باید حداقل 8 کاراکتر باشد',
variant: 'destructive',
});
return;
}
setIsLoading(true);
try {
const result = await signUp(email, password);
if (result.error) {
let errorMessage = 'خطا در ثبت نام';
if ((result.error.message as any).includes('User already registered')) {
errorMessage = 'این ایمیل قبلاً ثبت شده است. لطفا وارد شوید.';
} else if ((result.error.message as any).includes('Password')) {
errorMessage = 'رمز عبور باید حداقل 6 کاراکتر باشد.';
} else {
errorMessage = (result.error.message as any);
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
} else if (result.data) {
// Check if email confirmation is required
if (result.data.user && !result.data.session) {
toast({
title: 'موفق',
description: 'حساب کاربری ایجاد شد. لطفا ایمیل خود را بررسی کنید و لینک تأیید را کلیک کنید.',
duration: 5000
});
navigate('/login');
} else if (result.data.session) {
toast({
title: 'موفق',
description: 'حساب کاربری ایجاد شد. در حال ورود...'
});
navigate('/account');
}
}
} catch (error: any) {
let errorMessage = 'خطا در ثبت نام';
if (error.message) {
if (error.message.includes('User already registered')) {
errorMessage = 'این ایمیل قبلاً ثبت شده است. لطفا وارد شوید.';
} else if (error.message.includes('Password')) {
errorMessage = 'رمز عبور باید حداقل 6 کاراکتر باشد.';
} else {
errorMessage = error.message;
}
}
await signUp(email, password);
toast({ title: 'موفق', description: 'حساب کاربری ایجاد شد. در حال ورود...' });
navigate('/', { replace: true });
} catch (error: unknown) {
console.error('Signup error:', error);
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
description: getBackendErrorMessage(error, 'خطا در ثبت‌نام. لطفاً دوباره تلاش کنید.'),
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleGoogleSignup = async () => {
setIsLoading(true);
try {
await signInWithGoogle();
// Redirect happens automatically
} catch (error: any) {
toast({
title: 'خطا',
description: error.message || 'خطا در ثبت نام با گوگل',
variant: 'destructive'
});
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted p-4 relative">
{/* Dark Mode Toggle Button */}
<div className="app-auth-screen ambient-glow relative flex h-full min-h-0 items-center justify-center overflow-y-auto p-4">
<button
type="button"
onClick={toggleTheme}
className="absolute top-4 left-4 p-2 rounded-lg bg-background/80 backdrop-blur-sm border border-input hover:bg-accent transition-colors"
className="absolute left-4 top-4 z-10 inline-flex h-10 w-10 items-center justify-center rounded-xl border border-neon-cyan/30 bg-background/80 text-neon-cyan backdrop-blur-md transition-all hover:shadow-glow-sm"
aria-label={isDark ? 'تغییر به حالت روشن' : 'تغییر به حالت تاریک'}
>
{isDark ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)}
{isDark ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
</button>
<Card className="w-full max-w-sm">
<CardHeader className="space-y-1">
<div className="flex justify-center mb-4">
<UserPlus className="h-12 w-12 text-primary" />
<Card className="relative z-10 w-full max-w-sm overflow-hidden">
<div
className="pointer-events-none absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-neon-blue/20 via-neon-cyan/5 to-transparent"
aria-hidden
/>
<CardHeader className="relative space-y-2">
<div className="mb-2 flex justify-center">
<div className="avatar-glow">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-white text-cyan-700 shadow-sm dark:bg-navy dark:text-neon-cyan dark:shadow-none">
<UserPlus className="h-7 w-7" />
</div>
</div>
</div>
<CardTitle className="text-2xl text-center">ثبت نام</CardTitle>
<CardDescription className="text-center">
حساب کاربری جدید ایجاد کنید
<CardTitle className="text-center text-3xl font-bold tracking-tight text-foreground">ثبت نام</CardTitle>
<CardDescription className="text-center text-body">
ایجاد حساب کاربری در {APP_NAME} — {APP_DESCRIPTION}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<CardContent className="relative space-y-4">
<form onSubmit={handleSignup} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">ایمیل</Label>
<Label htmlFor="email" className="text-body">ایمیل</Label>
<Input
id="email"
type="email"
@@ -158,10 +108,11 @@ export default function SignupPage() {
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLoading}
autoComplete="email"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">رمز عبور</Label>
<Label htmlFor="password" className="text-body">رمز عبور</Label>
<Input
id="password"
type="password"
@@ -169,10 +120,11 @@ export default function SignupPage() {
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={isLoading}
autoComplete="new-password"
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">تکرار رمز عبور</Label>
<Label htmlFor="confirmPassword" className="text-body">تکرار رمز عبور</Label>
<Input
id="confirmPassword"
type="password"
@@ -180,9 +132,10 @@ export default function SignupPage() {
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
disabled={isLoading}
autoComplete="new-password"
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
<Button type="submit" variant="neon" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
@@ -194,46 +147,9 @@ export default function SignupPage() {
</Button>
</form>
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-muted-foreground">یا</span>
</div>
</div>
<Button
type="button"
variant="outline"
className="w-full"
onClick={handleGoogleSignup}
disabled={isLoading}
>
<svg className="ml-2 h-4 w-4" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
/>
<path
fill="currentColor"
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
/>
<path
fill="currentColor"
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
/>
<path
fill="currentColor"
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
/>
</svg>
ثبت نام با گوگل
</Button>
<div className="text-center text-sm">
قبلا ثبت نام کرده‌اید؟{' '}
<Link to="/login" className="text-primary hover:underline">
<div className="text-center text-sm text-body">
حساب کاربری دارید؟{' '}
<Link to="/login" className="text-neon-cyan hover:text-neon-teal hover:underline">
ورود
</Link>
</div>
@@ -242,4 +158,3 @@ export default function SignupPage() {
</div>
);
}
+535 -208
View File
@@ -1,280 +1,607 @@
import { useState, useRef, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useState, useRef, useEffect, useCallback, Fragment, type FormEvent } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { MessageBubble } from '@/components/chat/MessageBubble';
import { AiThinkingBubble } from '@/components/chat/AiThinkingBubble';
import { useAuth } from '@/hooks/useAuth';
import { useChat } from '@/hooks/useChat';
import { useTypewriter } from '@/hooks/useTypewriter';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { useCurrentSession } from '@/hooks/useCurrentSession';
import { completeSessionWithBackend, getProgramProgress } from '@/services/programService';
import { formatRemainingUnlockTime } from '@/lib/sessionUnlock';
import { PROGRAM_SESSION_COUNT, getSessionByOrder } from '@/data/program/sessions';
import { useToast } from '@/components/ui/use-toast';
import { Send, MessageSquare, Loader2, Play } from 'lucide-react';
import { getFetchErrorMessage } from '@/lib/fetchError';
import { APP_NAME } from '@/utils/constants';
import { ArrowUp, Loader2, Sparkles } from 'lucide-react';
/**
* Chat = Educational Environment.
* Session content is NOT rendered here. `coachContext` is injected into the
* GapGPT system prompt so the AI coaches the current unlocked session.
*/
export default function ChatPage() {
const { user } = useAuth();
const { messages, loading, sendMessage } = useChat();
const { effectiveUserId, isGuest, guestSessionHydrated } = useAuth();
const { progress, loading: progressLoading, permissions, markTrainingDone, reloadProgress } = useLearningJourney(
effectiveUserId ?? undefined
);
const {
currentSession,
coachContext,
isProgramComplete,
programProgress,
waitingForNextSession,
refresh: refreshCurrentSession,
} = useCurrentSession(effectiveUserId);
const { toast } = useToast();
const navigate = useNavigate();
const handleCoachSessionCompleted = useCallback(
async (payload: {
sessionId: string;
sessionOrder: number;
reason: string;
readyForNextSession: boolean;
chatSessionId?: string;
signal?: {
sessionComplete: boolean;
sessionId: string;
sessionOrder: number;
reason: string;
coveredTopics: string[];
completedExercises: string[];
completedReflections?: string[];
userConfirmed: boolean;
readyForNextSession: boolean;
chatSessionId?: string;
};
}) => {
if (!effectiveUserId) return;
if (import.meta.env.DEV) {
console.debug('[AI Coach] Calling completeSession:', {
userId: effectiveUserId,
sessionId: payload.sessionId,
sessionOrder: payload.sessionOrder,
reason: payload.reason,
});
}
const signal = {
...(payload.signal ?? {
sessionComplete: true as const,
sessionId: payload.sessionId,
sessionOrder: payload.sessionOrder,
reason: payload.reason,
coveredTopics: [],
completedExercises: [],
userConfirmed: true as const,
readyForNextSession: payload.readyForNextSession,
}),
chatSessionId: payload.chatSessionId ?? payload.signal?.chatSessionId,
};
const updated = await completeSessionWithBackend(effectiveUserId, signal);
localStorage.removeItem(`chat-session:${effectiveUserId}:${payload.sessionOrder}`);
await refreshCurrentSession();
await reloadProgress();
const isFinalSession = Boolean(updated.completedAt);
if (isFinalSession) {
await markTrainingDone();
toast({
title: 'دوره آموزشی تکمیل شد',
description: 'پس‌آزمون برای شما فعال شد.',
});
navigate('/assessment/post', { replace: true });
return;
}
toast({
title: 'جلسه تکمیل شد',
description: 'جلسه بعدی برای شما باز شد.',
});
},
[effectiveUserId, markTrainingDone, navigate, refreshCurrentSession, reloadProgress, toast]
);
useEffect(() => {
if (!waitingForNextSession?.unlocksAt) {
return;
}
const unlockMs = new Date(waitingForNextSession.unlocksAt).getTime();
const delay = unlockMs - Date.now();
if (delay <= 0) {
void refreshCurrentSession();
return;
}
const timer = window.setTimeout(() => {
void refreshCurrentSession();
}, delay + 500);
return () => window.clearTimeout(timer);
}, [refreshCurrentSession, waitingForNextSession?.unlocksAt]);
useEffect(() => {
if (
!effectiveUserId ||
progressLoading ||
!progress?.pre_test_completed_at ||
progress.training_completed_at ||
progress.post_test_completed_at ||
!isProgramComplete
) {
return;
}
void markTrainingDone();
}, [
effectiveUserId,
isProgramComplete,
markTrainingDone,
progress?.post_test_completed_at,
progress?.pre_test_completed_at,
progress?.training_completed_at,
progressLoading,
]);
const {
messages,
loading,
isAiThinking,
isSessionTransitionPending,
sendMessage,
startCoachingSession,
markAssistantStreamComplete,
} = useChat({
coachContext,
userId: effectiveUserId,
onCoachSessionCompleted: handleCoachSessionCompleted,
});
const [message, setMessage] = useState('');
const [isSending, setIsSending] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const typedMessagesRef = useRef<Set<string>>(new Set()); // Track which messages have been typed
const messagesScrollRef = useRef<HTMLDivElement>(null);
const currentSessionAnchorRef = useRef<HTMLDivElement>(null);
const streamScrollRafRef = useRef<number | null>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
const resizeComposer = useCallback(() => {
const el = composerRef.current;
if (!el) return;
const previous = el.offsetHeight;
el.style.transition = 'none';
el.style.height = 'auto';
const next = Math.min(Math.max(el.scrollHeight, 48), 144);
el.style.height = `${previous}px`;
void el.offsetHeight;
el.style.transition = 'height 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
el.style.height = `${next}px`;
}, []);
const scrollToBottom = useCallback(() => {
const scroller = messagesScrollRef.current;
if (!scroller) return;
scroller.scrollTop = scroller.scrollHeight;
}, []);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
if (loading || isSessionTransitionPending) return;
// On enter / session change: jump to the latest message.
let cancelled = false;
const frame = window.requestAnimationFrame(() => {
window.requestAnimationFrame(() => {
if (!cancelled) scrollToBottom();
});
});
return () => {
cancelled = true;
window.cancelAnimationFrame(frame);
};
}, [loading, coachContext?.order, messages.length, scrollToBottom, isSessionTransitionPending]);
const handleSend = async (e?: React.FormEvent, initialMessage?: string, skipUserMessage = false) => {
useEffect(() => {
if (loading) return;
if (!isAiThinking && messages.every((msg) => msg.status !== 'streaming')) {
return;
}
scrollToBottom();
}, [messages, isAiThinking, loading, scrollToBottom]);
const handleStreamProgress = useCallback(() => {
if (streamScrollRafRef.current !== null) return;
streamScrollRafRef.current = window.requestAnimationFrame(() => {
streamScrollRafRef.current = null;
scrollToBottom();
});
}, [scrollToBottom]);
const handleStreamComplete = useCallback(
(messageId: string) => {
markAssistantStreamComplete(messageId);
scrollToBottom();
},
[markAssistantStreamComplete, scrollToBottom]
);
if (!guestSessionHydrated) {
return (
<div className="flex h-full min-h-0 flex-1 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-neon-cyan" />
</div>
);
}
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
if (!progressLoading && progress) {
if (progress.post_test_completed_at) {
return <Navigate to="/finished" replace />;
}
if (progress.training_completed_at) {
return <Navigate to="/assessment/post" replace />;
}
if (!permissions.canOpenTraining) {
return <Navigate to="/assessment/pre" replace />;
}
} else if (!progressLoading && !permissions.canOpenTraining) {
return <Navigate to="/assessment/pre" replace />;
}
const isWaitingForUnlock = Boolean(waitingForNextSession);
const completedSessions =
programProgress?.completedSessions.length ??
getProgramProgress(effectiveUserId).completedSessions.length;
const progressPercent = Math.round((completedSessions / PROGRAM_SESSION_COUNT) * 100);
const sessionOrder =
currentSession?.order ??
coachContext?.order ??
waitingForNextSession?.sessionOrder ??
null;
const sessionTitle =
currentSession?.title ??
coachContext?.title ??
waitingForNextSession?.title ??
null;
const remainingUnlockLabel = waitingForNextSession
? formatRemainingUnlockTime(new Date(waitingForNextSession.unlocksAt))
: null;
const currentSessionMessages = messages.filter(
(msg) => msg.sessionOrder === sessionOrder || msg.sessionOrder == null
);
const hasCurrentSessionMessages = currentSessionMessages.length > 0;
const showStartPrompt =
!loading &&
!isAiThinking &&
!hasCurrentSessionMessages &&
!isWaitingForUnlock &&
!isSessionTransitionPending;
const isStreamBusy =
isAiThinking ||
isSessionTransitionPending ||
messages.some((msg) => msg.status === 'streaming');
const composerDisabled =
loading || !effectiveUserId || isStreamBusy || isSending || showStartPrompt || isWaitingForUnlock;
const composerPlaceholder = loading
? 'در حال بارگذاری...'
: isWaitingForUnlock
? 'جلسه بعدی به‌زودی باز می‌شود'
: isSessionTransitionPending
? 'در حال جمع‌بندی جلسه...'
: showStartPrompt
? 'برای شروع جلسه بعد، دکمه بالا را بزن'
: 'پاسخ خود را بنویسید...';
const handleSend = async (e?: FormEvent, initialMessage?: string, skipUserMessage = false) => {
e?.preventDefault();
if (!user) {
if (!effectiveUserId) {
toast({
title: 'خطا',
description: 'لطفا ابتدا وارد حساب کاربری شوید',
variant: 'destructive'
variant: 'destructive',
});
return;
}
const messageToSend = initialMessage || message;
if (!messageToSend.trim()) {
const messageToSend = (initialMessage || message).trim();
if (!messageToSend) {
return;
}
if (!initialMessage) {
setMessage('');
requestAnimationFrame(() => {
const el = composerRef.current;
if (!el) return;
el.style.transition = 'height 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
el.style.height = '48px';
});
}
setIsSending(true);
try {
// @ts-ignore - skipUserMessage parameter exists
await sendMessage(messageToSend, user.id, skipUserMessage);
if (!initialMessage) {
setMessage('');
}
await sendMessage(messageToSend, effectiveUserId, skipUserMessage);
} catch (error) {
const description =
error instanceof Error
? error.message
: 'خطا در ارسال پیام';
toast({
title: 'خطا',
description,
variant: 'destructive'
description: getFetchErrorMessage(error, 'خطا در ارسال پیام'),
variant: 'destructive',
});
} finally {
setIsSending(false);
}
};
const handleStartChat = () => {
// skipUserMessage = true یعنی پیام کاربر نمایش داده نمی‌شود
handleSend(undefined, 'سلام', true);
const handleStartChat = async () => {
if (!effectiveUserId) {
toast({
title: 'خطا',
description: 'لطفا ابتدا وارد حساب کاربری شوید',
variant: 'destructive',
});
return;
}
setIsSending(true);
try {
if (coachContext) {
await startCoachingSession(effectiveUserId);
} else {
await sendMessage('سلام', effectiveUserId, true);
}
} catch (error) {
toast({
title: 'خطا',
description: getFetchErrorMessage(error, 'خطا در شروع گفتگو'),
variant: 'destructive',
});
} finally {
setIsSending(false);
}
};
const getUserDisplayName = (msg: typeof messages[0]) => {
if (msg?.role === 'assistant') return 'دستیار هوشمند';
if (msg.user_id === user?.id) return 'شما';
// For other users, show a simplified identifier
// In production, you'd fetch from a profiles table
const getUserDisplayName = (msg: (typeof messages)[0]) => {
if (msg?.role === 'assistant') return APP_NAME;
if (msg.user_id === effectiveUserId) return isGuest ? 'شما (مهمان)' : 'شما';
if (msg.user?.full_name) return msg.user.full_name;
if (msg.user?.email) return msg.user.email;
if (msg.user?.phone) return msg.user.phone;
return `کاربر ${msg.user_id.substring(0, 8)}`;
};
const getUserInitials = (msg: typeof messages[0]) => {
if (msg?.role === 'assistant') return 'هو';
const name = getUserDisplayName(msg);
if (name === 'شما') return 'ش';
if (name.length >= 2) return name.substring(0, 2);
return 'ک';
};
// Component for message bubble with typewriter effect for AI messages
const MessageBubble = ({
message,
isOwnMessage,
isAssistant,
getUserDisplayName,
getUserInitials
}: {
message: typeof messages[0];
isOwnMessage: boolean;
isAssistant: boolean;
getUserDisplayName: (msg: typeof messages[0]) => string;
getUserInitials: (msg: typeof messages[0]) => string;
}) => {
// Check if this message has already been typed
const hasBeenTyped = typedMessagesRef.current.has(message.id);
// If it's an assistant message and hasn't been typed yet, use typewriter
const shouldAnimate = isAssistant && !hasBeenTyped && !!message.content;
// Only use typewriter for assistant messages that haven't been typed yet
const typewriterResult = useTypewriter({
text: shouldAnimate ? message.content : '',
speed: 10, // سرعت تایپ سریع‌تر (میلی‌ثانیه)
onComplete: () => {
// Mark this message as typed when animation completes
if (isAssistant && message.id) {
typedMessagesRef.current.add(message.id);
}
}
});
// Determine final text to display
// Priority: animated text (if available) > message.content
let finalText: string;
if (isAssistant && shouldAnimate) {
// For assistant messages with animation, use displayedText if it exists, otherwise fallback to content
finalText = typewriterResult.displayedText.length > 0
? typewriterResult.displayedText
: message.content || '';
} else {
// For user messages or already-typed assistant messages, show full content
finalText = message.content || '';
}
const showCursor = isAssistant && shouldAnimate && typewriterResult.isTyping;
return (
<div
className={`flex gap-3 ${isOwnMessage ? 'flex-row-reverse' : 'flex-row'}`}
>
<Avatar className="h-8 w-8 flex-shrink-0">
<AvatarImage src={message.user?.avatar_url} />
<AvatarFallback className="text-xs">
{getUserInitials(message)}
</AvatarFallback>
</Avatar>
<div className={`flex-1 ${isOwnMessage ? 'text-left' : 'text-right'}`}>
<div className="flex items-center gap-2 mb-1 flex-wrap">
<span className="text-xs font-medium">
{getUserDisplayName(message)}
</span>
<span className="text-xs text-muted-foreground">
{new Date(message.created_at).toLocaleTimeString('fa-IR', {
hour: '2-digit',
minute: '2-digit'
})}
</span>
</div>
<div
className={`rounded-lg p-3 ${
isOwnMessage
? 'bg-primary text-primary-foreground ml-auto'
: isAssistant
? 'bg-secondary text-secondary-foreground'
: 'bg-muted'
}`}
style={{
maxWidth: '85%',
marginRight: isOwnMessage ? '0' : 'auto',
marginLeft: isOwnMessage ? 'auto' : '0'
}}
>
<p className="text-xs whitespace-pre-wrap break-words">
{finalText}
{showCursor && (
<span className="inline-block w-2 h-4 bg-current ml-1 animate-pulse">|</span>
)}
</p>
{message.status === 'error' && (
<span className="mt-2 block text-[10px] text-destructive">
ارسال ناموفق بود. دوباره تلاش کنید.
</span>
)}
</div>
</div>
</div>
);
};
return (
<div className="min-h-screen bg-gradient-to-br from-background to-muted p-4 pb-20">
<div className="mx-auto max-w-sm">
<div className="mb-4">
<h1 className="text-2xl font-bold mb-2">چت</h1>
<p className="text-sm text-muted-foreground">ارسال پیام و ارتباط با دیگران</p>
<div className="flex h-full min-h-0 flex-1 flex-col overflow-hidden">
<div className="glass-panel-chat relative flex min-h-0 flex-1 flex-col gap-4 overflow-hidden p-4">
<div className="relative z-10 shrink-0">
{isProgramComplete ? (
<p className="text-center text-xs text-muted-foreground">دوره آموزشی تکمیل شده</p>
) : isWaitingForUnlock && waitingForNextSession ? (
<p className="text-center text-xs text-muted-foreground">
«{waitingForNextSession.title}» تا {remainingUnlockLabel} دیگر باز می‌شود
</p>
) : !sessionOrder ? (
<p className="text-center text-xs text-muted-foreground">جلسه فعالی در دسترس نیست</p>
) : (
<div className="space-y-2">
<div className="flex items-center gap-2.5">
<span className="shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-foreground">
{sessionOrder}/{PROGRAM_SESSION_COUNT}
</span>
<p className="min-w-0 flex-1 truncate text-[13px] font-medium text-foreground">{sessionTitle}</p>
</div>
<div
className="h-[2px] w-full overflow-hidden rounded-full bg-black/10 dark:bg-white/[0.06]"
role="progressbar"
aria-valuenow={progressPercent}
aria-valuemin={0}
aria-valuemax={100}
aria-label="پیشرفت دوره"
>
<div
className="h-full rounded-full bg-gradient-to-l from-neon-cyan/80 to-neon-emerald/70 transition-all duration-500"
style={{ width: `${progressPercent}%` }}
/>
</div>
</div>
)}
</div>
<Card className="flex flex-col h-[calc(100vh-14rem)]">
<CardHeader>
<div className="flex items-center gap-2">
<MessageSquare className="h-6 w-6 text-primary" />
<CardTitle className="text-lg">پیام‌ها</CardTitle>
</div>
<CardDescription className="text-sm">
{loading ? 'در حال بارگذاری...' : `${messages.length} پیام`}
</CardDescription>
</CardHeader>
<CardContent className="flex-1 flex flex-col overflow-hidden">
{loading ? (
<div className="flex items-center justify-center flex-1">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : (
<>
<div className="flex-1 overflow-y-auto space-y-4 mb-4 pr-2">
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full py-8">
<div className="text-center mb-6">
<MessageSquare className="h-16 w-16 text-muted-foreground mx-auto mb-4 opacity-50" />
<p className="text-muted-foreground mb-2">به چت هوشمند خوش آمدید</p>
<p className="text-sm text-muted-foreground">
برای شروع گفتگو، دکمه زیر را بزنید
</p>
</div>
<div
ref={messagesScrollRef}
className="relative z-10 min-h-0 flex-1 overflow-y-auto overscroll-contain"
>
{loading ? (
<div className="flex h-full items-center justify-center py-6">
<Loader2 className="h-8 w-8 animate-spin text-neon-cyan" />
</div>
) : messages.length === 0 && !isAiThinking ? (
<div className="flex h-full min-h-0 flex-col items-center justify-center px-1 py-6 text-center">
<div className="mb-5 flex h-14 w-14 items-center justify-center rounded-full bg-white/20 text-neon-cyan backdrop-blur-md dark:bg-white/10">
<Sparkles className="h-7 w-7" />
</div>
{isWaitingForUnlock && waitingForNextSession ? (
<>
<h2 className="mb-2 text-lg font-semibold text-foreground">جلسه بعدی به‌زودی باز می‌شود</h2>
<p className="mb-2 max-w-sm text-sm leading-6 text-muted-foreground">
جلسه «{waitingForNextSession.title}» یک ساعت پس از پایان جلسه قبل باز می‌شود.
</p>
<p className="max-w-sm text-sm font-medium text-foreground">
زمان باقی‌مانده: {remainingUnlockLabel}
</p>
</>
) : (
<>
<h2 className="mb-2 text-lg font-semibold text-foreground">شروع جلسه با {APP_NAME}</h2>
<p className="mb-6 max-w-sm text-sm leading-6 text-muted-foreground">
{sessionTitle
? `${APP_NAME} شما را در جلسه «${sessionTitle}» راهنمایی می‌کند — محتوا از طریق گفتگو ارائه می‌شود.`
: `${APP_NAME} مسیر آموزشی را از طریق گفتگو هدایت می‌کند.`}
</p>
<Button
onClick={handleStartChat}
disabled={isSending || !user}
disabled={isSending || !effectiveUserId || !coachContext}
size="lg"
variant="neon"
className="gap-2"
>
{isSending ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
در حال اتصال...
در حال آماده‌سازی...
</>
) : (
<>
<Play className="h-5 w-5" />
<Sparkles className="h-5 w-5" />
شروع گفتگو
</>
)}
</Button>
</div>
) : (
messages.map((msg) => {
const isOwnMessage = msg.user_id === user?.id && msg.role !== 'assistant';
const isAssistant = msg.role === 'assistant';
return (
</>
)}
</div>
) : (
<div className="space-y-5">
{messages.map((msg, index) => {
const isOwnMessage = msg.user_id === effectiveUserId && msg.role !== 'assistant';
const isAssistant = msg.role === 'assistant';
const msgSessionOrder = msg.sessionOrder ?? sessionOrder ?? 0;
const isPastSession =
sessionOrder != null &&
msg.sessionOrder != null &&
msg.sessionOrder < sessionOrder;
const prevOrder =
index > 0
? messages[index - 1]?.sessionOrder ?? msgSessionOrder
: msgSessionOrder;
const showSessionDivider =
index === 0 ||
(msg.sessionOrder != null && msg.sessionOrder !== prevOrder);
const isCurrentSessionStart =
showSessionDivider &&
sessionOrder != null &&
msgSessionOrder === sessionOrder;
const dividerTitle =
getSessionByOrder(msgSessionOrder)?.title ?? `جلسه ${msgSessionOrder}`;
return (
<Fragment key={msg.id}>
{showSessionDivider && (
<div
ref={isCurrentSessionStart ? currentSessionAnchorRef : undefined}
className="flex items-center gap-3 py-1"
>
<div className="h-px flex-1 bg-foreground/10" />
<span
className={`shrink-0 text-[11px] font-medium ${
isPastSession
? 'text-muted-foreground/80'
: 'text-neon-cyan'
}`}
>
جلسه {msgSessionOrder}
{dividerTitle ? ` — ${dividerTitle}` : ''}
</span>
<div className="h-px flex-1 bg-foreground/10" />
</div>
)}
<MessageBubble
key={msg.id}
message={msg}
isOwnMessage={isOwnMessage}
isAssistant={isAssistant}
getUserDisplayName={getUserDisplayName}
getUserInitials={getUserInitials}
displayName={getUserDisplayName(msg)}
isPastSession={isPastSession}
onStreamProgress={handleStreamProgress}
onStreamComplete={handleStreamComplete}
/>
);
})
</Fragment>
);
})}
{showStartPrompt && (
<div
ref={currentSessionAnchorRef}
className="flex flex-col items-center gap-3 py-6 text-center"
>
<p className="max-w-sm text-sm text-muted-foreground">
{sessionTitle
? `آماده شروع جلسه «${sessionTitle}» هستی؟`
: 'آماده شروع جلسه جدید هستی؟'}
</p>
<Button
onClick={handleStartChat}
disabled={isSending || !effectiveUserId || !coachContext}
size="lg"
variant="neon"
className="gap-2"
>
{isSending ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
در حال آماده‌سازی...
</>
) : (
<>
<Sparkles className="h-5 w-5" />
شروع جلسه جدید
</>
)}
</Button>
</div>
)}
{isAiThinking && <AiThinkingBubble />}
<div ref={messagesEndRef} />
</div>
<form onSubmit={handleSend} className="flex gap-2">
<Input
placeholder="پیام خود را بنویسید..."
value={message}
onChange={(e) => setMessage(e.target.value)}
disabled={isSending || !user}
/>
<Button type="submit" disabled={isSending || !user || !message.trim()}>
{isSending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
</Button>
</form>
</>
)}
</CardContent>
</Card>
)}
</div>
<div className="relative z-10 w-full shrink-0">
<form onSubmit={handleSend} className="w-full">
<div className="composer-glass">
<textarea
ref={composerRef}
rows={1}
placeholder={composerPlaceholder}
value={message}
onChange={(e) => {
setMessage(e.target.value);
resizeComposer();
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
if (!composerDisabled && message.trim()) {
void handleSend();
}
}
}}
disabled={composerDisabled}
className="input-neon max-h-36 min-h-12 flex-1 resize-none overflow-y-auto border-0 bg-transparent py-3 text-right text-base leading-6 text-foreground placeholder:text-muted-foreground shadow-none outline-none backdrop-blur-none focus-visible:border-0 focus-visible:shadow-none focus-visible:ring-0 disabled:opacity-60"
aria-label={`پیام به ${APP_NAME}`}
/>
<Button
type="submit"
size="icon"
variant="neon"
className="mb-0.5 h-10 w-10 shrink-0 rounded-xl p-0 disabled:opacity-70 [&_svg]:h-6 [&_svg]:w-6"
disabled={composerDisabled || !message.trim()}
aria-label="ارسال"
>
{isSending ? (
<Loader2 className="h-6 w-6 animate-spin" />
) : (
<ArrowUp className="h-6 w-6" strokeWidth={2.75} />
)}
</Button>
</div>
</form>
</div>
</div>
</div>
);
+59
View File
@@ -0,0 +1,59 @@
import { Navigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { Check, CheckCircle2, Loader2 } from 'lucide-react';
export default function FinishedPage() {
const { effectiveUserId, guestSessionHydrated } = useAuth();
const { permissions, loading } = useLearningJourney(effectiveUserId ?? undefined);
if (!guestSessionHydrated || loading) {
return (
<div className="flex min-h-[50vh] items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-neon-cyan" />
</div>
);
}
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
if (!permissions.isCompleted) {
return <Navigate to="/" replace />;
}
return (
<div className="h-full min-h-0 flex-1 overflow-y-auto px-4 py-10">
<div className="mx-auto flex w-full max-w-md flex-col items-center gap-8 text-center">
<div className="avatar-glow">
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-white text-emerald-600 shadow-sm dark:bg-navy dark:text-neon-emerald dark:shadow-none">
<CheckCircle2 className="h-9 w-9" aria-hidden />
</div>
</div>
<h1 className="text-xl font-bold leading-8 text-foreground sm:text-2xl">
دوره آموزشی شما با موفقیت به پایان رسید.
</h1>
<ul className="glass-panel w-full space-y-3 px-4 py-4 text-right text-sm text-body">
<li className="flex items-center gap-2">
<Check className="h-4 w-4 shrink-0 text-neon-emerald" aria-hidden />
پیش‌آزمون انجام شده
</li>
<li className="flex items-center gap-2">
<Check className="h-4 w-4 shrink-0 text-neon-emerald" aria-hidden />
دوره آموزشی تکمیل شده
</li>
<li className="flex items-center gap-2">
<Check className="h-4 w-4 shrink-0 text-neon-emerald" aria-hidden />
پس‌آزمون انجام شده
</li>
</ul>
<p className="text-sm text-muted-foreground">
از منوی پروفایل می‌توانید وضعیت دوره را ببینید یا خارج شوید.
</p>
</div>
</div>
);
}
+27 -2
View File
@@ -1,11 +1,13 @@
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/hooks/useAuth';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { useNavigate } from 'react-router-dom';
import { Home, User, MessageSquare, FileText } from 'lucide-react';
import { Home, User, MessageSquare, FileText, ClipboardCheck } from 'lucide-react';
export default function MainPage() {
const { user, isAuthenticated } = useAuth();
const { progress, permissions } = useLearningJourney(user?.id);
const navigate = useNavigate();
return (
@@ -15,7 +17,7 @@ export default function MainPage() {
<h1 className="text-2xl font-bold mb-2">خوش آمدید</h1>
<p className="text-sm text-muted-foreground">
{isAuthenticated && user
? `سلام ${user.email || user.phone || 'کاربر'}`
? `سلام ${user.email || 'کاربر'}`
: 'به اپلیکیشن پیشرفته PWA خوش آمدید'}
</p>
</div>
@@ -59,6 +61,19 @@ export default function MainPage() {
</Button>
</CardContent>
</Card>
<Card className="cursor-pointer transition-all hover:shadow-lg" onClick={() => navigate('/assessment/pre')}>
<CardHeader>
<ClipboardCheck className="mb-2 h-7 w-7 text-primary" />
<CardTitle className="text-lg">آزمون‌ها</CardTitle>
<CardDescription className="text-sm">اجرای پیش‌آزمون و پس‌آزمون</CardDescription>
</CardHeader>
<CardContent>
<Button variant="outline" className="w-full">
شروع
</Button>
</CardContent>
</Card>
</div>
<Card className="mt-6">
@@ -83,6 +98,16 @@ export default function MainPage() {
</div>
<div className="text-xs text-muted-foreground">وضعیت ورود</div>
</div>
<div className="rounded-lg border p-4">
<div className="text-sm font-semibold">
{permissions.isCompleted
? 'تکمیل‌شده'
: progress?.pre_test_completed_at
? 'در حال آموزش'
: 'آماده پیش‌آزمون'}
</div>
<div className="text-xs text-muted-foreground">وضعیت مسیر آموزشی</div>
</div>
</div>
</CardContent>
</Card>
+180
View File
@@ -0,0 +1,180 @@
import { useState, type FormEvent } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/components/ui/use-toast';
import { hasSessionToken } from '@/services/backend';
import { getBackendErrorMessage } from '@/lib/backendError';
import { AnimationWrapper } from '@/components/motion';
import { Loader2, Sparkles } from 'lucide-react';
import { ROUTES } from '@/utils/constants';
const NAME_MAX_LENGTH = 100;
const toAsciiDigits = (value: string) =>
value.replace(/[۰-۹٠-٩]/g, (digit) => {
const persian = '۰۱۲۳۴۵۶۷۸۹'.indexOf(digit);
if (persian >= 0) return String(persian);
const arabic = '٠١٢٣٤٥٦٧٨٩'.indexOf(digit);
return arabic >= 0 ? String(arabic) : digit;
});
const parseAge = (raw: string): number | null => {
const normalized = toAsciiDigits(raw.trim());
if (!normalized || !/^-?\d+$/.test(normalized)) return null;
const age = Number(normalized);
return Number.isInteger(age) ? age : null;
};
const profileErrorMessage = (error: unknown): string =>
getBackendErrorMessage(error, 'ذخیره مشخصات انجام نشد. لطفاً دوباره تلاش کنید.');
export default function ProfileCompletionPage() {
const navigate = useNavigate();
const { user, updateProfile, isAuthenticated } = useAuth();
const { toast } = useToast();
const [name, setName] = useState('');
const [age, setAge] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [fieldError, setFieldError] = useState<{ name?: string; age?: string }>({});
// Send to login (not home): home's ProtectedRoute re-routes incomplete
// backend users to /profile, which would infinite-loop when the token is gone.
if (!isAuthenticated || !hasSessionToken()) {
return <Navigate to={ROUTES.LOGIN} replace />;
}
if (user?.profileComplete) {
return <Navigate to={ROUTES.HOME} replace />;
}
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
const trimmedName = name.trim();
const parsedAge = parseAge(age);
const nextErrors: { name?: string; age?: string } = {};
if (!trimmedName) {
nextErrors.name = 'اسمت را بنویس';
}
if (parsedAge === null) {
nextErrors.age = 'سن باید یک عدد صحیح باشد';
}
setFieldError(nextErrors);
if (nextErrors.name || nextErrors.age) {
toast({
title: 'خطا',
description: nextErrors.name || nextErrors.age,
variant: 'destructive',
});
return;
}
setIsLoading(true);
try {
await updateProfile(trimmedName, parsedAge as number);
toast({ title: 'موفق', description: 'مشخصاتت ذخیره شد' });
navigate(ROUTES.HOME, { replace: true });
} catch (error: unknown) {
toast({
title: 'خطا',
description: profileErrorMessage(error),
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
return (
<div className="app-auth-screen ambient-glow relative flex h-full min-h-0 items-center justify-center overflow-y-auto p-4">
<AnimationWrapper immediate interactive={false} className="relative z-10 w-full max-w-sm">
<Card className="relative w-full overflow-hidden">
<div
className="pointer-events-none absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-neon-blue/20 via-neon-cyan/5 to-transparent"
aria-hidden
/>
<CardHeader className="relative space-y-2">
<div className="mb-2 flex justify-center">
<div className="avatar-glow">
<div className="flex h-14 w-14 items-center justify-center rounded-full bg-white text-cyan-700 shadow-sm dark:bg-navy dark:text-neon-cyan dark:shadow-none">
<Sparkles className="h-7 w-7" />
</div>
</div>
</div>
<CardTitle className="text-center text-2xl font-bold tracking-tight text-foreground">
قبل از شروع، کمی با هم آشنا بشیم
</CardTitle>
<CardDescription className="text-center text-body">
اسم و سنت را بنویس تا مسیر یادگیری‌ات را ادامه بدهیم.
</CardDescription>
</CardHeader>
<CardContent className="relative space-y-4">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="profile-name" className="text-body">
اسمت چیه؟
</Label>
<Input
id="profile-name"
type="text"
placeholder="نام"
value={name}
onChange={(event) => {
setName(event.target.value);
if (fieldError.name) setFieldError((current) => ({ ...current, name: undefined }));
}}
disabled={isLoading}
maxLength={NAME_MAX_LENGTH}
autoComplete="name"
aria-invalid={Boolean(fieldError.name)}
/>
{fieldError.name ? (
<p className="text-xs text-red-400">{fieldError.name}</p>
) : null}
</div>
<div className="space-y-2">
<Label htmlFor="profile-age" className="text-body">
چند سالته؟
</Label>
<Input
id="profile-age"
type="text"
inputMode="numeric"
placeholder="سن"
value={age}
onChange={(event) => {
setAge(event.target.value);
if (fieldError.age) setFieldError((current) => ({ ...current, age: undefined }));
}}
disabled={isLoading}
autoComplete="off"
aria-invalid={Boolean(fieldError.age)}
/>
{fieldError.age ? <p className="text-xs text-red-400">{fieldError.age}</p> : null}
</div>
<Button type="submit" variant="neon" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ذخیره...
</>
) : (
'ادامه'
)}
</Button>
</form>
</CardContent>
</Card>
</AnimationWrapper>
</div>
);
}
+200
View File
@@ -0,0 +1,200 @@
import { useState, useEffect } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { useAuth } from '@/hooks/useAuth';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { Loader2, BookOpen, CheckCircle2, Lock, ChevronLeft } from 'lucide-react';
import {
PROGRAM_SESSIONS,
} from '@/data/program/sessions';
import {
getProgramProgress,
isSessionUnlocked,
isSessionCompleted,
isProgramCompleted,
} from '@/services/programService';
export default function ProgramPage() {
const navigate = useNavigate();
const { effectiveUserId, guestSessionHydrated } = useAuth();
const { permissions, loading: journeyLoading } = useLearningJourney(effectiveUserId ?? undefined);
const [progress, setProgress] = useState(getProgramProgress(effectiveUserId ?? ''));
useEffect(() => {
if (!effectiveUserId) return;
setProgress(getProgramProgress(effectiveUserId));
}, [effectiveUserId]);
if (!guestSessionHydrated || journeyLoading) {
return (
<div className="flex min-h-screen items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
if (!permissions.canOpenTraining) {
return <Navigate to="/assessment/pre" replace />;
}
const programCompleted = isProgramCompleted(effectiveUserId);
const completedCount = progress.completedSessions.length;
const totalCount = PROGRAM_SESSIONS.length;
const progressPercent = totalCount > 0 ? (completedCount / totalCount) * 100 : 0;
return (
<div className="min-h-screen bg-gradient-to-br from-background to-muted p-4 pb-20">
<div className="mx-auto max-w-sm">
{/* Header */}
<div className="mb-4">
<Button
variant="ghost"
size="sm"
className="mb-2 px-0"
onClick={() => navigate('/chat')}
>
<ChevronLeft className="h-4 w-4 mr-1" />
بازگشت
</Button>
<h1 className="text-2xl font-bold mb-1">برنامه آموزشی</h1>
<p className="text-sm text-muted-foreground">
{programCompleted
? 'برنامه آموزشی با موفقیت به پایان رسید'
: `${completedCount} از ${totalCount} جلسه تکمیل شده`}
</p>
</div>
{/* Progress Card */}
<Card className="mb-4">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">پیشرفت برنامه</CardTitle>
<span className="text-sm font-medium text-primary">
{Math.round(progressPercent)}%
</span>
</div>
</CardHeader>
<CardContent>
<Progress value={progressPercent} className="h-2" />
{progress.startedAt && (
<p className="mt-2 text-xs text-muted-foreground">
شروع: {new Date(progress.startedAt).toLocaleDateString('fa-IR')}
</p>
)}
</CardContent>
</Card>
{/* Session List */}
<div className="space-y-3">
{PROGRAM_SESSIONS.map((session) => {
const completed = isSessionCompleted(effectiveUserId, session.order);
const unlocked = isSessionUnlocked(effectiveUserId, session.order);
const isCurrent = progress.currentSessionOrder === session.order;
return (
<Card
key={session.id}
className={`transition-colors ${
completed
? 'border-green-500/30 bg-green-500/5'
: isCurrent
? 'border-primary/50'
: ''
}`}
>
<CardContent className="p-4">
<div className="flex items-start gap-3">
{/* Status Icon */}
<div className="flex-shrink-0 mt-0.5">
{completed ? (
<CheckCircle2 className="h-5 w-5 text-green-600" />
) : unlocked ? (
<BookOpen className="h-5 w-5 text-primary" />
) : (
<Lock className="h-5 w-5 text-muted-foreground" />
)}
</div>
{/* Session Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-muted-foreground">
جلسه {session.order}
</span>
{isCurrent && !completed && (
<span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs text-primary">
در حال انجام
</span>
)}
{completed && (
<span className="rounded-full bg-green-500/10 px-2 py-0.5 text-xs text-green-600">
تکمیل شده
</span>
)}
</div>
<p className="mt-1 font-medium text-sm leading-snug">{session.title}</p>
<p className="mt-0.5 text-xs text-muted-foreground line-clamp-2">
{session.description}
</p>
<p className="mt-1 text-xs text-muted-foreground">
~{session.estimatedDurationMinutes} دقیقه
</p>
</div>
{/* Action */}
{unlocked && !completed && (
<Button
size="sm"
variant={isCurrent ? 'default' : 'outline'}
className="flex-shrink-0"
onClick={() => navigate(`/program/${session.id}`)}
>
{isCurrent ? 'ادامه' : 'مشاهده'}
</Button>
)}
{completed && (
<Button
size="sm"
variant="ghost"
className="flex-shrink-0"
onClick={() => navigate(`/program/${session.id}`)}
>
مرور
</Button>
)}
</div>
</CardContent>
</Card>
);
})}
</div>
{/* Program Complete Banner */}
{programCompleted && (
<Card className="mt-4 border-green-500/30 bg-green-500/5">
<CardContent className="p-4 text-center">
<CheckCircle2 className="h-8 w-8 text-green-600 mx-auto mb-2" />
<p className="font-medium text-sm">تبریک! برنامه آموزشی را به پایان رساندید.</p>
<p className="mt-1 text-xs text-muted-foreground">
اکنون می‌توانید پس‌آزمون را انجام دهید.
</p>
<Button
className="mt-3 w-full"
onClick={() => navigate('/assessment/post')}
>
رفتن به پس‌آزمون
</Button>
</CardContent>
</Card>
)}
</div>
</div>
);
}
+173
View File
@@ -0,0 +1,173 @@
import { useState } from 'react';
import { Navigate, useNavigate, useParams } from 'react-router-dom';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/hooks/useAuth';
import { useLearningJourney } from '@/hooks/useLearningJourney';
import { ContentRenderer } from '@/components/program';
import {
getSessionById,
getSessionByOrder,
PROGRAM_SESSIONS,
type ProgramSession
} from '@/data/program/sessions';
import {
completeSession,
isSessionUnlocked,
isSessionCompleted
} from '@/services/programService';
import { ChevronLeft, ChevronRight, CheckCircle2, Clock } from 'lucide-react';
export default function SessionPage() {
const { sessionId } = useParams<{ sessionId: string }>();
const navigate = useNavigate();
const { effectiveUserId } = useAuth();
const { markTrainingDone } = useLearningJourney(effectiveUserId ?? undefined);
const session: ProgramSession | undefined = sessionId ? getSessionById(sessionId) : undefined;
const [completing, setCompleting] = useState(false);
const [completed, setCompleted] = useState(
session ? isSessionCompleted(effectiveUserId ?? '', session.order) : false
);
if (!effectiveUserId) {
return <Navigate to="/login" replace />;
}
if (!session) {
return <Navigate to="/program" replace />;
}
if (!isSessionUnlocked(effectiveUserId, session.order)) {
return <Navigate to="/program" replace />;
}
const isFinalSession = session.order === PROGRAM_SESSIONS.length;
const prevSession = session.order > 1 ? getSessionByOrder(session.order - 1) : null;
const nextSession =
session.order < PROGRAM_SESSIONS.length ? getSessionByOrder(session.order + 1) : null;
const handleComplete = async () => {
if (!effectiveUserId || completing || completed) return;
setCompleting(true);
try {
completeSession(effectiveUserId, session.order);
setCompleted(true);
if (isFinalSession) {
await markTrainingDone();
}
if (nextSession) {
navigate(`/program/${nextSession.id}`);
} else {
navigate('/program');
}
} finally {
setCompleting(false);
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-background to-muted p-4 pb-24">
<div className="mx-auto max-w-sm">
<div className="mb-4 flex items-center justify-between">
<Button variant="ghost" size="sm" className="px-0" onClick={() => navigate('/program')}>
<ChevronLeft className="h-4 w-4 mr-1" />
برنامه
</Button>
<span className="text-xs text-muted-foreground">
جلسه {session.order} از {PROGRAM_SESSIONS.length}
</span>
</div>
<Card className="mb-4">
<CardHeader>
<div className="flex items-start justify-between gap-2">
<div>
<CardDescription>جلسه {session.order}</CardDescription>
<CardTitle className="text-lg leading-snug mt-1">{session.title}</CardTitle>
</div>
{completed && <CheckCircle2 className="h-5 w-5 flex-shrink-0 text-green-600" />}
</div>
<div className="flex items-center gap-3 text-xs text-muted-foreground mt-2">
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />~{session.estimatedDurationMinutes} دقیقه
</span>
<span>·</span>
<span>{session.description}</span>
</div>
</CardHeader>
</Card>
<Card className="mb-4">
<CardHeader>
<CardTitle className="text-base">محتوای آموزشی</CardTitle>
</CardHeader>
<CardContent>
<ContentRenderer blocks={session.blocks} />
</CardContent>
</Card>
{!completed && (
<div className="fixed bottom-4 left-0 right-0 px-4">
<div className="mx-auto max-w-sm">
<Button className="w-full" size="lg" disabled={completing} onClick={handleComplete}>
{completing ? (
'در حال ثبت...'
) : isFinalSession ? (
'پایان برنامه آموزشی'
) : (
<>
تکمیل جلسه و ادامه
<ChevronRight className="h-4 w-4 mr-2" />
</>
)}
</Button>
</div>
</div>
)}
{completed && (
<Card className="mb-4 border-green-500/30 bg-green-500/5">
<CardContent className="p-4 text-center">
<CheckCircle2 className="h-6 w-6 text-green-600 mx-auto mb-2" />
<p className="text-sm font-medium text-green-700 dark:text-green-300">
این جلسه تکمیل شده است
</p>
<Button variant="outline" className="mt-3 w-full" onClick={() => navigate('/program')}>
بازگشت به برنامه
</Button>
</CardContent>
</Card>
)}
<div className="flex gap-2">
{prevSession && (
<Button
variant="outline"
className="flex-1"
onClick={() => navigate(`/program/${prevSession.id}`)}
>
<ChevronLeft className="h-4 w-4 mr-1" />
جلسه قبلی
</Button>
)}
{nextSession && !completed && (
<Button
variant="outline"
className="flex-1"
onClick={() => navigate(`/program/${nextSession.id}`)}
>
جلسه بعدی
<ChevronRight className="h-4 w-4 ml-1" />
</Button>
)}
</div>
</div>
</div>
);
}