Release 2.3.1

This commit is contained in:
2025-07-08 16:46:00 +03:00
parent bf3e231f67
commit eaf5e21ea1
11 changed files with 267 additions and 5 deletions

1
.gitignore vendored
View File

@@ -2,3 +2,4 @@ node_modules
.env .env
.env.local .env.local
.next .next
package-lock.json

View File

@@ -34,6 +34,7 @@
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-hot-toast": "^2.4.1", "react-hot-toast": "^2.4.1",
"react-icons": "^5.5.0",
"react-redux": "^9.2.0", "react-redux": "^9.2.0",
"resend": "^4.0.1", "resend": "^4.0.1",
"styled-components": "^6.1.13", "styled-components": "^6.1.13",

View File

@@ -7,6 +7,7 @@ import { getImageUrl } from '@/lib/neoApi';
import type { MovieDetails } from '@/lib/api'; import type { MovieDetails } from '@/lib/api';
import MoviePlayer from '@/components/MoviePlayer'; import MoviePlayer from '@/components/MoviePlayer';
import FavoriteButton from '@/components/FavoriteButton'; import FavoriteButton from '@/components/FavoriteButton';
import Reactions from '@/components/Reactions';
import { formatDate } from '@/lib/utils'; import { formatDate } from '@/lib/utils';
import { PlayCircle, ArrowLeft } from 'lucide-react'; import { PlayCircle, ArrowLeft } from 'lucide-react';
@@ -128,6 +129,10 @@ export default function MovieContent({ movieId, initialMovie }: MovieContentProp
/> />
</div> </div>
<div className="mt-8">
<Reactions mediaId={movie.id.toString()} mediaType="movie" />
</div>
{/* Desktop-only Embedded Player */} {/* Desktop-only Embedded Player */}
{imdbId && ( {imdbId && (
<div id="movie-player" className="mt-10 hidden md:block rounded-lg bg-secondary/50 p-4 shadow-inner"> <div id="movie-player" className="mt-10 hidden md:block rounded-lg bg-secondary/50 p-4 shadow-inner">

View File

@@ -1,9 +1,12 @@
'use client'; 'use client';
import { useAuth } from '@/hooks/useAuth'; import { useAuth } from '@/hooks/useAuth';
import { authAPI } from '@/lib/authApi';
import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Loader2, User, LogOut, Trash2 } from 'lucide-react'; import { Loader2, User, LogOut, Trash2 } from 'lucide-react';
import Modal from '@/components/ui/Modal';
export default function ProfilePage() { export default function ProfilePage() {
const { logout } = useAuth(); const { logout } = useAuth();
@@ -11,6 +14,7 @@ export default function ProfilePage() {
const [userName, setUserName] = useState<string | null>(null); const [userName, setUserName] = useState<string | null>(null);
const [userEmail, setUserEmail] = useState<string | null>(null); const [userEmail, setUserEmail] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
useEffect(() => { useEffect(() => {
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
@@ -23,9 +27,17 @@ export default function ProfilePage() {
} }
}, [router]); }, [router]);
const handleDeleteAccount = () => { const handleConfirmDelete = async () => {
// TODO: Implement account deletion logic try {
alert('Функция удаления аккаунта в разработке.'); await authAPI.deleteAccount();
toast.success('Аккаунт успешно удален.');
setIsModalOpen(false);
logout();
} catch (error) {
console.error('Failed to delete account:', error);
toast.error('Не удалось удалить аккаунт. Попробуйте снова.');
setIsModalOpen(false);
}
}; };
if (loading) { if (loading) {
@@ -62,7 +74,7 @@ export default function ProfilePage() {
<h2 className="text-xl font-bold text-red-500 mb-4">Опасная зона</h2> <h2 className="text-xl font-bold text-red-500 mb-4">Опасная зона</h2>
<p className="text-red-400 mb-6">Это действие нельзя будет отменить. Все ваши данные, включая избранное, будут удалены.</p> <p className="text-red-400 mb-6">Это действие нельзя будет отменить. Все ваши данные, включая избранное, будут удалены.</p>
<button <button
onClick={handleDeleteAccount} onClick={() => setIsModalOpen(true)}
className="w-full sm:w-auto px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 flex items-center justify-center gap-2" className="w-full sm:w-auto px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 flex items-center justify-center gap-2"
> >
<Trash2 size={20} /> <Trash2 size={20} />
@@ -70,6 +82,14 @@ export default function ProfilePage() {
</button> </button>
</div> </div>
</div> </div>
<Modal
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onConfirm={handleConfirmDelete}
title="Подтвердите удаление аккаунта"
>
<p>Вы уверены, что хотите навсегда удалить свой аккаунт? Все ваши данные, включая избранное и реакции, будут безвозвратно удалены. Это действие нельзя будет отменить.</p>
</Modal>
</div> </div>
); );
} }

View File

@@ -7,6 +7,7 @@ import { getImageUrl } from '@/lib/neoApi';
import type { TVShowDetails } from '@/lib/api'; import type { TVShowDetails } from '@/lib/api';
import MoviePlayer from '@/components/MoviePlayer'; import MoviePlayer from '@/components/MoviePlayer';
import FavoriteButton from '@/components/FavoriteButton'; import FavoriteButton from '@/components/FavoriteButton';
import Reactions from '@/components/Reactions';
import { formatDate } from '@/lib/utils'; import { formatDate } from '@/lib/utils';
import { PlayCircle, ArrowLeft } from 'lucide-react'; import { PlayCircle, ArrowLeft } from 'lucide-react';
@@ -132,6 +133,10 @@ export default function TVContent({ showId, initialShow }: TVContentProps) {
/> />
</div> </div>
<div className="mt-8">
<Reactions mediaId={show.id.toString()} mediaType="tv" />
</div>
{imdbId && ( {imdbId && (
<div id="movie-player" className="mt-10 hidden md:block rounded-lg bg-secondary/50 p-4 shadow-inner"> <div id="movie-player" className="mt-10 hidden md:block rounded-lg bg-secondary/50 p-4 shadow-inner">
<MoviePlayer <MoviePlayer

View File

@@ -1,13 +1,30 @@
'use client'; 'use client';
import { usePathname } from 'next/navigation';
import HeaderBar from './HeaderBar'; import HeaderBar from './HeaderBar';
import { Toaster } from 'react-hot-toast'; import { Toaster } from 'react-hot-toast';
import { ThemeProvider } from './ThemeProvider'; import { ThemeProvider } from './ThemeProvider';
import { useState } from 'react'; import { useState, useEffect } from 'react';
import MobileNav from './MobileNav'; import MobileNav from './MobileNav';
interface CustomWindow extends Window {
dataLayer?: any[];
}
declare const window: CustomWindow;
export function ClientLayout({ children }: { children: React.ReactNode }) { export function ClientLayout({ children }: { children: React.ReactNode }) {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const pathname = usePathname();
useEffect(() => {
if (window.dataLayer) {
window.dataLayer.push({
event: 'pageview',
page: pathname,
});
}
}, [pathname]);
return ( return (
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem={false}> <ThemeProvider attribute="class" defaultTheme="dark" enableSystem={false}>

View File

@@ -0,0 +1,130 @@
'use client';
import React, { useState, useEffect } from 'react';
import { reactionsAPI, Reaction } from '@/lib/reactionsApi';
import { toast } from 'react-hot-toast';
import cn from 'classnames';
import { formatNumber } from '@/lib/utils';
import { FaFireAlt } from 'react-icons/fa';
import { AiFillLike, AiFillDislike } from 'react-icons/ai';
import { RiEmotionNormalFill } from 'react-icons/ri';
import { MdMoodBad } from 'react-icons/md';
const reactionTypes: Reaction['type'][] = ['fire', 'nice', 'think', 'bore', 'shit'];
const reactionIcons: Record<Reaction['type'], React.ElementType> = {
fire: FaFireAlt,
nice: AiFillLike,
think: RiEmotionNormalFill,
bore: MdMoodBad,
shit: AiFillDislike,
};
interface ReactionsProps {
mediaId: string;
mediaType: 'movie' | 'tv';
}
const Reactions: React.FC<ReactionsProps> = ({ mediaId, mediaType }) => {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
const [reactionCounts, setReactionCounts] = useState<Record<string, number>>({});
const [userReaction, setUserReaction] = useState<Reaction['type'] | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchReactions = async () => {
setIsLoading(true);
try {
const [countsRes, myReactionRes] = await Promise.all([
reactionsAPI.getReactionCounts(mediaType, mediaId),
token ? reactionsAPI.getMyReaction(mediaType, mediaId) : Promise.resolve(null),
]);
setReactionCounts(countsRes.data);
if (myReactionRes?.data) {
setUserReaction(myReactionRes.data?.type ?? null);
}
} catch (error) {
console.error('Failed to fetch reactions:', error);
} finally {
setIsLoading(false);
}
};
fetchReactions();
}, [mediaId, token]);
const handleReactionClick = async (type: Reaction['type']) => {
if (!token) {
toast.error('Войдите в аккаунт, чтобы ставить реакции');
return;
}
const oldReaction = userReaction;
const oldCounts = { ...reactionCounts };
// Оптимистичное обновление
setUserReaction(prev => (prev === type ? null : type));
setReactionCounts(prev => {
const newCounts = { ...prev };
// Если снимаем реакцию
if (oldReaction === type) {
newCounts[type] = (newCounts[type] || 1) - 1;
} else {
// Если ставим новую реакцию
newCounts[type] = (newCounts[type] || 0) + 1;
// Если до этого стояла другая реакция, уменьшаем ее счетчик
if (oldReaction) {
newCounts[oldReaction] = (newCounts[oldReaction] || 1) - 1;
}
}
return newCounts;
});
try {
await reactionsAPI.setReaction(mediaType, mediaId, type);
} catch (error) {
console.error('Failed to set reaction:', error);
toast.error('Не удалось сохранить реакцию');
// Откат изменений в случае ошибки
setUserReaction(oldReaction);
setReactionCounts(oldCounts);
}
};
const renderButtons = () => (
<div className="flex items-center gap-4">
{reactionTypes.map((type) => {
const Icon = reactionIcons[type];
return (
<div key={type} className="flex flex-col items-center gap-2">
<button
onClick={() => handleReactionClick(type)}
disabled={isLoading}
className={cn(
'w-16 h-12 flex items-center justify-center text-2xl transition-all duration-200 ease-in-out rounded-lg bg-secondary hover:bg-primary/20',
{
'bg-primary/30 text-primary scale-110': userReaction === type,
'text-gray-400 hover:text-white': userReaction !== type,
}
)}
title={!token ? `Войдите, чтобы поставить реакцию` : ''}
>
<Icon />
</button>
<span className="text-sm font-medium text-gray-400">
{formatNumber(reactionCounts[type] || 0)}
</span>
</div>
);
})}
</div>
);
if (isLoading && Object.keys(reactionCounts).length === 0) {
return <div>Загрузка реакций...</div>;
}
return renderButtons();
};
export default Reactions;

View File

@@ -0,0 +1,42 @@
'use client';
import React from 'react';
interface ModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
children: React.ReactNode;
}
const Modal: React.FC<ModalProps> = ({ isOpen, onClose, onConfirm, title, children }) => {
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-75 flex justify-center items-center z-50">
<div className="bg-warm-900 rounded-lg shadow-xl p-6 w-full max-w-md mx-4">
<h2 className="text-2xl font-bold text-white mb-4">{title}</h2>
<div className="text-gray-300 mb-6">
{children}
</div>
<div className="flex justify-end gap-4">
<button
onClick={onClose}
className="px-4 py-2 rounded-lg bg-gray-700 text-white hover:bg-gray-600 transition-colors"
>
Отмена
</button>
<button
onClick={onConfirm}
className="px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-700 transition-colors"
>
Подтвердить удаление
</button>
</div>
</div>
</div>
);
};
export default Modal;

View File

@@ -12,5 +12,8 @@ export const authAPI = {
}, },
login(email: string, password: string) { login(email: string, password: string) {
return api.post('/auth/login', { email, password }); return api.post('/auth/login', { email, password });
},
deleteAccount() {
return api.delete('/auth/profile');
} }
}; };

28
src/lib/reactionsApi.ts Normal file
View File

@@ -0,0 +1,28 @@
import { api } from './api';
export interface Reaction {
_id: string;
userId: string;
mediaId: string;
mediaType: 'movie' | 'tv';
type: 'fire' | 'nice' | 'think' | 'bore' | 'shit';
createdAt: string;
}
export const reactionsAPI = {
// [PUBLIC] Получить счетчики для всех типов реакций
getReactionCounts(mediaType: string, mediaId: string): Promise<{ data: Record<string, number> }> {
return api.get(`/reactions/${mediaType}/${mediaId}/counts`);
},
// [AUTH] Получить реакцию пользователя для медиа
getMyReaction(mediaType: string, mediaId: string): Promise<{ data: Reaction | null }> {
return api.get(`/reactions/${mediaType}/${mediaId}/my-reaction`);
},
// [AUTH] Установить/обновить/удалить реакцию
setReaction(mediaType: string, mediaId: string, type: Reaction['type']): Promise<{ data: Reaction }> {
const fullMediaId = `${mediaType}_${mediaId}`;
return api.post('/reactions', { mediaId: fullMediaId, type });
},
};

View File

@@ -53,3 +53,13 @@ export const formatDate = (dateString: string | Date | undefined | null) => {
return 'Нет даты'; return 'Нет даты';
} }
}; };
export function formatNumber(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num.toString();
}