DoneAuthContext

This commit is contained in:
fullofempt
2025-12-13 18:30:48 +05:00
parent 48d4db0e77
commit b1cab4a2ab
7 changed files with 560 additions and 50 deletions

View File

@@ -2,16 +2,19 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useAuth } from "../app/context/AuthContext";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const AuthPage = () => { const AuthPage = () => {
const router = useRouter(); const router = useRouter();
const { login } = useAuth();
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(false); const [rememberMe, setRememberMe] = useState(false);
const [checkboxError, setCheckboxError] = useState(false); const [checkboxError, setCheckboxError] = useState(false);
const [authError, setAuthError] = useState("");
const isEmailValid = emailRegex.test(email); const isEmailValid = emailRegex.test(email);
const isFormValid = isEmailValid && password.length > 0; const isFormValid = isEmailValid && password.length > 0;
@@ -19,24 +22,24 @@ const AuthPage = () => {
const handleSubmit = (e) => { const handleSubmit = (e) => {
e.preventDefault(); e.preventDefault();
// проверка чекбокса
if (!rememberMe) { if (!rememberMe) {
setCheckboxError(true); setCheckboxError(true);
return; return;
} }
setCheckboxError(false); setCheckboxError(false);
if (!isFormValid) return; if (!isFormValid) return;
console.log("Email:", email, "Password:", password, "Remember:", rememberMe); try {
router.push('./home'); login(email, password); // редирект сделает сам контекст
} catch (err) {
setAuthError(err.message);
}
}; };
return ( return (
<div className="min-h-screen w-full bg-[#90D2F9] flex items-center justify-center px-4"> <div className="min-h-screen w-full bg-[#90D2F9] flex items-center justify-center px-4">
<div className="w-full max-w-md bg-white/10 rounded-2xl p-6 sm:p-8 shadow-lg relative"> <div className="w-full max-w-md bg-white/10 rounded-2xl p-6 sm:p-8 shadow-lg relative">
{/* Красный баннер ошибки по чекбоксу */}
{checkboxError && ( {checkboxError && (
<div <div
className="absolute -top-10 left-0 w-full bg-red-500 text-white text-xs sm:text-sm font-montserrat px-3 py-2 rounded-t-2xl flex items-center justify-center shadow-md" className="absolute -top-10 left-0 w-full bg-red-500 text-white text-xs sm:text-sm font-montserrat px-3 py-2 rounded-t-2xl flex items-center justify-center shadow-md"
@@ -49,9 +52,6 @@ const AuthPage = () => {
<h1 className="font-montserrat text-white font-extrabold text-2xl text-center"> <h1 className="font-montserrat text-white font-extrabold text-2xl text-center">
Авторизация Авторизация
</h1> </h1>
{/* <p className="font-montserrat text-white text-sm text-center mt-1">
как пользователь
</p> */}
<form onSubmit={handleSubmit} className="mt-6 space-y-4"> <form onSubmit={handleSubmit} className="mt-6 space-y-4">
{/* Почта */} {/* Почта */}
@@ -93,22 +93,34 @@ const AuthPage = () => {
setRememberMe((prev) => !prev); setRememberMe((prev) => !prev);
if (!rememberMe) setCheckboxError(false); if (!rememberMe) setCheckboxError(false);
}} }}
className={`w-5 h-5 rounded-full border border-white flex items-center justify-center ${rememberMe ? "bg-white" : "bg-transparent" className={`w-5 h-5 rounded-full border border-white flex items-center justify-center ${
}`} rememberMe ? "bg-white" : "bg-transparent"
}`}
> >
{rememberMe && ( {rememberMe && (
<span className="h-2 w-2 rounded-full bg-[#90D2F9]" /> <span className="h-2 w-2 rounded-full bg-[#90D2F9]" />
)} )}
</button> </button>
<p className="font-montserrat text-[10px] leading-[12px] text-white"> <p className="font-montserrat text-[10px] leading-[12px] text-white">
Подтверждаю, что я прочитал условия использования данного приложения Подтверждаю, что я прочитал условия использования данного
приложения
</p> </p>
</div> </div>
{/* Ошибка авторизации */}
{authError && (
<p className="text-[11px] text-red-600 font-montserrat">
{authError}
</p>
)}
{/* Ссылки */} {/* Ссылки */}
<div className="flex justify-between text-[11px] font-montserrat font-bold text-[#FF6363] mt-1"> <div className="flex justify-between text-[11px] font-montserrat font-bold text-[#FF6363] mt-1">
<button type="button" className="hover:underline" onClick={() => router.push("/recPassword")}> <button
type="button"
className="hover:underline"
onClick={() => router.push("/recPassword")}
>
Забыли пароль? Забыли пароль?
</button> </button>
<button <button
@@ -125,14 +137,23 @@ const AuthPage = () => {
type="submit" type="submit"
disabled={!isFormValid} disabled={!isFormValid}
className={`mt-4 w-full rounded-full py-2 text-center font-montserrat font-extrabold text-sm transition-colors className={`mt-4 w-full rounded-full py-2 text-center font-montserrat font-extrabold text-sm transition-colors
${isFormValid ${
? "bg-green-500 text-white hover:bg-green-600" isFormValid
: "bg-white text-[#C4C4C4] cursor-not-allowed" ? "bg-green-500 text-white hover:bg-green-600"
: "bg-white text-[#C4C4C4] cursor-not-allowed"
}`} }`}
> >
Войти Войти
</button> </button>
</form> </form>
{/* Подсказка по тестовым логинам */}
<div className="mt-4 text-[10px] text-white font-montserrat space-y-1">
<p>Тестовые аккаунты:</p>
<p>Пользователь: user@mail.com / user123</p>
<p>Волонтёр: vol@mail.com / vol123</p>
<p>Модератор: mod@mail.com / mod123</p>
</div>
</div> </div>
</div> </div>
); );

View File

@@ -2,41 +2,59 @@
import React from "react"; import React from "react";
import { FaClock, FaNewspaper, FaHome, FaCog } from "react-icons/fa"; import { FaClock, FaNewspaper, FaHome, FaCog } from "react-icons/fa";
import { useRouter } from "next/navigation"; import { useRouter, usePathname } from "next/navigation";
import { useAuth } from "../context/AuthContext";
const TabBar = () => { const TabBar = () => {
const router = useRouter(); const router = useRouter();
const pathname = usePathname();
const { user } = useAuth();
if (!user) return null; // не показываем таббар, если не залогинен
// маршруты по ролям
const routesByRole = {
user: [
{ key: "home", icon: FaHome, href: "/createRequest" },
{ key: "history", icon: FaClock, href: "/historyRequest" },
{ key: "news", icon: FaNewspaper, href: "/news" },
{ key: "profile", icon: FaCog, href: "/ProfilePage" },
],
volunteer: [
{ key: "home", icon: FaHome, href: "/mainValounter" },
{ key: "history", icon: FaClock, href: "/valounterHistoryRequest" },
{ key: "news", icon: FaNewspaper, href: "/volunteer/news" },
{ key: "profile", icon: FaCog, href: "/volunterProfile" },
],
moderator: [
{ key: "queue", icon: FaHome, href: "/moderator/home" },
{ key: "history", icon: FaClock, href: "/moderator/history" },
{ key: "news", icon: FaNewspaper, href: "/moderator/news" },
{ key: "profile", icon: FaCog, href: "/moderator/profile" },
],
};
const tabs = routesByRole[user.role] || [];
return ( return (
<nav className="fixed bottom-0 left-0 right-0 flex justify-center"> <nav className="fixed bottom-0 left-0 right-0 flex justify-center">
<div className="w-full max-w-md bg-white rounded-t-xl flex items-center justify-around py-4 shadow-inner"> <div className="w-full max-w-md bg-white rounded-t-xl flex items-center justify-around py-4 shadow-inner">
<button {tabs.map((tab) => {
type="button" const Icon = tab.icon;
onClick={() => router.push("/createRequest")} const active = pathname === tab.href;
className="flex flex-col items-center gap-1 text-[#90D2F9]" return (
> <button
<FaHome size={20} /> key={tab.key}
</button> type="button"
<button onClick={() => router.push(tab.href)}
type="button" className={`flex flex-col items-center gap-1 ${
onClick={() => router.push("/historyRequest")} active ? "text-[#90D2F9]" : "text-gray-400"
className="flex flex-col items-center gap-1 text-[#90D2F9]" }`}
> >
<FaClock size={20} /> <Icon size={20} />
</button> </button>
<button );
type="button" })}
className="flex flex-col items-center gap-1 text-[#90D2F9]"
>
<FaNewspaper size={20} />
</button>
<button
type="button"
onClick={() => router.push("/ProfilePage")}
className="flex flex-col items-center gap-1 text-[#90D2F9]"
>
<FaCog size={20} />
</button>
</div> </div>
</nav> </nav>
); );

View File

@@ -0,0 +1,153 @@
import React, { useState } from "react";
import { FaStar } from "react-icons/fa";
const RequestDetailsModal = ({ request, onClose }) => {
const isDone = request.status === "Выполнена";
const isInProgress = request.status === "В процессе";
const [rating, setRating] = useState(0);
const [review, setReview] = useState("");
const handleStarClick = (value) => {
setRating(value);
};
const handleSubmit = () => {
console.log("Отправить отзыв:", {
id: request.id,
status: request.status,
rating,
review,
});
onClose();
};
return (
<div className="fixed inset-0 z-40 flex flex-col bg-[#90D2F9] px-4 pt-4 pb-20">
{/* Хедер */}
<div className="flex items-center gap-2 mb-3">
<button
type="button"
onClick={onClose}
className="text-white w-7 h-7 rounded-full flex items-center justify-center text-lg"
>
</button>
<p className="flex-1 text-center font-montserrat font-extrabold text-[20px] leading-[24px] text-white">
Заявка от {request.createdAt}
</p>
<span className="w-7" />
</div>
{/* Карточка */}
<div className="flex-1 flex items-start justify-center">
<div className="w-full max-w-[360px] bg-white rounded-2xl p-4 flex flex-col gap-4 shadow-lg">
{/* Статус + дата/время */}
<div className="flex items-start justify-between">
<span
className="inline-flex items-center justify-center px-3 py-1 rounded-full font-montserrat text-[10px] font-semibold text-white"
style={{ backgroundColor: request.statusColor }}
>
{request.status}
</span>
<div className="text-right leading-tight">
<p className="font-montserrat text-[10px] text-black">
{request.date}
</p>
<p className="font-montserrat text-[10px] text-black">
{request.time}
</p>
</div>
</div>
{/* Название задачи */}
<p className="font-montserrat font-semibold text-[16px] leading-[20px] text-black">
{request.title}
</p>
{/* Полная информация о заявке */}
<div className="flex flex-col gap-1 text-[12px] font-montserrat text-black">
<p>ФИО: {request.fullName}</p>
<p>Адрес: {request.address}</p>
{request.flat && <p>Квартира: {request.flat}</p>}
{request.floor && <p>Этаж: {request.floor}</p>}
{request.phone && <p>Телефон: {request.phone}</p>}
{request.amount && <p>Сумма: {request.amount}</p>}
{request.deadline && <p>Выполнить до: {request.deadline}</p>}
</div>
{/* Описание / список покупок */}
{request.description && (
<div className="bg-[#E4E4E4] rounded-2xl px-3 py-2 max-h-[140px] overflow-y-auto">
<p className="text-[11px] leading-[13px] font-montserrat whitespace-pre-line">
{request.description}
</p>
</div>
)}
{/* Блок отзыва + рейтинг — и для Выполнена, и для В процессе */}
{(isDone || isInProgress) && (
<>
<div className="bg-[#72B8E2] rounded-3xl p-3 flex flex-col gap-2">
<p className="font-montserrat font-bold text-[12px] text-white">
Отзыв
</p>
<textarea
value={review}
onChange={(e) => setReview(e.target.value)}
rows={4}
className="w-full bg-[#72B8E2] rounded-2xl px-3 py-2 text-sm font-montserrat text-white placeholder:text-white/70 outline-none resize-none border border-white/20"
placeholder={
isDone
? "Напишите, как прошла помощь"
: "Напишите, как сейчас идёт выполнение"
}
/>
</div>
<div className="mt-1 flex flex-col items-center gap-2">
<p className="font-montserrat font-semibold text-[14px] text-black">
Оценить волонтера
</p>
<div className="flex gap-2">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => handleStarClick(star)}
className="text-[#F6E168]"
>
<FaStar
size={26}
className={
star <= rating
? "fill-[#F6E168]"
: "fill-[#F6E168]/40"
}
/>
</button>
))}
</div>
</div>
</>
)}
</div>
</div>
{/* Кнопка внизу */}
{(isDone || isInProgress) && (
<button
type="button"
onClick={handleSubmit}
className="mt-4 w-full max-w-[360px] mx-auto bg-[#94E067] rounded-2xl py-3 flex items-center justify-center"
>
<span className="font-montserrat font-extrabold text-[16px] text-white">
{isDone ? "Оставить отзыв" : "Сохранить прогресс"}
</span>
</button>
)}
</div>
);
};
export default RequestDetailsModal;

View File

@@ -0,0 +1,89 @@
"use client";
import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
const AuthContext = createContext(null);
// фейковые пользователи (3 логина/пароля)
const USERS = [
{
id: 1,
role: "user", // обычный пользователь
name: "Пользователь",
login: "user@mail.com",
password: "user123",
},
{
id: 2,
role: "volunteer",
name: "Волонтёр",
login: "vol@mail.com",
password: "vol123",
},
{
id: 3,
role: "moderator",
name: "Модератор",
login: "mod@mail.com",
password: "mod123",
},
];
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null); // {id, role, name, login}
const [loading, setLoading] = useState(true);
const router = useRouter();
// Поднимаем пользователя из localStorage, чтобы контекст сохранялся между перезагрузками
useEffect(() => {
const saved = typeof window !== "undefined" ? localStorage.getItem("authUser") : null;
if (saved) {
setUser(JSON.parse(saved));
}
setLoading(false);
}, []);
const login = async (login, password) => {
// имитация запроса на бэк
const found = USERS.find(
(u) => u.login === login && u.password === password
);
if (!found) {
throw new Error("Неверный логин или пароль");
}
const authUser = {
id: found.id,
role: found.role,
name: found.name,
login: found.login,
};
setUser(authUser);
localStorage.setItem("authUser", JSON.stringify(authUser));
// после логина перенаправляем на стартовую страницу по роли
if (found.role === "user") router.push("/home");
if (found.role === "volunteer") router.push("/mainValounter");
if (found.role === "moderator") router.push("/mainModerator");
};
const logout = () => {
setUser(null);
localStorage.removeItem("authUser");
router.push("/login");
};
const value = {
user,
loading,
isAuthenticated: !!user,
login,
logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => useContext(AuthContext);

View File

@@ -1,5 +1,6 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import "./globals.css"; import "./globals.css";
import { AuthProvider } from "../app/context/AuthContext";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Create Next App", title: "Create Next App",
@@ -14,7 +15,7 @@ export default function RootLayout({
return ( return (
<html lang="en"> <html lang="en">
<body className="antialiased"> <body className="antialiased">
{children} <AuthProvider>{children}</AuthProvider>
</body> </body>
</html> </html>
); );

View File

@@ -109,7 +109,7 @@ const MainVolunteerPage = () => {
<div className="w-8 h-8 rounded-full border border-white flex items-center justify-center"> <div className="w-8 h-8 rounded-full border border-white flex items-center justify-center">
<FaUser className="text-white text-sm" /> <FaUser className="text-white text-sm" />
</div> </div>
<p className="font-montserrat font-extrabold text-[11px] leading-[11px] text-white"> <p className="font-montserrat font-extrabold text-[20px] leading-[11px] text-white">
Александр Александр
</p> </p>
</div> </div>
@@ -121,7 +121,7 @@ const MainVolunteerPage = () => {
</button> </button>
</header> </header>
<h1 className="font-montserrat font-extrabold text-[16px] leading-[20px] text-white mb-2"> <h1 className="font-montserrat font-extrabold text-[20px] leading-[20px] text-white mb-2">
Кому нужна помощь Кому нужна помощь
</h1> </h1>
@@ -161,14 +161,14 @@ const MainVolunteerPage = () => {
className="bg-white rounded-xl px-3 py-2 flex flex-col gap-1" className="bg-white rounded-xl px-3 py-2 flex flex-col gap-1"
onClick={() => openPopup(req)} onClick={() => openPopup(req)}
> >
<p className="font-montserrat font-semibold text-[12px] leading-[14px] text-black"> <p className="font-montserrat font-semibold text-[15px] leading-[14px] text-black">
{req.title} {req.title}
</p> </p>
<p className="font-montserrat text-[10px] text-black"> <p className="font-montserrat text-[15px] text-black">
{req.address} {req.address}
</p> </p>
{req.distance && ( {req.distance && (
<p className="font-montserrat text-[9px] text-gray-500"> <p className="font-montserrat text-[12px] text-gray-500">
Расстояние: {req.distance} Расстояние: {req.distance}
</p> </p>
)} )}

View File

@@ -0,0 +1,228 @@
"use client";
import React, { useState } from "react";
import { FaBell, FaUser, FaStar } from "react-icons/fa";
import TabBar from "../components/TabBar";
import RequestDetailsModal from "../components/ValounterRequestDetailsModal";
const requests = [
{
id: 4,
title: "Приобрести продукты пенсионерке",
status: "Выполнена",
statusColor: "#71A5E9",
date: "До 28.11.2025",
time: "13:00",
createdAt: "28.11.2025",
description: "Купить продукты и принести по адресу.",
},
{
id: 5,
title: "Приобрести продукты пенсионерке",
status: "В процессе",
statusColor: "#E971E1",
date: "До 28.11.2025",
time: "13:00",
createdAt: "28.11.2025",
description: "Купить продукты и принести по адресу.",
},
{
id: 6,
title: "Приобрести продукты пенсионерке",
status: "В процессе",
statusColor: "#E971E1",
date: "До 28.11.2025",
time: "13:00",
createdAt: "28.11.2025",
description: "Купить продукты и принести по адресу.",
},
{
id: 7,
title: "Приобрести продукты пенсионерке",
status: "В процессе",
statusColor: "#E971E1",
date: "До 28.11.2025",
time: "13:00",
createdAt: "28.11.2025",
description: "Купить продукты и принести по адресу.",
},
];
const HistoryRequestPage = () => {
const [selectedRequest, setSelectedRequest] = useState(null);
const handleOpen = (req) => {
setSelectedRequest(req);
};
const handleClose = () => {
setSelectedRequest(null);
};
return (
<div className="min-h-screen w-full bg-[#90D2F9] flex justify-center px-4">
<div className="relative w-full max-w-md flex flex-col pb-20 pt-4">
{/* Header */}
<header className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full border border-white flex items-center justify-center">
<FaUser className="text-white text-sm" />
</div>
<p className="font-montserrat font-extrabold text-[20px] leading-[11px] text-white">
Александр
</p>
</div>
<button
type="button"
className="w-8 h-8 rounded-full border border-white flex items-center justify-center"
>
<FaBell className="text-white text-sm" />
</button>
</header>
<h1 className="font-montserrat font-extrabold text-[20px] leading-[22px] text-white mb-3">
История заявок
</h1>
{/* Список заявок */}
<main className="space-y-3 overflow-y-auto pr-1 max-h-[80vh]">
{requests.map((req) => (
<button
key={req.id}
type="button"
onClick={() => handleOpen(req)}
className="w-full text-left bg-white rounded-xl px-3 py-2 flex flex-col gap-1"
>
{/* верхняя строка: статус + дата/время */}
<div className="flex items-center justify-between gap-2">
<span
className="inline-flex items-center justify-center px-2 py-0.5 rounded-full font-montserrat text-[12px] font-light text-black"
style={{ backgroundColor: req.statusColor }}
>
{req.status}
</span>
<div className="text-right leading-tight">
<p className="font-montserrat text-[10px] text-black">
{req.date}
</p>
<p className="font-montserrat text-[10px] text-black">
{req.time}
</p>
</div>
</div>
{/* Заголовок заявки */}
<p className="font-montserrat font-semibold text-[15px] leading-[18px] text-black mt-1">
{req.title}
</p>
{/* Кнопка "Развернуть" */}
<div className="mt-2 w-full bg-[#94E067] rounded-lg py-3 flex items-center justify-center">
<span className="font-montserrat font-bold text-[15px] leading-[18px] text-white">
Развернуть
</span>
</div>
</button>
))}
</main>
{/* Попап */}
{selectedRequest && (
<RequestDetailsModal request={selectedRequest} onClose={handleClose} />
)}
<TabBar />
</div>
</div>
);
};
export default HistoryRequestPage;
// const RequestDetailsModal = ({ request, onClose }) => {
// const isDone = request.status === "Выполнена";
// return (
// <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/40 px-4">
// <div className="w-full max-w-sm bg-[#90D2F9] rounded-2xl p-3 relative">
// {/* Белая карточка */}
// <div className="bg-white rounded-xl p-3 flex flex-col gap-3">
// {/* Шапка попапа */}
// <div className="flex items-center justify-between mb-1">
// <button
// type="button"
// onClick={onClose}
// className="text-white bg-[#90D2F9] w-7 h-7 rounded-full flex items-center justify-center text-sm"
// >
// ←
// </button>
// <p className="flex-1 text-center font-montserrat font-extrabold text-[15px] text-white">
// Заявка от {request.createdAt}
// </p>
// <span className="w-7" />
// </div>
// {/* Статус + срок */}
// <div className="flex items-center justify-between">
// <span
// className="inline-flex items-center justify-center px-2 py-0.5 rounded-full font-montserrat text-[8px] font-light text-black"
// style={{ backgroundColor: "#71A5E9" }}
// >
// Выполнена
// </span>
// <div className="text-right leading-tight">
// <p className="font-montserrat text-[8px] text-black">
// До {request.date.replace("До ", "")}
// </p>
// <p className="font-montserrat text-[8px] text-black">
// {request.time}
// </p>
// </div>
// </div>
// {/* Название задачи */}
// <p className="font-montserrat font-semibold text-[12px] leading-[15px] text-black">
// {request.title}
// </p>
// {/* Блок отзыва */}
// {isDone && (
// <div className="bg-[#72B8E2] rounded-lg p-2 flex flex-col gap-2">
// <p className="font-montserrat font-bold text-[10px] text-white">
// Отзыв
// </p>
// <p className="font-montserrat text-[10px] text-white">
// Здесь будет текст отзыва с бэка.
// </p>
// </div>
// )}
// {/* Оценка волонтера */}
// <div className="mt-1">
// <p className="font-montserrat font-semibold text-[12px] text-black mb-1">
// Оценить волонтера
// </p>
// <div className="flex gap-1">
// {[1, 2, 3, 4, 5].map((star) => (
// <FaStar key={star} className="text-[#F6E168]" size={20} />
// ))}
// </div>
// </div>
// {/* Кнопка оставить отзыв */}
// {isDone && (
// <button
// type="button"
// className="mt-3 w-full bg-[#94E067] rounded-lg py-2 flex items-center justify-center"
// >
// <span className="font-montserrat font-bold text-[14px] text-white">
// Оставить отзыв
// </span>
// </button>
// )}
// </div>
// </div>
// </div>
// );
// };